Make spanned module private and hide internals

This commit is contained in:
John-John Tedro 2018-05-09 21:26:59 +02:00
parent 44ecae9bfb
commit 0616d3562c
3 changed files with 44 additions and 10 deletions

View file

@ -170,6 +170,6 @@ mod tokens;
#[doc(hidden)] #[doc(hidden)]
pub mod macros; pub mod macros;
pub mod spanned; mod spanned;
#[doc(no_inline)] #[doc(no_inline)]
pub use spanned::Spanned; pub use spanned::Spanned;

View file

@ -3,7 +3,7 @@
//! extern crate serde_derive; //! extern crate serde_derive;
//! //!
//! extern crate toml; //! extern crate toml;
//! use toml::spanned::Spanned; //! use toml::Spanned;
//! //!
//! #[derive(Deserialize)] //! #[derive(Deserialize)]
//! struct Value { //! struct Value {
@ -15,8 +15,10 @@
//! //!
//! let u: Value = toml::from_str(t).unwrap(); //! let u: Value = toml::from_str(t).unwrap();
//! //!
//! assert_eq!(u.s.start, 4); //! assert_eq!(u.s.start(), 4);
//! assert_eq!(u.s.end, 11); //! assert_eq!(u.s.end(), 11);
//! assert_eq!(u.s.get_ref(), "value");
//! assert_eq!(u.s.into_inner(), String::from("value"));
//! } //! }
//! ``` //! ```
@ -36,11 +38,43 @@ pub const VALUE: &'static str = "$__toml_private_value";
#[derive(Debug)] #[derive(Debug)]
pub struct Spanned<T> { pub struct Spanned<T> {
/// The start range. /// The start range.
pub start: usize, start: usize,
/// The end range (exclusive). /// The end range (exclusive).
pub end: usize, end: usize,
/// The spanned value. /// The spanned value.
pub value: T, value: T,
}
impl<T> Spanned<T> {
/// Access the start of the span of the contained value.
pub fn start(&self) -> usize {
self.start
}
/// Access the end of the span of the contained value.
pub fn end(&self) -> usize {
self.end
}
/// Get the span of the contained value.
pub fn span(&self) -> (usize, usize) {
(self.start, self.end)
}
/// Consumes the spanned value and returns the contained value.
pub fn into_inner(self) -> T {
self.value
}
/// Returns a reference to the contained value.
pub fn get_ref(&self) -> &T {
&self.value
}
/// Returns a mutable reference to the contained value.
pub fn get_mut(&self) -> &T {
&self.value
}
} }
impl<'de, T> de::Deserialize<'de> for Spanned<T> impl<'de, T> de::Deserialize<'de> for Spanned<T>

View file

@ -34,9 +34,9 @@ fn test_spanned_field() {
fn good<'de, T>(s: &'de str, expected: &str) where T: serde::Deserialize<'de> { fn good<'de, T>(s: &'de str, expected: &str) where T: serde::Deserialize<'de> {
let foo: Foo<T> = toml::from_str(s).unwrap(); let foo: Foo<T> = toml::from_str(s).unwrap();
assert_eq!(6, foo.foo.start); assert_eq!(6, foo.foo.start());
assert_eq!(s.len(), foo.foo.end); assert_eq!(s.len(), foo.foo.end());
assert_eq!(expected, &s[foo.foo.start..foo.foo.end]); assert_eq!(expected, &s[foo.foo.start()..foo.foo.end()]);
} }
good::<String>("foo = \"foo\"", "\"foo\""); good::<String>("foo = \"foo\"", "\"foo\"");