1 use crate::leb128::{self, max_leb128_len};
2 use crate::serialize::{self, Encoder as _};
4 use std::convert::TryInto;
6 use std::io::{self, Write};
7 use std::mem::MaybeUninit;
11 // -----------------------------------------------------------------------------
13 // -----------------------------------------------------------------------------
15 pub type EncodeResult = Result<(), !>;
22 pub fn new(data: Vec<u8>) -> Encoder {
26 pub fn into_inner(self) -> Vec<u8> {
31 pub fn position(&self) -> usize {
36 macro_rules! write_leb128 {
37 ($enc:expr, $value:expr, $int_ty:ty, $fun:ident) => {{
38 const MAX_ENCODED_LEN: usize = max_leb128_len!($int_ty);
39 let old_len = $enc.data.len();
41 if MAX_ENCODED_LEN > $enc.data.capacity() - old_len {
42 $enc.data.reserve(MAX_ENCODED_LEN);
45 // SAFETY: The above check and `reserve` ensures that there is enough
46 // room to write the encoded value to the vector's internal buffer.
48 let buf = &mut *($enc.data.as_mut_ptr().add(old_len)
49 as *mut [MaybeUninit<u8>; MAX_ENCODED_LEN]);
50 let encoded = leb128::$fun(buf, $value);
51 $enc.data.set_len(old_len + encoded.len());
58 /// A byte that [cannot occur in UTF8 sequences][utf8]. Used to mark the end of a string.
59 /// This way we can skip validation and still be relatively sure that deserialization
60 /// did not desynchronize.
62 /// [utf8]: https://en.wikipedia.org/w/index.php?title=UTF-8&oldid=1058865525#Codepage_layout
63 const STR_SENTINEL: u8 = 0xC1;
65 impl serialize::Encoder for Encoder {
69 fn emit_unit(&mut self) -> EncodeResult {
74 fn emit_usize(&mut self, v: usize) -> EncodeResult {
75 write_leb128!(self, v, usize, write_usize_leb128)
79 fn emit_u128(&mut self, v: u128) -> EncodeResult {
80 write_leb128!(self, v, u128, write_u128_leb128)
84 fn emit_u64(&mut self, v: u64) -> EncodeResult {
85 write_leb128!(self, v, u64, write_u64_leb128)
89 fn emit_u32(&mut self, v: u32) -> EncodeResult {
90 write_leb128!(self, v, u32, write_u32_leb128)
94 fn emit_u16(&mut self, v: u16) -> EncodeResult {
95 write_leb128!(self, v, u16, write_u16_leb128)
99 fn emit_u8(&mut self, v: u8) -> EncodeResult {
105 fn emit_isize(&mut self, v: isize) -> EncodeResult {
106 write_leb128!(self, v, isize, write_isize_leb128)
110 fn emit_i128(&mut self, v: i128) -> EncodeResult {
111 write_leb128!(self, v, i128, write_i128_leb128)
115 fn emit_i64(&mut self, v: i64) -> EncodeResult {
116 write_leb128!(self, v, i64, write_i64_leb128)
120 fn emit_i32(&mut self, v: i32) -> EncodeResult {
121 write_leb128!(self, v, i32, write_i32_leb128)
125 fn emit_i16(&mut self, v: i16) -> EncodeResult {
126 write_leb128!(self, v, i16, write_i16_leb128)
130 fn emit_i8(&mut self, v: i8) -> EncodeResult {
131 let as_u8: u8 = unsafe { std::mem::transmute(v) };
136 fn emit_bool(&mut self, v: bool) -> EncodeResult {
137 self.emit_u8(if v { 1 } else { 0 })
141 fn emit_f64(&mut self, v: f64) -> EncodeResult {
142 let as_u64: u64 = v.to_bits();
143 self.emit_u64(as_u64)
147 fn emit_f32(&mut self, v: f32) -> EncodeResult {
148 let as_u32: u32 = v.to_bits();
149 self.emit_u32(as_u32)
153 fn emit_char(&mut self, v: char) -> EncodeResult {
154 self.emit_u32(v as u32)
158 fn emit_str(&mut self, v: &str) -> EncodeResult {
159 self.emit_usize(v.len())?;
160 self.emit_raw_bytes(v.as_bytes())?;
161 self.emit_u8(STR_SENTINEL)
165 fn emit_raw_bytes(&mut self, s: &[u8]) -> EncodeResult {
166 self.data.extend_from_slice(s);
171 pub type FileEncodeResult = Result<(), io::Error>;
173 // `FileEncoder` encodes data to file via fixed-size buffer.
175 // When encoding large amounts of data to a file, using `FileEncoder` may be
176 // preferred over using `Encoder` to encode to a `Vec`, and then writing the
177 // `Vec` to file, as the latter uses as much memory as there is encoded data,
178 // while the former uses the fixed amount of memory allocated to the buffer.
179 // `FileEncoder` also has the advantage of not needing to reallocate as data
180 // is appended to it, but the disadvantage of requiring more error handling,
181 // which has some runtime overhead.
182 pub struct FileEncoder {
183 // The input buffer. For adequate performance, we need more control over
184 // buffering than `BufWriter` offers. If `BufWriter` ever offers a raw
185 // buffer access API, we can use it, and remove `buf` and `buffered`.
186 buf: Box<[MaybeUninit<u8>]>,
193 pub fn new<P: AsRef<Path>>(path: P) -> io::Result<Self> {
194 const DEFAULT_BUF_SIZE: usize = 8192;
195 FileEncoder::with_capacity(path, DEFAULT_BUF_SIZE)
198 pub fn with_capacity<P: AsRef<Path>>(path: P, capacity: usize) -> io::Result<Self> {
199 // Require capacity at least as large as the largest LEB128 encoding
200 // here, so that we don't have to check or handle this on every write.
201 assert!(capacity >= max_leb128_len());
203 // Require capacity small enough such that some capacity checks can be
204 // done using guaranteed non-overflowing add rather than sub, which
205 // shaves an instruction off those code paths (on x86 at least).
206 assert!(capacity <= usize::MAX - max_leb128_len());
208 let file = File::create(path)?;
210 Ok(FileEncoder { buf: Box::new_uninit_slice(capacity), buffered: 0, flushed: 0, file })
214 pub fn position(&self) -> usize {
215 // Tracking position this way instead of having a `self.position` field
216 // means that we don't have to update the position on every write call.
217 self.flushed + self.buffered
220 pub fn flush(&mut self) -> FileEncodeResult {
221 // This is basically a copy of `BufWriter::flush`. If `BufWriter` ever
222 // offers a raw buffer access API, we can use it, and remove this.
224 /// Helper struct to ensure the buffer is updated after all the writes
225 /// are complete. It tracks the number of written bytes and drains them
226 /// all from the front of the buffer when dropped.
227 struct BufGuard<'a> {
228 buffer: &'a mut [u8],
229 encoder_buffered: &'a mut usize,
230 encoder_flushed: &'a mut usize,
234 impl<'a> BufGuard<'a> {
236 buffer: &'a mut [u8],
237 encoder_buffered: &'a mut usize,
238 encoder_flushed: &'a mut usize,
240 assert_eq!(buffer.len(), *encoder_buffered);
241 Self { buffer, encoder_buffered, encoder_flushed, flushed: 0 }
244 /// The unwritten part of the buffer
245 fn remaining(&self) -> &[u8] {
246 &self.buffer[self.flushed..]
249 /// Flag some bytes as removed from the front of the buffer
250 fn consume(&mut self, amt: usize) {
254 /// true if all of the bytes have been written
255 fn done(&self) -> bool {
256 self.flushed >= *self.encoder_buffered
260 impl Drop for BufGuard<'_> {
262 if self.flushed > 0 {
264 *self.encoder_flushed += *self.encoder_buffered;
265 *self.encoder_buffered = 0;
267 self.buffer.copy_within(self.flushed.., 0);
268 *self.encoder_flushed += self.flushed;
269 *self.encoder_buffered -= self.flushed;
275 let mut guard = BufGuard::new(
276 unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf[..self.buffered]) },
281 while !guard.done() {
282 match self.file.write(guard.remaining()) {
284 return Err(io::Error::new(
285 io::ErrorKind::WriteZero,
286 "failed to write the buffered data",
289 Ok(n) => guard.consume(n),
290 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
291 Err(e) => return Err(e),
299 fn capacity(&self) -> usize {
304 fn write_one(&mut self, value: u8) -> FileEncodeResult {
305 // We ensure this during `FileEncoder` construction.
306 debug_assert!(self.capacity() >= 1);
308 let mut buffered = self.buffered;
310 if std::intrinsics::unlikely(buffered >= self.capacity()) {
315 // SAFETY: The above check and `flush` ensures that there is enough
316 // room to write the input to the buffer.
318 *MaybeUninit::slice_as_mut_ptr(&mut self.buf).add(buffered) = value;
321 self.buffered = buffered + 1;
327 fn write_all(&mut self, buf: &[u8]) -> FileEncodeResult {
328 let capacity = self.capacity();
329 let buf_len = buf.len();
331 if std::intrinsics::likely(buf_len <= capacity) {
332 let mut buffered = self.buffered;
334 if std::intrinsics::unlikely(buf_len > capacity - buffered) {
339 // SAFETY: The above check and `flush` ensures that there is enough
340 // room to write the input to the buffer.
342 let src = buf.as_ptr();
343 let dst = MaybeUninit::slice_as_mut_ptr(&mut self.buf).add(buffered);
344 ptr::copy_nonoverlapping(src, dst, buf_len);
347 self.buffered = buffered + buf_len;
351 self.write_all_unbuffered(buf)
355 fn write_all_unbuffered(&mut self, mut buf: &[u8]) -> FileEncodeResult {
356 if self.buffered > 0 {
360 // This is basically a copy of `Write::write_all` but also updates our
361 // `self.flushed`. It's necessary because `Write::write_all` does not
362 // return the number of bytes written when an error is encountered, and
363 // without that, we cannot accurately update `self.flushed` on error.
364 while !buf.is_empty() {
365 match self.file.write(buf) {
367 return Err(io::Error::new(
368 io::ErrorKind::WriteZero,
369 "failed to write whole buffer",
376 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
377 Err(e) => return Err(e),
385 impl Drop for FileEncoder {
387 let _result = self.flush();
391 macro_rules! file_encoder_write_leb128 {
392 ($enc:expr, $value:expr, $int_ty:ty, $fun:ident) => {{
393 const MAX_ENCODED_LEN: usize = max_leb128_len!($int_ty);
395 // We ensure this during `FileEncoder` construction.
396 debug_assert!($enc.capacity() >= MAX_ENCODED_LEN);
398 let mut buffered = $enc.buffered;
400 // This can't overflow. See assertion in `FileEncoder::with_capacity`.
401 if std::intrinsics::unlikely(buffered + MAX_ENCODED_LEN > $enc.capacity()) {
406 // SAFETY: The above check and flush ensures that there is enough
407 // room to write the encoded value to the buffer.
409 &mut *($enc.buf.as_mut_ptr().add(buffered) as *mut [MaybeUninit<u8>; MAX_ENCODED_LEN])
412 let encoded = leb128::$fun(buf, $value);
413 $enc.buffered = buffered + encoded.len();
419 impl serialize::Encoder for FileEncoder {
420 type Error = io::Error;
423 fn emit_unit(&mut self) -> FileEncodeResult {
428 fn emit_usize(&mut self, v: usize) -> FileEncodeResult {
429 file_encoder_write_leb128!(self, v, usize, write_usize_leb128)
433 fn emit_u128(&mut self, v: u128) -> FileEncodeResult {
434 file_encoder_write_leb128!(self, v, u128, write_u128_leb128)
438 fn emit_u64(&mut self, v: u64) -> FileEncodeResult {
439 file_encoder_write_leb128!(self, v, u64, write_u64_leb128)
443 fn emit_u32(&mut self, v: u32) -> FileEncodeResult {
444 file_encoder_write_leb128!(self, v, u32, write_u32_leb128)
448 fn emit_u16(&mut self, v: u16) -> FileEncodeResult {
449 file_encoder_write_leb128!(self, v, u16, write_u16_leb128)
453 fn emit_u8(&mut self, v: u8) -> FileEncodeResult {
458 fn emit_isize(&mut self, v: isize) -> FileEncodeResult {
459 file_encoder_write_leb128!(self, v, isize, write_isize_leb128)
463 fn emit_i128(&mut self, v: i128) -> FileEncodeResult {
464 file_encoder_write_leb128!(self, v, i128, write_i128_leb128)
468 fn emit_i64(&mut self, v: i64) -> FileEncodeResult {
469 file_encoder_write_leb128!(self, v, i64, write_i64_leb128)
473 fn emit_i32(&mut self, v: i32) -> FileEncodeResult {
474 file_encoder_write_leb128!(self, v, i32, write_i32_leb128)
478 fn emit_i16(&mut self, v: i16) -> FileEncodeResult {
479 file_encoder_write_leb128!(self, v, i16, write_i16_leb128)
483 fn emit_i8(&mut self, v: i8) -> FileEncodeResult {
484 let as_u8: u8 = unsafe { std::mem::transmute(v) };
489 fn emit_bool(&mut self, v: bool) -> FileEncodeResult {
490 self.emit_u8(if v { 1 } else { 0 })
494 fn emit_f64(&mut self, v: f64) -> FileEncodeResult {
495 let as_u64: u64 = v.to_bits();
496 self.emit_u64(as_u64)
500 fn emit_f32(&mut self, v: f32) -> FileEncodeResult {
501 let as_u32: u32 = v.to_bits();
502 self.emit_u32(as_u32)
506 fn emit_char(&mut self, v: char) -> FileEncodeResult {
507 self.emit_u32(v as u32)
511 fn emit_str(&mut self, v: &str) -> FileEncodeResult {
512 self.emit_usize(v.len())?;
513 self.emit_raw_bytes(v.as_bytes())?;
514 self.emit_u8(STR_SENTINEL)
518 fn emit_raw_bytes(&mut self, s: &[u8]) -> FileEncodeResult {
523 // -----------------------------------------------------------------------------
525 // -----------------------------------------------------------------------------
527 pub struct Decoder<'a> {
532 impl<'a> Decoder<'a> {
534 pub fn new(data: &'a [u8], position: usize) -> Decoder<'a> {
535 Decoder { data, position }
539 pub fn position(&self) -> usize {
544 pub fn set_position(&mut self, pos: usize) {
549 pub fn advance(&mut self, bytes: usize) {
550 self.position += bytes;
554 pub fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] {
555 let start = self.position;
556 self.position += bytes;
557 &self.data[start..self.position]
561 macro_rules! read_leb128 {
562 ($dec:expr, $fun:ident) => {{
563 let (value, bytes_read) = leb128::$fun(&$dec.data[$dec.position..]);
564 $dec.position += bytes_read;
569 impl<'a> serialize::Decoder for Decoder<'a> {
573 fn read_nil(&mut self) -> Result<(), Self::Error> {
578 fn read_u128(&mut self) -> Result<u128, Self::Error> {
579 read_leb128!(self, read_u128_leb128)
583 fn read_u64(&mut self) -> Result<u64, Self::Error> {
584 read_leb128!(self, read_u64_leb128)
588 fn read_u32(&mut self) -> Result<u32, Self::Error> {
589 read_leb128!(self, read_u32_leb128)
593 fn read_u16(&mut self) -> Result<u16, Self::Error> {
594 read_leb128!(self, read_u16_leb128)
598 fn read_u8(&mut self) -> Result<u8, Self::Error> {
599 let value = self.data[self.position];
605 fn read_usize(&mut self) -> Result<usize, Self::Error> {
606 read_leb128!(self, read_usize_leb128)
610 fn read_i128(&mut self) -> Result<i128, Self::Error> {
611 read_leb128!(self, read_i128_leb128)
615 fn read_i64(&mut self) -> Result<i64, Self::Error> {
616 read_leb128!(self, read_i64_leb128)
620 fn read_i32(&mut self) -> Result<i32, Self::Error> {
621 read_leb128!(self, read_i32_leb128)
625 fn read_i16(&mut self) -> Result<i16, Self::Error> {
626 read_leb128!(self, read_i16_leb128)
630 fn read_i8(&mut self) -> Result<i8, Self::Error> {
631 let as_u8 = self.data[self.position];
633 unsafe { Ok(::std::mem::transmute(as_u8)) }
637 fn read_isize(&mut self) -> Result<isize, Self::Error> {
638 read_leb128!(self, read_isize_leb128)
642 fn read_bool(&mut self) -> Result<bool, Self::Error> {
643 let value = self.read_u8()?;
648 fn read_f64(&mut self) -> Result<f64, Self::Error> {
649 let bits = self.read_u64()?;
650 Ok(f64::from_bits(bits))
654 fn read_f32(&mut self) -> Result<f32, Self::Error> {
655 let bits = self.read_u32()?;
656 Ok(f32::from_bits(bits))
660 fn read_char(&mut self) -> Result<char, Self::Error> {
661 let bits = self.read_u32()?;
662 Ok(std::char::from_u32(bits).unwrap())
666 fn read_str(&mut self) -> Result<Cow<'_, str>, Self::Error> {
667 let len = self.read_usize()?;
668 let sentinel = self.data[self.position + len];
669 assert!(sentinel == STR_SENTINEL);
671 std::str::from_utf8_unchecked(&self.data[self.position..self.position + len])
673 self.position += len + 1;
678 fn error(&mut self, err: &str) -> Self::Error {
683 fn read_raw_bytes_into(&mut self, s: &mut [u8]) -> Result<(), String> {
684 let start = self.position;
685 self.position += s.len();
686 s.copy_from_slice(&self.data[start..self.position]);
691 // Specializations for contiguous byte sequences follow. The default implementations for slices
692 // encode and decode each element individually. This isn't necessary for `u8` slices when using
693 // opaque encoders and decoders, because each `u8` is unchanged by encoding and decoding.
694 // Therefore, we can use more efficient implementations that process the entire sequence at once.
696 // Specialize encoding byte slices. This specialization also applies to encoding `Vec<u8>`s, etc.,
697 // since the default implementations call `encode` on their slices internally.
698 impl serialize::Encodable<Encoder> for [u8] {
699 fn encode(&self, e: &mut Encoder) -> EncodeResult {
700 serialize::Encoder::emit_usize(e, self.len())?;
701 e.emit_raw_bytes(self)
705 impl serialize::Encodable<FileEncoder> for [u8] {
706 fn encode(&self, e: &mut FileEncoder) -> FileEncodeResult {
707 serialize::Encoder::emit_usize(e, self.len())?;
708 e.emit_raw_bytes(self)
712 // Specialize decoding `Vec<u8>`. This specialization also applies to decoding `Box<[u8]>`s, etc.,
713 // since the default implementations call `decode` to produce a `Vec<u8>` internally.
714 impl<'a> serialize::Decodable<Decoder<'a>> for Vec<u8> {
715 fn decode(d: &mut Decoder<'a>) -> Result<Self, String> {
716 let len = serialize::Decoder::read_usize(d)?;
717 Ok(d.read_raw_bytes(len).to_owned())
721 // An integer that will always encode to 8 bytes.
722 pub struct IntEncodedWithFixedSize(pub u64);
724 impl IntEncodedWithFixedSize {
725 pub const ENCODED_SIZE: usize = 8;
728 impl serialize::Encodable<Encoder> for IntEncodedWithFixedSize {
730 fn encode(&self, e: &mut Encoder) -> EncodeResult {
731 let _start_pos = e.position();
732 e.emit_raw_bytes(&self.0.to_le_bytes())?;
733 let _end_pos = e.position();
734 debug_assert_eq!((_end_pos - _start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
739 impl serialize::Encodable<FileEncoder> for IntEncodedWithFixedSize {
741 fn encode(&self, e: &mut FileEncoder) -> FileEncodeResult {
742 let _start_pos = e.position();
743 e.emit_raw_bytes(&self.0.to_le_bytes())?;
744 let _end_pos = e.position();
745 debug_assert_eq!((_end_pos - _start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
750 impl<'a> serialize::Decodable<Decoder<'a>> for IntEncodedWithFixedSize {
752 fn decode(decoder: &mut Decoder<'a>) -> Result<IntEncodedWithFixedSize, String> {
753 let _start_pos = decoder.position();
754 let bytes = decoder.read_raw_bytes(IntEncodedWithFixedSize::ENCODED_SIZE);
755 let _end_pos = decoder.position();
756 debug_assert_eq!((_end_pos - _start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
758 let value = u64::from_le_bytes(bytes.try_into().unwrap());
759 Ok(IntEncodedWithFixedSize(value))