embedrs_bytes/buf/
buf_mut.rs

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