Skip to main content

IntoBuf

Trait IntoBuf 

Source
pub trait IntoBuf {
    type Buf: Buf;

    // Required method
    fn into_buf(self) -> Self::Buf;
}
Expand description

Conversion into a Buf.

By implementing IntoBuf for a type, you define how it will be converted into a Buf. This conversion is useful for types that represent valid UTF-8 byte sequences, whether or not all the bytes are contiguous in memory.

All implementations must respect the Buf invariant, namely that the new Buf produced by a call to into_buf must yield a valid UTF-8 byte sequence if read from beginning to end.

§Examples

Basic usage:

use bufjson::{Buf, IntoBuf};

let s = "hello, world";
let mut buf = s.into_buf();

assert_eq!(12, buf.remaining());
assert_eq!(b"hello, world", buf.chunk());

buf.advance(7);

let mut dst = [0; 5];
buf.copy_to_slice(&mut dst);
assert_eq!(b"world", &dst);

You can use IntoBuf as a trait bound. This allows the input type to change, so long as it can still be converted into a Buf. Additional bounds can be specified by restricting on Buf:

use bufjson::{Buf, IntoBuf};

fn collect_as_string<T>(input: T) -> String
where
    T: IntoBuf,
    T::Buf: std::fmt::Debug,
{
    let buf = input.into_buf();
    let mut v = Vec::with_capacity(buf.remaining());
    while buf.remaining() > 0 {
        v.copy_from_slice(buf.chunk());
    }

    v.try_into()
        .expect("input must satisfy Buf invariant")
}

Required Associated Types§

Required Methods§

Source

fn into_buf(self) -> Self::Buf

Converts self into a Buf.

Implementations on Foreign Types§

Source§

impl IntoBuf for String

Source§

type Buf = StringBuf

Source§

fn into_buf(self) -> Self::Buf

Source§

impl<'a> IntoBuf for &'a str

Source§

type Buf = &'a [u8]

Source§

fn into_buf(self) -> Self::Buf

Implementors§

Source§

impl IntoBuf for Literal

Available on crate feature read only.
Source§

impl<T: IntoBuf> IntoBuf for Unescaped<T>