]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_serialize/src/opaque.rs
Auto merge of #92604 - nnethercote:optimize-impl_read_unsigned_leb128, r=michaelwoerister
[rust.git] / compiler / rustc_serialize / src / opaque.rs
1 use crate::leb128::{self, max_leb128_len};
2 use crate::serialize::{self, Encoder as _};
3 use std::borrow::Cow;
4 use std::convert::TryInto;
5 use std::fs::File;
6 use std::io::{self, Write};
7 use std::mem::MaybeUninit;
8 use std::path::Path;
9 use std::ptr;
10
11 // -----------------------------------------------------------------------------
12 // Encoder
13 // -----------------------------------------------------------------------------
14
15 pub type EncodeResult = Result<(), !>;
16
17 pub struct Encoder {
18     pub data: Vec<u8>,
19 }
20
21 impl Encoder {
22     pub fn new(data: Vec<u8>) -> Encoder {
23         Encoder { data }
24     }
25
26     pub fn into_inner(self) -> Vec<u8> {
27         self.data
28     }
29
30     #[inline]
31     pub fn position(&self) -> usize {
32         self.data.len()
33     }
34 }
35
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();
40
41         if MAX_ENCODED_LEN > $enc.data.capacity() - old_len {
42             $enc.data.reserve(MAX_ENCODED_LEN);
43         }
44
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.
47         unsafe {
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());
52         }
53
54         Ok(())
55     }};
56 }
57
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.
61 ///
62 /// [utf8]: https://en.wikipedia.org/w/index.php?title=UTF-8&oldid=1058865525#Codepage_layout
63 const STR_SENTINEL: u8 = 0xC1;
64
65 impl serialize::Encoder for Encoder {
66     type Error = !;
67
68     #[inline]
69     fn emit_unit(&mut self) -> EncodeResult {
70         Ok(())
71     }
72
73     #[inline]
74     fn emit_usize(&mut self, v: usize) -> EncodeResult {
75         write_leb128!(self, v, usize, write_usize_leb128)
76     }
77
78     #[inline]
79     fn emit_u128(&mut self, v: u128) -> EncodeResult {
80         write_leb128!(self, v, u128, write_u128_leb128)
81     }
82
83     #[inline]
84     fn emit_u64(&mut self, v: u64) -> EncodeResult {
85         write_leb128!(self, v, u64, write_u64_leb128)
86     }
87
88     #[inline]
89     fn emit_u32(&mut self, v: u32) -> EncodeResult {
90         write_leb128!(self, v, u32, write_u32_leb128)
91     }
92
93     #[inline]
94     fn emit_u16(&mut self, v: u16) -> EncodeResult {
95         self.data.extend_from_slice(&v.to_le_bytes());
96         Ok(())
97     }
98
99     #[inline]
100     fn emit_u8(&mut self, v: u8) -> EncodeResult {
101         self.data.push(v);
102         Ok(())
103     }
104
105     #[inline]
106     fn emit_isize(&mut self, v: isize) -> EncodeResult {
107         write_leb128!(self, v, isize, write_isize_leb128)
108     }
109
110     #[inline]
111     fn emit_i128(&mut self, v: i128) -> EncodeResult {
112         write_leb128!(self, v, i128, write_i128_leb128)
113     }
114
115     #[inline]
116     fn emit_i64(&mut self, v: i64) -> EncodeResult {
117         write_leb128!(self, v, i64, write_i64_leb128)
118     }
119
120     #[inline]
121     fn emit_i32(&mut self, v: i32) -> EncodeResult {
122         write_leb128!(self, v, i32, write_i32_leb128)
123     }
124
125     #[inline]
126     fn emit_i16(&mut self, v: i16) -> EncodeResult {
127         self.data.extend_from_slice(&v.to_le_bytes());
128         Ok(())
129     }
130
131     #[inline]
132     fn emit_i8(&mut self, v: i8) -> EncodeResult {
133         let as_u8: u8 = unsafe { std::mem::transmute(v) };
134         self.emit_u8(as_u8)
135     }
136
137     #[inline]
138     fn emit_bool(&mut self, v: bool) -> EncodeResult {
139         self.emit_u8(if v { 1 } else { 0 })
140     }
141
142     #[inline]
143     fn emit_f64(&mut self, v: f64) -> EncodeResult {
144         let as_u64: u64 = v.to_bits();
145         self.emit_u64(as_u64)
146     }
147
148     #[inline]
149     fn emit_f32(&mut self, v: f32) -> EncodeResult {
150         let as_u32: u32 = v.to_bits();
151         self.emit_u32(as_u32)
152     }
153
154     #[inline]
155     fn emit_char(&mut self, v: char) -> EncodeResult {
156         self.emit_u32(v as u32)
157     }
158
159     #[inline]
160     fn emit_str(&mut self, v: &str) -> EncodeResult {
161         self.emit_usize(v.len())?;
162         self.emit_raw_bytes(v.as_bytes())?;
163         self.emit_u8(STR_SENTINEL)
164     }
165
166     #[inline]
167     fn emit_raw_bytes(&mut self, s: &[u8]) -> EncodeResult {
168         self.data.extend_from_slice(s);
169         Ok(())
170     }
171 }
172
173 pub type FileEncodeResult = Result<(), io::Error>;
174
175 // `FileEncoder` encodes data to file via fixed-size buffer.
176 //
177 // When encoding large amounts of data to a file, using `FileEncoder` may be
178 // preferred over using `Encoder` to encode to a `Vec`, and then writing the
179 // `Vec` to file, as the latter uses as much memory as there is encoded data,
180 // while the former uses the fixed amount of memory allocated to the buffer.
181 // `FileEncoder` also has the advantage of not needing to reallocate as data
182 // is appended to it, but the disadvantage of requiring more error handling,
183 // which has some runtime overhead.
184 pub struct FileEncoder {
185     // The input buffer. For adequate performance, we need more control over
186     // buffering than `BufWriter` offers. If `BufWriter` ever offers a raw
187     // buffer access API, we can use it, and remove `buf` and `buffered`.
188     buf: Box<[MaybeUninit<u8>]>,
189     buffered: usize,
190     flushed: usize,
191     file: File,
192 }
193
194 impl FileEncoder {
195     pub fn new<P: AsRef<Path>>(path: P) -> io::Result<Self> {
196         const DEFAULT_BUF_SIZE: usize = 8192;
197         FileEncoder::with_capacity(path, DEFAULT_BUF_SIZE)
198     }
199
200     pub fn with_capacity<P: AsRef<Path>>(path: P, capacity: usize) -> io::Result<Self> {
201         // Require capacity at least as large as the largest LEB128 encoding
202         // here, so that we don't have to check or handle this on every write.
203         assert!(capacity >= max_leb128_len());
204
205         // Require capacity small enough such that some capacity checks can be
206         // done using guaranteed non-overflowing add rather than sub, which
207         // shaves an instruction off those code paths (on x86 at least).
208         assert!(capacity <= usize::MAX - max_leb128_len());
209
210         let file = File::create(path)?;
211
212         Ok(FileEncoder { buf: Box::new_uninit_slice(capacity), buffered: 0, flushed: 0, file })
213     }
214
215     #[inline]
216     pub fn position(&self) -> usize {
217         // Tracking position this way instead of having a `self.position` field
218         // means that we don't have to update the position on every write call.
219         self.flushed + self.buffered
220     }
221
222     pub fn flush(&mut self) -> FileEncodeResult {
223         // This is basically a copy of `BufWriter::flush`. If `BufWriter` ever
224         // offers a raw buffer access API, we can use it, and remove this.
225
226         /// Helper struct to ensure the buffer is updated after all the writes
227         /// are complete. It tracks the number of written bytes and drains them
228         /// all from the front of the buffer when dropped.
229         struct BufGuard<'a> {
230             buffer: &'a mut [u8],
231             encoder_buffered: &'a mut usize,
232             encoder_flushed: &'a mut usize,
233             flushed: usize,
234         }
235
236         impl<'a> BufGuard<'a> {
237             fn new(
238                 buffer: &'a mut [u8],
239                 encoder_buffered: &'a mut usize,
240                 encoder_flushed: &'a mut usize,
241             ) -> Self {
242                 assert_eq!(buffer.len(), *encoder_buffered);
243                 Self { buffer, encoder_buffered, encoder_flushed, flushed: 0 }
244             }
245
246             /// The unwritten part of the buffer
247             fn remaining(&self) -> &[u8] {
248                 &self.buffer[self.flushed..]
249             }
250
251             /// Flag some bytes as removed from the front of the buffer
252             fn consume(&mut self, amt: usize) {
253                 self.flushed += amt;
254             }
255
256             /// true if all of the bytes have been written
257             fn done(&self) -> bool {
258                 self.flushed >= *self.encoder_buffered
259             }
260         }
261
262         impl Drop for BufGuard<'_> {
263             fn drop(&mut self) {
264                 if self.flushed > 0 {
265                     if self.done() {
266                         *self.encoder_flushed += *self.encoder_buffered;
267                         *self.encoder_buffered = 0;
268                     } else {
269                         self.buffer.copy_within(self.flushed.., 0);
270                         *self.encoder_flushed += self.flushed;
271                         *self.encoder_buffered -= self.flushed;
272                     }
273                 }
274             }
275         }
276
277         let mut guard = BufGuard::new(
278             unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf[..self.buffered]) },
279             &mut self.buffered,
280             &mut self.flushed,
281         );
282
283         while !guard.done() {
284             match self.file.write(guard.remaining()) {
285                 Ok(0) => {
286                     return Err(io::Error::new(
287                         io::ErrorKind::WriteZero,
288                         "failed to write the buffered data",
289                     ));
290                 }
291                 Ok(n) => guard.consume(n),
292                 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
293                 Err(e) => return Err(e),
294             }
295         }
296
297         Ok(())
298     }
299
300     #[inline]
301     fn capacity(&self) -> usize {
302         self.buf.len()
303     }
304
305     #[inline]
306     fn write_one(&mut self, value: u8) -> FileEncodeResult {
307         // We ensure this during `FileEncoder` construction.
308         debug_assert!(self.capacity() >= 1);
309
310         let mut buffered = self.buffered;
311
312         if std::intrinsics::unlikely(buffered >= self.capacity()) {
313             self.flush()?;
314             buffered = 0;
315         }
316
317         // SAFETY: The above check and `flush` ensures that there is enough
318         // room to write the input to the buffer.
319         unsafe {
320             *MaybeUninit::slice_as_mut_ptr(&mut self.buf).add(buffered) = value;
321         }
322
323         self.buffered = buffered + 1;
324
325         Ok(())
326     }
327
328     #[inline]
329     fn write_all(&mut self, buf: &[u8]) -> FileEncodeResult {
330         let capacity = self.capacity();
331         let buf_len = buf.len();
332
333         if std::intrinsics::likely(buf_len <= capacity) {
334             let mut buffered = self.buffered;
335
336             if std::intrinsics::unlikely(buf_len > capacity - buffered) {
337                 self.flush()?;
338                 buffered = 0;
339             }
340
341             // SAFETY: The above check and `flush` ensures that there is enough
342             // room to write the input to the buffer.
343             unsafe {
344                 let src = buf.as_ptr();
345                 let dst = MaybeUninit::slice_as_mut_ptr(&mut self.buf).add(buffered);
346                 ptr::copy_nonoverlapping(src, dst, buf_len);
347             }
348
349             self.buffered = buffered + buf_len;
350
351             Ok(())
352         } else {
353             self.write_all_unbuffered(buf)
354         }
355     }
356
357     fn write_all_unbuffered(&mut self, mut buf: &[u8]) -> FileEncodeResult {
358         if self.buffered > 0 {
359             self.flush()?;
360         }
361
362         // This is basically a copy of `Write::write_all` but also updates our
363         // `self.flushed`. It's necessary because `Write::write_all` does not
364         // return the number of bytes written when an error is encountered, and
365         // without that, we cannot accurately update `self.flushed` on error.
366         while !buf.is_empty() {
367             match self.file.write(buf) {
368                 Ok(0) => {
369                     return Err(io::Error::new(
370                         io::ErrorKind::WriteZero,
371                         "failed to write whole buffer",
372                     ));
373                 }
374                 Ok(n) => {
375                     buf = &buf[n..];
376                     self.flushed += n;
377                 }
378                 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
379                 Err(e) => return Err(e),
380             }
381         }
382
383         Ok(())
384     }
385 }
386
387 impl Drop for FileEncoder {
388     fn drop(&mut self) {
389         let _result = self.flush();
390     }
391 }
392
393 macro_rules! file_encoder_write_leb128 {
394     ($enc:expr, $value:expr, $int_ty:ty, $fun:ident) => {{
395         const MAX_ENCODED_LEN: usize = max_leb128_len!($int_ty);
396
397         // We ensure this during `FileEncoder` construction.
398         debug_assert!($enc.capacity() >= MAX_ENCODED_LEN);
399
400         let mut buffered = $enc.buffered;
401
402         // This can't overflow. See assertion in `FileEncoder::with_capacity`.
403         if std::intrinsics::unlikely(buffered + MAX_ENCODED_LEN > $enc.capacity()) {
404             $enc.flush()?;
405             buffered = 0;
406         }
407
408         // SAFETY: The above check and flush ensures that there is enough
409         // room to write the encoded value to the buffer.
410         let buf = unsafe {
411             &mut *($enc.buf.as_mut_ptr().add(buffered) as *mut [MaybeUninit<u8>; MAX_ENCODED_LEN])
412         };
413
414         let encoded = leb128::$fun(buf, $value);
415         $enc.buffered = buffered + encoded.len();
416
417         Ok(())
418     }};
419 }
420
421 impl serialize::Encoder for FileEncoder {
422     type Error = io::Error;
423
424     #[inline]
425     fn emit_unit(&mut self) -> FileEncodeResult {
426         Ok(())
427     }
428
429     #[inline]
430     fn emit_usize(&mut self, v: usize) -> FileEncodeResult {
431         file_encoder_write_leb128!(self, v, usize, write_usize_leb128)
432     }
433
434     #[inline]
435     fn emit_u128(&mut self, v: u128) -> FileEncodeResult {
436         file_encoder_write_leb128!(self, v, u128, write_u128_leb128)
437     }
438
439     #[inline]
440     fn emit_u64(&mut self, v: u64) -> FileEncodeResult {
441         file_encoder_write_leb128!(self, v, u64, write_u64_leb128)
442     }
443
444     #[inline]
445     fn emit_u32(&mut self, v: u32) -> FileEncodeResult {
446         file_encoder_write_leb128!(self, v, u32, write_u32_leb128)
447     }
448
449     #[inline]
450     fn emit_u16(&mut self, v: u16) -> FileEncodeResult {
451         self.write_all(&v.to_le_bytes())
452     }
453
454     #[inline]
455     fn emit_u8(&mut self, v: u8) -> FileEncodeResult {
456         self.write_one(v)
457     }
458
459     #[inline]
460     fn emit_isize(&mut self, v: isize) -> FileEncodeResult {
461         file_encoder_write_leb128!(self, v, isize, write_isize_leb128)
462     }
463
464     #[inline]
465     fn emit_i128(&mut self, v: i128) -> FileEncodeResult {
466         file_encoder_write_leb128!(self, v, i128, write_i128_leb128)
467     }
468
469     #[inline]
470     fn emit_i64(&mut self, v: i64) -> FileEncodeResult {
471         file_encoder_write_leb128!(self, v, i64, write_i64_leb128)
472     }
473
474     #[inline]
475     fn emit_i32(&mut self, v: i32) -> FileEncodeResult {
476         file_encoder_write_leb128!(self, v, i32, write_i32_leb128)
477     }
478
479     #[inline]
480     fn emit_i16(&mut self, v: i16) -> FileEncodeResult {
481         self.write_all(&v.to_le_bytes())
482     }
483
484     #[inline]
485     fn emit_i8(&mut self, v: i8) -> FileEncodeResult {
486         self.emit_u8(v as u8)
487     }
488
489     #[inline]
490     fn emit_bool(&mut self, v: bool) -> FileEncodeResult {
491         self.emit_u8(if v { 1 } else { 0 })
492     }
493
494     #[inline]
495     fn emit_f64(&mut self, v: f64) -> FileEncodeResult {
496         let as_u64: u64 = v.to_bits();
497         self.emit_u64(as_u64)
498     }
499
500     #[inline]
501     fn emit_f32(&mut self, v: f32) -> FileEncodeResult {
502         let as_u32: u32 = v.to_bits();
503         self.emit_u32(as_u32)
504     }
505
506     #[inline]
507     fn emit_char(&mut self, v: char) -> FileEncodeResult {
508         self.emit_u32(v as u32)
509     }
510
511     #[inline]
512     fn emit_str(&mut self, v: &str) -> FileEncodeResult {
513         self.emit_usize(v.len())?;
514         self.emit_raw_bytes(v.as_bytes())?;
515         self.emit_u8(STR_SENTINEL)
516     }
517
518     #[inline]
519     fn emit_raw_bytes(&mut self, s: &[u8]) -> FileEncodeResult {
520         self.write_all(s)
521     }
522 }
523
524 // -----------------------------------------------------------------------------
525 // Decoder
526 // -----------------------------------------------------------------------------
527
528 pub struct Decoder<'a> {
529     pub data: &'a [u8],
530     position: usize,
531 }
532
533 impl<'a> Decoder<'a> {
534     #[inline]
535     pub fn new(data: &'a [u8], position: usize) -> Decoder<'a> {
536         Decoder { data, position }
537     }
538
539     #[inline]
540     pub fn position(&self) -> usize {
541         self.position
542     }
543
544     #[inline]
545     pub fn set_position(&mut self, pos: usize) {
546         self.position = pos
547     }
548
549     #[inline]
550     pub fn advance(&mut self, bytes: usize) {
551         self.position += bytes;
552     }
553
554     #[inline]
555     pub fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] {
556         let start = self.position;
557         self.position += bytes;
558         &self.data[start..self.position]
559     }
560 }
561
562 macro_rules! read_leb128 {
563     ($dec:expr, $fun:ident) => {{ Ok(leb128::$fun($dec.data, &mut $dec.position)) }};
564 }
565
566 impl<'a> serialize::Decoder for Decoder<'a> {
567     type Error = String;
568
569     #[inline]
570     fn read_nil(&mut self) -> Result<(), Self::Error> {
571         Ok(())
572     }
573
574     #[inline]
575     fn read_u128(&mut self) -> Result<u128, Self::Error> {
576         read_leb128!(self, read_u128_leb128)
577     }
578
579     #[inline]
580     fn read_u64(&mut self) -> Result<u64, Self::Error> {
581         read_leb128!(self, read_u64_leb128)
582     }
583
584     #[inline]
585     fn read_u32(&mut self) -> Result<u32, Self::Error> {
586         read_leb128!(self, read_u32_leb128)
587     }
588
589     #[inline]
590     fn read_u16(&mut self) -> Result<u16, Self::Error> {
591         let bytes = [self.data[self.position], self.data[self.position + 1]];
592         let value = u16::from_le_bytes(bytes);
593         self.position += 2;
594         Ok(value)
595     }
596
597     #[inline]
598     fn read_u8(&mut self) -> Result<u8, Self::Error> {
599         let value = self.data[self.position];
600         self.position += 1;
601         Ok(value)
602     }
603
604     #[inline]
605     fn read_usize(&mut self) -> Result<usize, Self::Error> {
606         read_leb128!(self, read_usize_leb128)
607     }
608
609     #[inline]
610     fn read_i128(&mut self) -> Result<i128, Self::Error> {
611         read_leb128!(self, read_i128_leb128)
612     }
613
614     #[inline]
615     fn read_i64(&mut self) -> Result<i64, Self::Error> {
616         read_leb128!(self, read_i64_leb128)
617     }
618
619     #[inline]
620     fn read_i32(&mut self) -> Result<i32, Self::Error> {
621         read_leb128!(self, read_i32_leb128)
622     }
623
624     #[inline]
625     fn read_i16(&mut self) -> Result<i16, Self::Error> {
626         let bytes = [self.data[self.position], self.data[self.position + 1]];
627         let value = i16::from_le_bytes(bytes);
628         self.position += 2;
629         Ok(value)
630     }
631
632     #[inline]
633     fn read_i8(&mut self) -> Result<i8, Self::Error> {
634         let as_u8 = self.data[self.position];
635         self.position += 1;
636         unsafe { Ok(::std::mem::transmute(as_u8)) }
637     }
638
639     #[inline]
640     fn read_isize(&mut self) -> Result<isize, Self::Error> {
641         read_leb128!(self, read_isize_leb128)
642     }
643
644     #[inline]
645     fn read_bool(&mut self) -> Result<bool, Self::Error> {
646         let value = self.read_u8()?;
647         Ok(value != 0)
648     }
649
650     #[inline]
651     fn read_f64(&mut self) -> Result<f64, Self::Error> {
652         let bits = self.read_u64()?;
653         Ok(f64::from_bits(bits))
654     }
655
656     #[inline]
657     fn read_f32(&mut self) -> Result<f32, Self::Error> {
658         let bits = self.read_u32()?;
659         Ok(f32::from_bits(bits))
660     }
661
662     #[inline]
663     fn read_char(&mut self) -> Result<char, Self::Error> {
664         let bits = self.read_u32()?;
665         Ok(std::char::from_u32(bits).unwrap())
666     }
667
668     #[inline]
669     fn read_str(&mut self) -> Result<Cow<'_, str>, Self::Error> {
670         let len = self.read_usize()?;
671         let sentinel = self.data[self.position + len];
672         assert!(sentinel == STR_SENTINEL);
673         let s = unsafe {
674             std::str::from_utf8_unchecked(&self.data[self.position..self.position + len])
675         };
676         self.position += len + 1;
677         Ok(Cow::Borrowed(s))
678     }
679
680     #[inline]
681     fn error(&mut self, err: &str) -> Self::Error {
682         err.to_string()
683     }
684
685     #[inline]
686     fn read_raw_bytes_into(&mut self, s: &mut [u8]) -> Result<(), String> {
687         let start = self.position;
688         self.position += s.len();
689         s.copy_from_slice(&self.data[start..self.position]);
690         Ok(())
691     }
692 }
693
694 // Specializations for contiguous byte sequences follow. The default implementations for slices
695 // encode and decode each element individually. This isn't necessary for `u8` slices when using
696 // opaque encoders and decoders, because each `u8` is unchanged by encoding and decoding.
697 // Therefore, we can use more efficient implementations that process the entire sequence at once.
698
699 // Specialize encoding byte slices. This specialization also applies to encoding `Vec<u8>`s, etc.,
700 // since the default implementations call `encode` on their slices internally.
701 impl serialize::Encodable<Encoder> for [u8] {
702     fn encode(&self, e: &mut Encoder) -> EncodeResult {
703         serialize::Encoder::emit_usize(e, self.len())?;
704         e.emit_raw_bytes(self)
705     }
706 }
707
708 impl serialize::Encodable<FileEncoder> for [u8] {
709     fn encode(&self, e: &mut FileEncoder) -> FileEncodeResult {
710         serialize::Encoder::emit_usize(e, self.len())?;
711         e.emit_raw_bytes(self)
712     }
713 }
714
715 // Specialize decoding `Vec<u8>`. This specialization also applies to decoding `Box<[u8]>`s, etc.,
716 // since the default implementations call `decode` to produce a `Vec<u8>` internally.
717 impl<'a> serialize::Decodable<Decoder<'a>> for Vec<u8> {
718     fn decode(d: &mut Decoder<'a>) -> Result<Self, String> {
719         let len = serialize::Decoder::read_usize(d)?;
720         Ok(d.read_raw_bytes(len).to_owned())
721     }
722 }
723
724 // An integer that will always encode to 8 bytes.
725 pub struct IntEncodedWithFixedSize(pub u64);
726
727 impl IntEncodedWithFixedSize {
728     pub const ENCODED_SIZE: usize = 8;
729 }
730
731 impl serialize::Encodable<Encoder> for IntEncodedWithFixedSize {
732     #[inline]
733     fn encode(&self, e: &mut Encoder) -> EncodeResult {
734         let _start_pos = e.position();
735         e.emit_raw_bytes(&self.0.to_le_bytes())?;
736         let _end_pos = e.position();
737         debug_assert_eq!((_end_pos - _start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
738         Ok(())
739     }
740 }
741
742 impl serialize::Encodable<FileEncoder> for IntEncodedWithFixedSize {
743     #[inline]
744     fn encode(&self, e: &mut FileEncoder) -> FileEncodeResult {
745         let _start_pos = e.position();
746         e.emit_raw_bytes(&self.0.to_le_bytes())?;
747         let _end_pos = e.position();
748         debug_assert_eq!((_end_pos - _start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
749         Ok(())
750     }
751 }
752
753 impl<'a> serialize::Decodable<Decoder<'a>> for IntEncodedWithFixedSize {
754     #[inline]
755     fn decode(decoder: &mut Decoder<'a>) -> Result<IntEncodedWithFixedSize, String> {
756         let _start_pos = decoder.position();
757         let bytes = decoder.read_raw_bytes(IntEncodedWithFixedSize::ENCODED_SIZE);
758         let _end_pos = decoder.position();
759         debug_assert_eq!((_end_pos - _start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
760
761         let value = u64::from_le_bytes(bytes.try_into().unwrap());
762         Ok(IntEncodedWithFixedSize(value))
763     }
764 }