pub struct EncBuf { /* private fields */ }Expand description
Implements right_encode and left_encode.
Implementations§
Source§impl EncBuf
impl EncBuf
Sourcepub fn encode_string<'a, 'b>(&'a mut self, s: &'b [u8]) -> EncodedString<'a> ⓘwhere
'b: 'a,
pub fn encode_string<'a, 'b>(&'a mut self, s: &'b [u8]) -> EncodedString<'a> ⓘwhere
'b: 'a,
Encodes s such that it can be unambiguously encoded
from the beginning.
use tuple_hash::EncBuf;
let mut b = EncBuf::new();
let s = b.encode_string(b"hello, world!");
assert_eq!(
s.flatten().copied().collect::<Vec<_>>(),
&[
1, 104,
104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33,
],
);Sourcepub fn left_encode(&mut self, x: usize) -> &[u8] ⓘ
pub fn left_encode(&mut self, x: usize) -> &[u8] ⓘ
Encodes x as a byte string in a way that can be
unambiguously parsed from the beginning.
Sourcepub fn left_encode_bytes(&mut self, x: usize) -> &[u8] ⓘ
pub fn left_encode_bytes(&mut self, x: usize) -> &[u8] ⓘ
Encodes x*8 as a byte string in a way that can be
unambiguously parsed from the beginning.
§Rationale
left_encode is typically used to
encode a length in bits. In practice, we usually have
a length in bytes. The conversion from bytes to bits
might overflow if the number of bytes is large. This
method avoids overflowing.
§Example
use tuple_hash::EncBuf;
assert_eq!(
EncBuf::new().left_encode(8192 * 8),
EncBuf::new().left_encode_bytes(8192),
);
// usize::MAX*8 overflows, causing an incorrect result.
assert_ne!(
EncBuf::new().left_encode(usize::MAX.wrapping_mul(8)),
EncBuf::new().left_encode_bytes(usize::MAX),
);Sourcepub fn right_encode(&mut self, x: usize) -> &[u8] ⓘ
pub fn right_encode(&mut self, x: usize) -> &[u8] ⓘ
Encodes x as a byte string in a way that can be
unambiguously parsed from the end.
Sourcepub fn right_encode_bytes(&mut self, x: usize) -> &[u8] ⓘ
pub fn right_encode_bytes(&mut self, x: usize) -> &[u8] ⓘ
Encodes x*8 as a byte string in a way that can be
unambiguously parsed from the beginning.
§Rationale
right_encode is typically used to
encode a length in bits. In practice, we usually have
a length in bytes. The conversion from bytes to bits
might overflow if the number of bytes is large. This
method avoids overflowing.
§Example
use tuple_hash::EncBuf;
assert_eq!(
EncBuf::new().right_encode(8192 * 8),
EncBuf::new().right_encode_bytes(8192),
);
// usize::MAX*8 overflows, causing an incorrect result.
assert_ne!(
EncBuf::new().right_encode(usize::MAX.wrapping_mul(8)),
EncBuf::new().right_encode_bytes(usize::MAX),
);