embedrs_bytes/buf/
buf.rs

1use super::{IntoBuf, Take, Reader, Iter, Chain};
2#[cfg(feature = "alloc")]
3use super::FromBuf;
4#[allow(unused_imports)]
5use prelude::*;
6
7use byteorder::ByteOrder;
8#[cfg(feature = "std")]
9use iovec::IoVec;
10
11use core::{cmp, ptr};
12
13#[cfg(feature = "std")]
14use std::io;
15
16#[allow(unused_imports)]
17use prelude::*;
18
19/// Read bytes from a buffer.
20///
21/// A buffer stores bytes in memory such that read operations are infallible.
22/// The underlying storage may or may not be in contiguous memory. A `Buf` value
23/// is a cursor into the buffer. Reading from `Buf` advances the cursor
24/// position. It can be thought of as an efficient `Iterator` for collections of
25/// bytes.
26///
27/// The simplest `Buf` is a `io::Cursor` wrapping a `[u8]`.
28///
29/// ```
30/// use embedrs_bytes::Buf;
31/// use std::io::Cursor;
32///
33/// let mut buf = Cursor::new(b"hello world");
34///
35/// assert_eq!(b'h', buf.get_u8());
36/// assert_eq!(b'e', buf.get_u8());
37/// assert_eq!(b'l', buf.get_u8());
38///
39/// let mut rest = [0; 8];
40/// buf.copy_to_slice(&mut rest);
41///
42/// assert_eq!(&rest[..], b"lo world");
43/// ```
44pub trait Buf {
45    /// Returns the number of bytes between the current position and the end of
46    /// the buffer.
47    ///
48    /// This value is greater than or equal to the length of the slice returned
49    /// by `bytes`.
50    ///
51    /// # Examples
52    ///
53    /// ```
54    /// use embedrs_bytes::Buf;
55    /// use std::io::Cursor;
56    ///
57    /// let mut buf = Cursor::new(b"hello world");
58    ///
59    /// assert_eq!(buf.remaining(), 11);
60    ///
61    /// buf.get_u8();
62    ///
63    /// assert_eq!(buf.remaining(), 10);
64    /// ```
65    ///
66    /// # Implementer notes
67    ///
68    /// Implementations of `remaining` should ensure that the return value does
69    /// not change unless a call is made to `advance` or any other function that
70    /// is documented to change the `Buf`'s current position.
71    fn remaining(&self) -> usize;
72
73    /// Returns a slice starting at the current position and of length between 0
74    /// and `Buf::remaining()`.
75    ///
76    /// This is a lower level function. Most operations are done with other
77    /// functions.
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// use embedrs_bytes::Buf;
83    /// use std::io::Cursor;
84    ///
85    /// let mut buf = Cursor::new(b"hello world");
86    ///
87    /// assert_eq!(buf.bytes(), b"hello world");
88    ///
89    /// buf.advance(6);
90    ///
91    /// assert_eq!(buf.bytes(), b"world");
92    /// ```
93    ///
94    /// # Implementer notes
95    ///
96    /// This function should never panic. Once the end of the buffer is reached,
97    /// i.e., `Buf::remaining` returns 0, calls to `bytes` should return an
98    /// empty slice.
99    fn bytes(&self) -> &[u8];
100
101    /// Fills `dst` with potentially multiple slices starting at `self`'s
102    /// current position.
103    ///
104    /// If the `Buf` is backed by disjoint slices of bytes, `bytes_vec` enables
105    /// fetching more than one slice at once. `dst` is a slice of `IoVec`
106    /// references, enabling the slice to be directly used with [`writev`]
107    /// without any further conversion. The sum of the lengths of all the
108    /// buffers in `dst` will be less than or equal to `Buf::remaining()`.
109    ///
110    /// The entries in `dst` will be overwritten, but the data **contained** by
111    /// the slices **will not** be modified. If `bytes_vec` does not fill every
112    /// entry in `dst`, then `dst` is guaranteed to contain all remaining slices
113    /// in `self.
114    ///
115    /// This is a lower level function. Most operations are done with other
116    /// functions.
117    ///
118    /// # Implementer notes
119    ///
120    /// This function should never panic. Once the end of the buffer is reached,
121    /// i.e., `Buf::remaining` returns 0, calls to `bytes_vec` must return 0
122    /// without mutating `dst`.
123    ///
124    /// Implementations should also take care to properly handle being called
125    /// with `dst` being a zero length slice.
126    ///
127    /// [`writev`]: http://man7.org/linux/man-pages/man2/readv.2.html
128    #[cfg(feature = "std")]
129    fn bytes_vec<'a>(&'a self, dst: &mut [&'a IoVec]) -> usize {
130        if dst.is_empty() {
131            return 0;
132        }
133
134        if self.has_remaining() {
135            dst[0] = self.bytes().into();
136            1
137        } else {
138            0
139        }
140    }
141
142    /// Advance the internal cursor of the Buf
143    ///
144    /// The next call to `bytes` will return a slice starting `cnt` bytes
145    /// further into the underlying buffer.
146    ///
147    /// # Examples
148    ///
149    /// ```
150    /// use embedrs_bytes::Buf;
151    /// use std::io::Cursor;
152    ///
153    /// let mut buf = Cursor::new(b"hello world");
154    ///
155    /// assert_eq!(buf.bytes(), b"hello world");
156    ///
157    /// buf.advance(6);
158    ///
159    /// assert_eq!(buf.bytes(), b"world");
160    /// ```
161    ///
162    /// # Panics
163    ///
164    /// This function **may** panic if `cnt > self.remaining()`.
165    ///
166    /// # Implementer notes
167    ///
168    /// It is recommended for implementations of `advance` to panic if `cnt >
169    /// self.remaining()`. If the implementation does not panic, the call must
170    /// behave as if `cnt == self.remaining()`.
171    ///
172    /// A call with `cnt == 0` should never panic and be a no-op.
173    fn advance(&mut self, cnt: usize);
174
175    /// Returns true if there are any more bytes to consume
176    ///
177    /// This is equivalent to `self.remaining() != 0`.
178    ///
179    /// # Examples
180    ///
181    /// ```
182    /// use embedrs_bytes::Buf;
183    /// use std::io::Cursor;
184    ///
185    /// let mut buf = Cursor::new(b"a");
186    ///
187    /// assert!(buf.has_remaining());
188    ///
189    /// buf.get_u8();
190    ///
191    /// assert!(!buf.has_remaining());
192    /// ```
193    fn has_remaining(&self) -> bool {
194        self.remaining() > 0
195    }
196
197    /// Copies bytes from `self` into `dst`.
198    ///
199    /// The cursor is advanced by the number of bytes copied. `self` must have
200    /// enough remaining bytes to fill `dst`.
201    ///
202    /// # Examples
203    ///
204    /// ```
205    /// use embedrs_bytes::Buf;
206    /// use std::io::Cursor;
207    ///
208    /// let mut buf = Cursor::new(b"hello world");
209    /// let mut dst = [0; 5];
210    ///
211    /// buf.copy_to_slice(&mut dst);
212    /// assert_eq!(b"hello", &dst);
213    /// assert_eq!(6, buf.remaining());
214    /// ```
215    ///
216    /// # Panics
217    ///
218    /// This function panics if `self.remaining() < dst.len()`
219    fn copy_to_slice(&mut self, dst: &mut [u8]) {
220        let mut off = 0;
221
222        assert!(self.remaining() >= dst.len());
223
224        while off < dst.len() {
225            let cnt;
226
227            unsafe {
228                let src = self.bytes();
229                cnt = cmp::min(src.len(), dst.len() - off);
230
231                ptr::copy_nonoverlapping(
232                    src.as_ptr(), dst[off..].as_mut_ptr(), cnt);
233
234                off += src.len();
235            }
236
237            self.advance(cnt);
238        }
239    }
240
241    /// Gets an unsigned 8 bit integer from `self`.
242    ///
243    /// The current position is advanced by 1.
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// use embedrs_bytes::Buf;
249    /// use std::io::Cursor;
250    ///
251    /// let mut buf = Cursor::new(b"\x08 hello");
252    /// assert_eq!(8, buf.get_u8());
253    /// ```
254    ///
255    /// # Panics
256    ///
257    /// This function panics if there is no more remaining data in `self`.
258    fn get_u8(&mut self) -> u8 {
259        let mut buf = [0; 1];
260        self.copy_to_slice(&mut buf);
261        buf[0]
262    }
263
264    /// Gets a signed 8 bit integer from `self`.
265    ///
266    /// The current position is advanced by 1.
267    ///
268    /// # Examples
269    ///
270    /// ```
271    /// use embedrs_bytes::Buf;
272    /// use std::io::Cursor;
273    ///
274    /// let mut buf = Cursor::new(b"\x08 hello");
275    /// assert_eq!(8, buf.get_i8());
276    /// ```
277    ///
278    /// # Panics
279    ///
280    /// This function panics if there is no more remaining data in `self`.
281    fn get_i8(&mut self) -> i8 {
282        let mut buf = [0; 1];
283        self.copy_to_slice(&mut buf);
284        buf[0] as i8
285    }
286
287    /// Gets an unsigned 16 bit integer from `self` in the specified byte order.
288    ///
289    /// The current position is advanced by 2.
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// use embedrs_bytes::{Buf, BigEndian};
295    /// use std::io::Cursor;
296    ///
297    /// let mut buf = Cursor::new(b"\x08\x09 hello");
298    /// assert_eq!(0x0809, buf.get_u16::<BigEndian>());
299    /// ```
300    ///
301    /// # Panics
302    ///
303    /// This function panics if there is not enough remaining data in `self`.
304    fn get_u16<T: ByteOrder>(&mut self) -> u16 {
305        let mut buf = [0; 2];
306        self.copy_to_slice(&mut buf);
307        T::read_u16(&buf)
308    }
309
310    /// Gets a signed 16 bit integer from `self` in the specified byte order.
311    ///
312    /// The current position is advanced by 2.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// use embedrs_bytes::{Buf, BigEndian};
318    /// use std::io::Cursor;
319    ///
320    /// let mut buf = Cursor::new(b"\x08\x09 hello");
321    /// assert_eq!(0x0809, buf.get_i16::<BigEndian>());
322    /// ```
323    ///
324    /// # Panics
325    ///
326    /// This function panics if there is not enough remaining data in `self`.
327    fn get_i16<T: ByteOrder>(&mut self) -> i16 {
328        let mut buf = [0; 2];
329        self.copy_to_slice(&mut buf);
330        T::read_i16(&buf)
331    }
332
333    /// Gets an unsigned 32 bit integer from `self` in the specified byte order.
334    ///
335    /// The current position is advanced by 4.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// use embedrs_bytes::{Buf, BigEndian};
341    /// use std::io::Cursor;
342    ///
343    /// let mut buf = Cursor::new(b"\x08\x09\xA0\xA1 hello");
344    /// assert_eq!(0x0809A0A1, buf.get_u32::<BigEndian>());
345    /// ```
346    ///
347    /// # Panics
348    ///
349    /// This function panics if there is not enough remaining data in `self`.
350    fn get_u32<T: ByteOrder>(&mut self) -> u32 {
351        let mut buf = [0; 4];
352        self.copy_to_slice(&mut buf);
353        T::read_u32(&buf)
354    }
355
356    /// Gets a signed 32 bit integer from `self` in the specified byte order.
357    ///
358    /// The current position is advanced by 4.
359    ///
360    /// # Examples
361    ///
362    /// ```
363    /// use embedrs_bytes::{Buf, BigEndian};
364    /// use std::io::Cursor;
365    ///
366    /// let mut buf = Cursor::new(b"\x08\x09\xA0\xA1 hello");
367    /// assert_eq!(0x0809A0A1, buf.get_i32::<BigEndian>());
368    /// ```
369    ///
370    /// # Panics
371    ///
372    /// This function panics if there is not enough remaining data in `self`.
373    fn get_i32<T: ByteOrder>(&mut self) -> i32 {
374        let mut buf = [0; 4];
375        self.copy_to_slice(&mut buf);
376        T::read_i32(&buf)
377    }
378
379    /// Gets an unsigned 64 bit integer from `self` in the specified byte order.
380    ///
381    /// The current position is advanced by 8.
382    ///
383    /// # Examples
384    ///
385    /// ```
386    /// use embedrs_bytes::{Buf, BigEndian};
387    /// use std::io::Cursor;
388    ///
389    /// let mut buf = Cursor::new(b"\x01\x02\x03\x04\x05\x06\x07\x08 hello");
390    /// assert_eq!(0x0102030405060708, buf.get_u64::<BigEndian>());
391    /// ```
392    ///
393    /// # Panics
394    ///
395    /// This function panics if there is not enough remaining data in `self`.
396    fn get_u64<T: ByteOrder>(&mut self) -> u64 {
397        let mut buf = [0; 8];
398        self.copy_to_slice(&mut buf);
399        T::read_u64(&buf)
400    }
401
402    /// Gets a signed 64 bit integer from `self` in the specified byte order.
403    ///
404    /// The current position is advanced by 8.
405    ///
406    /// # Examples
407    ///
408    /// ```
409    /// use embedrs_bytes::{Buf, BigEndian};
410    /// use std::io::Cursor;
411    ///
412    /// let mut buf = Cursor::new(b"\x01\x02\x03\x04\x05\x06\x07\x08 hello");
413    /// assert_eq!(0x0102030405060708, buf.get_i64::<BigEndian>());
414    /// ```
415    ///
416    /// # Panics
417    ///
418    /// This function panics if there is not enough remaining data in `self`.
419    fn get_i64<T: ByteOrder>(&mut self) -> i64 {
420        let mut buf = [0; 8];
421        self.copy_to_slice(&mut buf);
422        T::read_i64(&buf)
423    }
424
425    /// Gets an unsigned n-byte integer from `self` in the specified byte order.
426    ///
427    /// The current position is advanced by `nbytes`.
428    ///
429    /// # Examples
430    ///
431    /// ```
432    /// use embedrs_bytes::{Buf, BigEndian};
433    /// use std::io::Cursor;
434    ///
435    /// let mut buf = Cursor::new(b"\x01\x02\x03 hello");
436    /// assert_eq!(0x010203, buf.get_uint::<BigEndian>(3));
437    /// ```
438    ///
439    /// # Panics
440    ///
441    /// This function panics if there is not enough remaining data in `self`.
442    fn get_uint<T: ByteOrder>(&mut self, nbytes: usize) -> u64 {
443        let mut buf = [0; 8];
444        self.copy_to_slice(&mut buf[..nbytes]);
445        T::read_uint(&buf[..nbytes], nbytes)
446    }
447
448    /// Gets a signed n-byte integer from `self` in the specified byte order.
449    ///
450    /// The current position is advanced by `nbytes`.
451    ///
452    /// # Examples
453    ///
454    /// ```
455    /// use embedrs_bytes::{Buf, BigEndian};
456    /// use std::io::Cursor;
457    ///
458    /// let mut buf = Cursor::new(b"\x01\x02\x03 hello");
459    /// assert_eq!(0x010203, buf.get_int::<BigEndian>(3));
460    /// ```
461    ///
462    /// # Panics
463    ///
464    /// This function panics if there is not enough remaining data in `self`.
465    fn get_int<T: ByteOrder>(&mut self, nbytes: usize) -> i64 {
466        let mut buf = [0; 8];
467        self.copy_to_slice(&mut buf[..nbytes]);
468        T::read_int(&buf[..nbytes], nbytes)
469    }
470
471    /// Gets an IEEE754 single-precision (4 bytes) floating point number from
472    /// `self` in the specified byte order.
473    ///
474    /// The current position is advanced by 4.
475    ///
476    /// # Examples
477    ///
478    /// ```
479    /// use embedrs_bytes::{Buf, BigEndian};
480    /// use std::io::Cursor;
481    ///
482    /// let mut buf = Cursor::new(b"\x3F\x99\x99\x9A hello");
483    /// assert_eq!(1.2f32, buf.get_f32::<BigEndian>());
484    /// ```
485    ///
486    /// # Panics
487    ///
488    /// This function panics if there is not enough remaining data in `self`.
489    fn get_f32<T: ByteOrder>(&mut self) -> f32 {
490        let mut buf = [0; 4];
491        self.copy_to_slice(&mut buf);
492        T::read_f32(&buf)
493    }
494
495    /// Gets an IEEE754 double-precision (8 bytes) floating point number from
496    /// `self` in the specified byte order.
497    ///
498    /// The current position is advanced by 8.
499    ///
500    /// # Examples
501    ///
502    /// ```
503    /// use embedrs_bytes::{Buf, BigEndian};
504    /// use std::io::Cursor;
505    ///
506    /// let mut buf = Cursor::new(b"\x3F\xF3\x33\x33\x33\x33\x33\x33 hello");
507    /// assert_eq!(1.2f64, buf.get_f64::<BigEndian>());
508    /// ```
509    ///
510    /// # Panics
511    ///
512    /// This function panics if there is not enough remaining data in `self`.
513    fn get_f64<T: ByteOrder>(&mut self) -> f64 {
514        let mut buf = [0; 8];
515        self.copy_to_slice(&mut buf);
516        T::read_f64(&buf)
517    }
518
519    /// Transforms a `Buf` into a concrete buffer.
520    ///
521    /// `collect()` can operate on any value that implements `Buf`, and turn it
522    /// into the relevent concrete buffer type.
523    ///
524    /// # Examples
525    ///
526    /// Collecting a buffer and loading the contents into a `Vec<u8>`.
527    ///
528    /// ```
529    /// use embedrs_bytes::{Buf, Bytes, IntoBuf};
530    ///
531    /// let buf = Bytes::from(&b"hello world"[..]).into_buf();
532    /// let vec: Vec<u8> = buf.collect();
533    ///
534    /// assert_eq!(vec, &b"hello world"[..]);
535    /// ```
536    #[cfg(feature = "alloc")]
537    fn collect<B>(self) -> B
538        where Self: Sized,
539              B: FromBuf,
540    {
541        B::from_buf(self)
542    }
543
544    /// Creates an adaptor which will read at most `limit` bytes from `self`.
545    ///
546    /// This function returns a new instance of `Buf` which will read at most
547    /// `limit` bytes.
548    ///
549    /// # Examples
550    ///
551    /// ```
552    /// use embedrs_bytes::{Buf, BufMut};
553    /// use std::io::Cursor;
554    ///
555    /// let mut buf = Cursor::new("hello world").take(5);
556    /// let mut dst = vec![];
557    ///
558    /// dst.put(&mut buf);
559    /// assert_eq!(dst, b"hello");
560    ///
561    /// let mut buf = buf.into_inner();
562    /// dst.clear();
563    /// dst.put(&mut buf);
564    /// assert_eq!(dst, b" world");
565    /// ```
566    fn take(self, limit: usize) -> Take<Self>
567        where Self: Sized
568    {
569        super::take::new(self, limit)
570    }
571
572    /// Creates an adaptor which will chain this buffer with another.
573    ///
574    /// The returned `Buf` instance will first consume all bytes from `self`.
575    /// Afterwards the output is equivalent to the output of next.
576    ///
577    /// # Examples
578    ///
579    /// ```
580    /// use embedrs_bytes::{Bytes, Buf, IntoBuf};
581    /// use embedrs_bytes::buf::Chain;
582    ///
583    /// let buf = Bytes::from(&b"hello "[..]).into_buf()
584    ///             .chain(Bytes::from(&b"world"[..]));
585    ///
586    /// let full: Bytes = buf.collect();
587    /// assert_eq!(full[..], b"hello world"[..]);
588    /// ```
589    fn chain<U>(self, next: U) -> Chain<Self, U::Buf>
590        where U: IntoBuf,
591              Self: Sized,
592    {
593        Chain::new(self, next.into_buf())
594    }
595
596    /// Creates a "by reference" adaptor for this instance of `Buf`.
597    ///
598    /// The returned adaptor also implements `Buf` and will simply borrow `self`.
599    ///
600    /// # Examples
601    ///
602    /// ```
603    /// use embedrs_bytes::{Buf, BufMut};
604    /// use std::io::Cursor;
605    ///
606    /// let mut buf = Cursor::new("hello world");
607    /// let mut dst = vec![];
608    ///
609    /// {
610    ///     let mut reference = buf.by_ref();
611    ///     dst.put(&mut reference.take(5));
612    ///     assert_eq!(dst, b"hello");
613    /// } // drop our &mut reference so we can use `buf` again
614    ///
615    /// dst.clear();
616    /// dst.put(&mut buf);
617    /// assert_eq!(dst, b" world");
618    /// ```
619    fn by_ref(&mut self) -> &mut Self where Self: Sized {
620        self
621    }
622
623    /// Creates an adaptor which implements the `Read` trait for `self`.
624    ///
625    /// This function returns a new value which implements `Read` by adapting
626    /// the `Read` trait functions to the `Buf` trait functions. Given that
627    /// `Buf` operations are infallible, none of the `Read` functions will
628    /// return with `Err`.
629    ///
630    /// # Examples
631    ///
632    /// ```
633    /// use embedrs_bytes::{Buf, IntoBuf, Bytes};
634    /// use std::io::Read;
635    ///
636    /// let buf = Bytes::from("hello world").into_buf();
637    ///
638    /// let mut reader = buf.reader();
639    /// let mut dst = [0; 1024];
640    ///
641    /// let num = reader.read(&mut dst).unwrap();
642    ///
643    /// assert_eq!(11, num);
644    /// assert_eq!(&dst[..11], b"hello world");
645    /// ```
646    fn reader(self) -> Reader<Self> where Self: Sized {
647        super::reader::new(self)
648    }
649
650    /// Returns an iterator over the bytes contained by the buffer.
651    ///
652    /// # Examples
653    ///
654    /// ```
655    /// use embedrs_bytes::{Buf, IntoBuf, Bytes};
656    ///
657    /// let buf = Bytes::from(&b"abc"[..]).into_buf();
658    /// let mut iter = buf.iter();
659    ///
660    /// assert_eq!(iter.next(), Some(b'a'));
661    /// assert_eq!(iter.next(), Some(b'b'));
662    /// assert_eq!(iter.next(), Some(b'c'));
663    /// assert_eq!(iter.next(), None);
664    /// ```
665    fn iter(self) -> Iter<Self> where Self: Sized {
666        super::iter::new(self)
667    }
668}
669
670impl<'a, T: Buf + ?Sized> Buf for &'a mut T {
671    fn remaining(&self) -> usize {
672        (**self).remaining()
673    }
674
675    fn bytes(&self) -> &[u8] {
676        (**self).bytes()
677    }
678
679    #[cfg(feature = "std")]
680    fn bytes_vec<'b>(&'b self, dst: &mut [&'b IoVec]) -> usize {
681        (**self).bytes_vec(dst)
682    }
683
684    fn advance(&mut self, cnt: usize) {
685        (**self).advance(cnt)
686    }
687}
688
689#[cfg(feature = "alloc")]
690impl<T: Buf + ?Sized> Buf for Box<T> {
691    fn remaining(&self) -> usize {
692        (**self).remaining()
693    }
694
695    fn bytes(&self) -> &[u8] {
696        (**self).bytes()
697    }
698
699    #[cfg(feature = "std")]
700    fn bytes_vec<'b>(&'b self, dst: &mut [&'b IoVec]) -> usize {
701        (**self).bytes_vec(dst)
702    }
703
704    fn advance(&mut self, cnt: usize) {
705        (**self).advance(cnt)
706    }
707}
708
709#[cfg(feature = "std")]
710impl<T: AsRef<[u8]>> Buf for io::Cursor<T> {
711    fn remaining(&self) -> usize {
712        let len = self.get_ref().as_ref().len();
713        let pos = self.position();
714
715        if pos >= len as u64 {
716            return 0;
717        }
718
719        len - pos as usize
720    }
721
722    fn bytes(&self) -> &[u8] {
723        let len = self.get_ref().as_ref().len();
724        let pos = self.position() as usize;
725
726        if pos >= len {
727            return Default::default();
728        }
729
730        &(self.get_ref().as_ref())[pos..]
731    }
732
733    fn advance(&mut self, cnt: usize) {
734        let pos = (self.position() as usize)
735            .checked_add(cnt).expect("overflow");
736
737        assert!(pos <= self.get_ref().as_ref().len());
738
739        self.set_position(pos as u64);
740    }
741}
742
743impl Buf for Option<[u8; 1]> {
744    fn remaining(&self) -> usize {
745        if self.is_some() {
746            1
747        } else {
748            0
749        }
750    }
751
752    fn bytes(&self) -> &[u8] {
753        self.as_ref().map(AsRef::as_ref)
754            .unwrap_or(Default::default())
755    }
756
757    fn advance(&mut self, cnt: usize) {
758        if cnt == 0 {
759            return;
760        }
761
762        if self.is_none() {
763            panic!("overflow");
764        } else {
765            assert_eq!(1, cnt);
766            *self = None;
767        }
768    }
769}