Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ su dependencia.
### Capítulo 08: zero-copy, buffers y serialización

- [x] #24 Especificar préstamos, buffers, parsing y costo de copias.
- [ ] #25 Implementar y probar parsing basado en slices y buffers.
- [x] #25 Implementar y probar parsing basado en slices y buffers.
- [ ] #26 Escribir capítulo, diagrama, ejemplos, ejercicios y benchmarks.

### Capítulo 09: SIMD y límites de vectorización
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod layout;
pub mod locality;
pub mod measurement;
pub mod profile;
pub mod zero_copy;

/// Devuelve la identidad del curso para comprobar la fundación del crate.
#[must_use]
Expand Down
27 changes: 27 additions & 0 deletions src/zero_copy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//! Parsing equivalente con datos prestados o propietarios.

/// Error al interpretar un segmento de pares clave-valor.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ParseError {
/// El segmento no contiene el separador `=`.
MissingSeparator,
}

/// Interpreta pares `clave=valor` sin copiar sus fragmentos.
pub fn parse_borrowed(input: &str) -> Result<Vec<(&str, &str)>, ParseError> {
input
.split(';')
.filter(|segment| !segment.is_empty())
.map(|segment| segment.split_once('=').ok_or(ParseError::MissingSeparator))
.collect()
}

/// Interpreta el mismo formato y crea una representación propietaria.
pub fn parse_owned(input: &str) -> Result<Vec<(String, String)>, ParseError> {
parse_borrowed(input).map(|pairs| {
pairs
.into_iter()
.map(|(key, value)| (key.to_owned(), value.to_owned()))
.collect()
})
}
24 changes: 24 additions & 0 deletions tests/zero_copy_parser.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use rust_performance::zero_copy::{parse_borrowed, parse_owned, ParseError};

#[test]
fn borrowed_and_owned_parsers_preserve_the_same_pairs() {
let borrowed = parse_borrowed("lang=rust;mode=release").expect("valid input");
let owned = parse_owned("lang=rust;mode=release").expect("valid input");

assert_eq!(borrowed, [("lang", "rust"), ("mode", "release")]);
assert_eq!(
owned,
[
(String::from("lang"), String::from("rust")),
(String::from("mode"), String::from("release"))
]
);
}

#[test]
fn parser_rejects_segments_without_an_equals_sign() {
assert_eq!(
parse_borrowed("lang=rust;invalid"),
Err(ParseError::MissingSeparator)
);
}
Loading