Skip to content

Commit

Permalink
Document more (#150)
Browse files Browse the repository at this point in the history
  • Loading branch information
udoprog authored May 17, 2024
1 parent 6ea7b2f commit 3653d4a
Show file tree
Hide file tree
Showing 77 changed files with 2,079 additions and 1,588 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ struct Version2 {

let version2 = musli::wire::to_vec(&Version2 {
name: String::from("Aristotle"),
age: Some(62),
age: Some(61),
})?;

let version1: Version1 = musli::wire::decode(version2.as_slice())?;
Expand All @@ -255,7 +255,7 @@ versions.
```rust
let version2 = musli::storage::to_vec(&Version2 {
name: String::from("Aristotle"),
age: Some(62),
age: Some(61),
})?;

assert!(musli::storage::decode::<_, Version1>(version2.as_slice()).is_err());
Expand Down
2 changes: 2 additions & 0 deletions crates/musli-core/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ pub trait Context {
T: ?Sized + fmt::Display;

/// Generate a map function which maps an error using the `custom` function.
#[inline]
fn map<T>(&self) -> impl FnOnce(T) -> Self::Error + '_
where
T: 'static + Send + Sync + no_std::Error,
Expand All @@ -96,6 +97,7 @@ pub trait Context {
T: 'static + Send + Sync + no_std::Error;

/// Generate a map function which maps an error using the `message` function.
#[inline]
fn map_message<T>(&self) -> impl FnOnce(T) -> Self::Error + '_
where
T: fmt::Display,
Expand Down
4 changes: 2 additions & 2 deletions crates/musli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ struct Version2 {

let version2 = musli::wire::to_vec(&Version2 {
name: String::from("Aristotle"),
age: Some(62),
age: Some(61),
})?;

let version1: Version1 = musli::wire::decode(version2.as_slice())?;
Expand All @@ -255,7 +255,7 @@ versions.
```rust
let version2 = musli::storage::to_vec(&Version2 {
name: String::from("Aristotle"),
age: Some(62),
age: Some(61),
})?;

assert!(musli::storage::decode::<_, Version1>(version2.as_slice()).is_err());
Expand Down
27 changes: 17 additions & 10 deletions crates/musli/src/allocator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
//! ```
//! use musli::{Allocator, Buf};
//!
//! musli::default_allocator!(|alloc| {
//! musli::allocator::default!(|alloc| {
//! let mut a = alloc.alloc().expect("allocation a failed");
//! let mut b = alloc.alloc().expect("allocation b failed");
//!
Expand Down Expand Up @@ -58,10 +58,18 @@ mod stack;
pub use self::stack::{Stack, StackBuffer};

/// The default stack buffer size for the default allocator provided through
/// [`default_allocator!`][crate::default_allocator].
/// [`default!`].
pub const DEFAULT_STACK_BUFFER: usize = 4096;

/// Call the given block with the default allocator.
#[macro_export]
#[doc(hidden)]
macro_rules! __default {
(|$alloc:ident| $body:block) => {
$crate::allocator::__default_allocator_impl!(|$alloc| $body)
};
}

/// Call the given block `$body` with the default allocator.
///
/// This is useful if you want to write application which are agnostic to
/// whether the `alloc` feature is or isn't enabled.
Expand All @@ -75,7 +83,7 @@ pub const DEFAULT_STACK_BUFFER: usize = 4096;
/// ```
/// use musli::{Allocator, Buf};
///
/// musli::default_allocator!(|alloc| {
/// musli::allocator::default!(|alloc| {
/// let mut a = alloc.alloc().expect("allocation a failed");
/// let mut b = alloc.alloc().expect("allocation b failed");
///
Expand All @@ -98,12 +106,8 @@ pub const DEFAULT_STACK_BUFFER: usize = 4096;
/// assert_eq!(a.len(), 12);
/// });
/// ```
#[macro_export]
macro_rules! default_allocator {
(|$alloc:ident| $body:block) => {
$crate::__default_allocator_impl!(|$alloc| $body)
};
}
#[doc(inline)]
pub use __default as default;

#[cfg(feature = "alloc")]
#[macro_export]
Expand All @@ -126,3 +130,6 @@ macro_rules! __default_allocator_impl {
$body
}};
}

#[doc(hidden)]
pub use __default_allocator_impl;
6 changes: 5 additions & 1 deletion crates/musli/src/allocator/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ use alloc::vec::Vec;
use crate::buf::Error;
use crate::{Allocator, Buf};

/// Buffer used in combination with an [`Allocator`].
/// System buffer that can be used in combination with an [`Allocator`].
///
/// This uses the [`System`] allocator.
///
/// [`System` allocator]: https://doc.rust-lang.org/std/alloc/struct.System.html
pub struct System {
internal: UnsafeCell<Internal>,
}
Expand Down
2 changes: 1 addition & 1 deletion crates/musli/src/descriptive/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ where
{
let cx = self.cx;

let Some(tag) = self.reader.peek(cx)?.map(Tag::from_byte) else {
let Some(tag) = self.reader.peek().map(Tag::from_byte) else {
return Err(cx.message("Expected tag in input"));
};

Expand Down
88 changes: 10 additions & 78 deletions crates/musli/src/descriptive/encoding.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
//! Module that defines [`Encoding`] whith allows for customization of the
//! encoding format, and the [`DEFAULT`] encoding configuration.
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::marker;
#[cfg(feature = "std")]
use std::io;

use crate::de::Decode;
use crate::en::Encode;
use crate::mode::Binary;
use crate::options;
use crate::Context;
use crate::{FixedBytes, Options, Reader, Writer};
use crate::{IntoReader, Options};

use super::de::SelfDecoder;
use super::en::SelfEncoder;
Expand All @@ -32,69 +25,7 @@ pub const OPTIONS: options::Options = options::new().build();
/// [`variable length`]: https://en.wikipedia.org/wiki/Variable-length_quantity
pub const DEFAULT: Encoding = Encoding::new();

/// Encode the given value to the given [`Writer`] using the [`DEFAULT`]
/// configuration.
#[inline]
pub fn encode<W, T>(writer: W, value: &T) -> Result<(), Error>
where
W: Writer,
T: ?Sized + Encode<Binary>,
{
DEFAULT.encode(writer, value)
}

/// Encode the given value to the given [Write][io::Write] using the [`DEFAULT`]
/// configuration.
#[cfg(feature = "std")]
#[inline]
pub fn to_writer<W, T>(writer: W, value: &T) -> Result<(), Error>
where
W: io::Write,
T: ?Sized + Encode<Binary>,
{
DEFAULT.to_writer(writer, value)
}

/// Encode the given value to a [Vec] using the [`DEFAULT`] configuration.
#[cfg(feature = "alloc")]
#[inline]
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>, Error>
where
T: ?Sized + Encode<Binary>,
{
DEFAULT.to_vec(value)
}

/// Encode the given value to a fixed-size bytes using the [`DEFAULT`]
/// configuration.
#[inline]
pub fn to_fixed_bytes<const N: usize, T>(value: &T) -> Result<FixedBytes<N>, Error>
where
T: ?Sized + Encode<Binary>,
{
DEFAULT.to_fixed_bytes::<N, _>(value)
}

/// Decode the given type `T` from the given [`Reader`] using the [`DEFAULT`]
/// configuration.
#[inline]
pub fn decode<'de, R, T>(reader: R) -> Result<T, Error>
where
R: Reader<'de>,
T: Decode<'de, Binary>,
{
DEFAULT.decode(reader)
}

/// Decode the given type `T` from the given slice using the [`DEFAULT`]
/// configuration.
#[inline]
pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T, Error>
where
T: Decode<'de, Binary>,
{
DEFAULT.from_slice(bytes)
}
crate::macros::bare_encoding!(Binary, DEFAULT, descriptive, IntoReader);

/// Setting up encoding with parameters.
pub struct Encoding<const OPT: Options = OPTIONS, M = Binary> {
Expand All @@ -112,21 +43,21 @@ impl Encoding<OPTIONS, Binary> {
/// Construct a new [`Encoding`] instance.
///
/// ```
/// use musli::descriptive::{Encoding};
/// use musli::{Encode, Decode};
/// use musli::descriptive::Encoding;
/// # use musli::descriptive::Error;
///
/// const CONFIG: Encoding = Encoding::new();
///
/// #[derive(Debug, PartialEq, Encode, Decode)]
/// struct Struct<'a> {
/// struct Person<'a> {
/// name: &'a str,
/// age: u32,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut out = Vec::new();
///
/// let expected = Struct {
/// let expected = Person {
/// name: "Aristotle",
/// age: 61,
/// };
Expand All @@ -135,7 +66,7 @@ impl Encoding<OPTIONS, Binary> {
/// let actual = CONFIG.decode(&out[..])?;
///
/// assert_eq!(expected, actual);
/// # Ok(()) }
/// # Ok::<_, Error>(())
/// ```
pub const fn new() -> Self {
Encoding {
Expand Down Expand Up @@ -179,11 +110,12 @@ impl<const OPT: Options, M> Encoding<OPT, M> {
}
}

crate::encoding_impls!(
crate::macros::encoding_impls!(
M,
descriptive,
SelfEncoder::<_, OPT, _>::new,
SelfDecoder::<_, OPT, _>::new
SelfDecoder::<_, OPT, _>::new,
IntoReader::into_reader,
);
}

Expand Down
6 changes: 3 additions & 3 deletions crates/musli/src/descriptive/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
//!
//! let version2 = musli::descriptive::to_vec(&Version2 {
//! name: String::from("Aristotle"),
//! age: Some(62),
//! age: Some(61),
//! })?;
//!
//! let version1: Version1 = musli::descriptive::decode(version2.as_slice())?;
Expand All @@ -60,14 +60,14 @@
//! const CONFIG: Encoding = Encoding::new();
//!
//! #[derive(Debug, PartialEq, Encode, Decode)]
//! struct Struct<'a> {
//! struct Person<'a> {
//! name: &'a str,
//! age: u32,
//! }
//!
//! let mut out = Vec::new();
//!
//! let expected = Struct {
//! let expected = Person {
//! name: "Aristotle",
//! age: 61,
//! };
Expand Down
2 changes: 1 addition & 1 deletion crates/musli/src/descriptive/test.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
//! Helpers for writing tests.
crate::test_fns!("descriptive", crate::mode::Binary, #[musli_value]);
crate::macros::test_fns!(Binary, "descriptive", #[musli_value]);
4 changes: 2 additions & 2 deletions crates/musli/src/help/derives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@
//! const TEXT: Encoding = Encoding::new();
//! const BINARY: Encoding<Binary> = Encoding::new().with_mode();
//!
//! let named = TEXT.to_vec(&Person { not_name: "Aristotle", age: 62 })?;
//! assert_eq!(named.as_slice(), br#"{"name":"Aristotle","age":62}"#);
//! let named = TEXT.to_vec(&Person { not_name: "Aristotle", age: 61 })?;
//! assert_eq!(named.as_slice(), br#"{"name":"Aristotle","age":61}"#);
//!
//! let indexed = BINARY.to_vec(&Person { not_name: "Plato", age: 84 })?;
//! assert_eq!(indexed.as_slice(), br#"{"0":"Plato","1":84}"#);
Expand Down
5 changes: 3 additions & 2 deletions crates/musli/src/int/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ where
crate::options::Integer::Variable => c::encode(cx, writer, value),
_ => {
let bo = crate::options::byteorder::<OPT>();

macro_rules! fixed {
($ty:ty) => {{
let Ok(value) = <$ty>::try_from(value) else {
Expand All @@ -110,7 +111,7 @@ where
}};
}

crate::width_arm!(crate::options::length_width::<OPT>(), fixed)
crate::options::width_arm!(crate::options::length_width::<OPT>(), fixed)
}
}
}
Expand Down Expand Up @@ -139,7 +140,7 @@ where
}};
}

crate::width_arm!(crate::options::length_width::<OPT>(), fixed)
crate::options::width_arm!(crate::options::length_width::<OPT>(), fixed)
}
}
}
6 changes: 3 additions & 3 deletions crates/musli/src/int/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const ITER: usize = 100;

#[test]
fn basic_continuation() {
crate::default_allocator!(|alloc| {
crate::allocator::default!(|alloc| {
let cx = context::Ignore::marker(&alloc);
let mut bytes = FixedBytes::<8>::new();
c::encode(&cx, &mut bytes, 5000u32).unwrap();
Expand All @@ -36,7 +36,7 @@ fn test_continuation_encoding() {
where
T: PartialEq<T> + fmt::Debug + Unsigned,
{
crate::default_allocator!(|alloc| {
crate::allocator::default!(|alloc| {
let mut out = Vec::new();
let cx = crate::context::Ignore::marker(&alloc);
c::encode(&cx, &mut out, expected).unwrap();
Expand All @@ -55,7 +55,7 @@ fn test_continuation_encoding() {
where
T: Unsigned,
{
crate::default_allocator!(|alloc| {
crate::allocator::default!(|alloc| {
let mut out = Vec::new();
let cx = crate::context::Same::marker(&alloc);
c::encode(&cx, crate::wrap::wrap(&mut out), value).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion crates/musli/src/json/de/key_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ where
where
V: Visitor<'de, C>,
{
match self.parser.peek(self.cx)? {
match self.parser.lex(self.cx) {
Token::String => {
let visitor = visitor.visit_string(self.cx, SizeHint::any())?;
self.decode_string(visitor)
Expand Down
Loading

0 comments on commit 3653d4a

Please sign in to comment.