data_buffer/
lib.rs

1//! This crate defines a buffer data structure optimized to be written to and read from standard
2//! `Vec`s. `DataBuffer` is particularly useful when dealing with data whose type is determined at
3//! run time.  Note that data is stored in the underlying byte buffers in native endian form, thus
4//! requesting typed data from a buffer on a platform with different endianness is unsafe.
5//!
6//! # Caveats
7//!
8//! `DataBuffer` doesn't support zero-sized types.
9
10pub use reinterpret;
11
12use std::{
13    any::{Any, TypeId},
14    mem::size_of,
15    slice,
16};
17
18#[cfg(feature = "numeric")]
19use std::fmt;
20
21#[cfg(feature = "numeric")]
22use num_traits::{cast, NumCast, Zero};
23
24pub mod macros;
25
26#[cfg(feature = "serde")]
27mod serde_helpers {
28    use std::any::TypeId;
29    fn transmute_type_id_to_u64(id: &TypeId) -> u64 {
30        unsafe { std::mem::transmute::<TypeId, u64>(*id) }
31    }
32
33    #[derive(serde::Serialize, serde::Deserialize)]
34    #[serde(remote = "TypeId")]
35    pub struct TypeIdDef {
36        #[serde(getter = "transmute_type_id_to_u64")]
37        t: u64,
38    }
39
40    impl From<TypeIdDef> for TypeId {
41        fn from(def: TypeIdDef) -> TypeId {
42            unsafe { std::mem::transmute::<u64, TypeId>(def.t) }
43        }
44    }
45}
46
47/// Buffer of data. The data is stored as an array of bytes (`Vec<u8>`).
48/// `DataBuffer` keeps track of the type stored within via an explicit `TypeId` member. This allows
49/// one to hide the type from the compiler and check it only when necessary. It is particularly
50/// useful when the type of data is determined at runtime (e.g. when parsing numeric data).
51#[derive(Clone, Debug, PartialEq, Hash)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
53pub struct DataBuffer {
54    /// Raw data stored as bytes.
55    #[cfg_attr(feature = "serde_bytes", serde(with = "serde_bytes"))]
56    data: Vec<u8>,
57    /// Number of bytes occupied by an element of this buffer.
58    ///
59    /// Note: We store this instead of length because it gives us the ability to get the type size
60    /// when the buffer is empty.
61    element_size: usize,
62    /// Type encoding for hiding the type of data from the compiler.
63    #[cfg_attr(feature = "serde", serde(with = "serde_helpers::TypeIdDef"))]
64    element_type_id: TypeId,
65}
66
67impl DataBuffer {
68    /// Construct an empty `DataBuffer` with a specific type.
69    #[inline]
70    pub fn with_type<T: Any>() -> Self {
71        let element_size = size_of::<T>();
72        assert_ne!(
73            element_size, 0,
74            "DataBuffer doesn't support zero sized types."
75        );
76        DataBuffer {
77            data: Vec::new(),
78            element_size,
79            element_type_id: TypeId::of::<T>(),
80        }
81    }
82
83    /// Construct a `DataBuffer` with the same type as the given buffer without copying its data.
84    #[inline]
85    pub fn with_buffer_type(other: &DataBuffer) -> Self {
86        DataBuffer {
87            data: Vec::new(),
88            element_size: other.element_size,
89            element_type_id: other.element_type_id,
90        }
91    }
92
93    /// Construct an empty `DataBuffer` with a capacity for a given number of typed elements. For
94    /// setting byte capacity use `with_byte_capacity`.
95    #[inline]
96    pub fn with_capacity<T: Any>(n: usize) -> Self {
97        let element_size = size_of::<T>();
98        assert_ne!(
99            element_size, 0,
100            "DataBuffer doesn't support zero sized types."
101        );
102        DataBuffer {
103            data: Vec::with_capacity(n * element_size),
104            element_size,
105            element_type_id: TypeId::of::<T>(),
106        }
107    }
108
109    /// Construct a typed `DataBuffer` with a given size and filled with the specified default
110    /// value.
111    /// #  Examples
112    /// ```
113    /// # extern crate data_buffer as buf;
114    /// # use buf::DataBuffer;
115    /// # fn main() {
116    /// let buf = DataBuffer::with_size(8, 42usize); // Create buffer
117    /// let buf_vec: Vec<usize> = buf.into_vec().unwrap(); // Convert into `Vec`
118    /// assert_eq!(buf_vec, vec![42usize; 8]);
119    /// # }
120    /// ```
121    #[inline]
122    pub fn with_size<T: Any + Clone>(n: usize, def: T) -> Self {
123        Self::from_vec(vec![def; n])
124    }
125
126    /// Construct a `DataBuffer` from a given `Vec<T>` reusing the space already allocated by the
127    /// given vector.
128    /// #  Examples
129    /// ```
130    /// # extern crate data_buffer as buf;
131    /// # use buf::DataBuffer;
132    /// # fn main() {
133    /// let vec = vec![1u8, 3, 4, 1, 2];
134    /// let buf = DataBuffer::from_vec(vec.clone()); // Convert into buffer
135    /// let nu_vec: Vec<u8> = buf.into_vec().unwrap(); // Convert back into `Vec`
136    /// assert_eq!(vec, nu_vec);
137    /// # }
138    /// ```
139    pub fn from_vec<T: Any>(mut vec: Vec<T>) -> Self {
140        let element_size = size_of::<T>();
141        assert_ne!(
142            element_size, 0,
143            "DataBuffer doesn't support zero sized types."
144        );
145
146        let data = {
147            let len_in_bytes = vec.len() * element_size;
148            let capacity_in_bytes = vec.capacity() * element_size;
149            let vec_ptr = vec.as_mut_ptr() as *mut u8;
150
151            unsafe {
152                ::std::mem::forget(vec);
153                Vec::from_raw_parts(vec_ptr, len_in_bytes, capacity_in_bytes)
154            }
155        };
156
157        DataBuffer {
158            data,
159            element_size,
160            element_type_id: TypeId::of::<T>(),
161        }
162    }
163
164    /// Construct a `DataBuffer` from a given slice by cloning the data.
165    #[inline]
166    pub fn from_slice<T: Any + Clone>(slice: &[T]) -> Self {
167        let mut vec = Vec::with_capacity(slice.len());
168        vec.extend_from_slice(slice);
169        Self::from_vec(vec)
170    }
171
172    /// Resizes the buffer in-place to store `new_len` elements and returns an optional
173    /// mutable reference to `Self`.
174    ///
175    /// If `T` does not correspond to the underlying element type, then `None` is returned and the
176    /// `DataBuffer` is left unchanged.
177    ///
178    /// This function has the similar properties to `Vec::resize`.
179    #[inline]
180    pub fn resize<T: Any + Clone>(&mut self, new_len: usize, value: T) -> Option<&mut Self> {
181        self.check_ref::<T>()?;
182        let size_t = size_of::<T>();
183        if new_len >= self.len() {
184            let diff = new_len - self.len();
185            self.reserve_bytes(diff * size_t);
186            for _ in 0..diff {
187                self.push(value.clone());
188            }
189        } else {
190            // Truncate
191            self.data.resize(new_len * size_t, 0);
192        }
193        Some(self)
194    }
195
196    /// Copy data from a given slice into the current buffer.
197    ///
198    /// The `DataBuffer` is extended if the given slice is larger than the number of elements
199    /// already stored in this `DataBuffer`.
200    #[inline]
201    pub fn copy_from_slice<T: Any + Copy>(&mut self, slice: &[T]) -> &mut Self {
202        let element_size = size_of::<T>();
203        assert_ne!(
204            element_size, 0,
205            "DataBuffer doesn't support zero sized types."
206        );
207        let bins = slice.len() * element_size;
208        let byte_slice = unsafe { slice::from_raw_parts(slice.as_ptr() as *const u8, bins) };
209        self.data.resize(bins, 0);
210        self.data.copy_from_slice(byte_slice);
211        self.element_size = element_size;
212        self.element_type_id = TypeId::of::<T>();
213        self
214    }
215
216    /// Clear the data buffer without destroying its type information.
217    #[inline]
218    pub fn clear(&mut self) {
219        self.data.clear();
220    }
221
222    /// Fill the current buffer with copies of the given value. The size of the buffer is left
223    /// unchanged. If the given type doesn't patch the internal type, `None` is returned, otherwise
224    /// a mut reference to the modified buffer is returned.
225    /// #  Examples
226    /// ```
227    /// # extern crate data_buffer as buf;
228    /// # use buf::DataBuffer;
229    /// # fn main() {
230    /// let vec = vec![1u8, 3, 4, 1, 2];
231    /// let mut buf = DataBuffer::from_vec(vec.clone()); // Convert into buffer
232    /// buf.fill(0u8);
233    /// assert_eq!(buf.into_vec::<u8>().unwrap(), vec![0u8, 0, 0, 0, 0]);
234    /// # }
235    /// ```
236    #[inline]
237    pub fn fill<T: Any + Clone>(&mut self, def: T) -> Option<&mut Self> {
238        for v in self.iter_mut::<T>()? {
239            *v = def.clone();
240        }
241        Some(self)
242    }
243
244    /// Add an element to this buffer. If the type of the given element coincides with the type
245    /// stored by this buffer, then the modified buffer is returned via a mutable reference.
246    /// Otherwise, `None` is returned.
247    #[inline]
248    pub fn push<T: Any>(&mut self, element: T) -> Option<&mut Self> {
249        self.check_ref::<T>()?;
250        let element_ref = &element;
251        let element_byte_ptr = element_ref as *const T as *const u8;
252        let element_byte_slice = unsafe { slice::from_raw_parts(element_byte_ptr, size_of::<T>()) };
253        unsafe { self.push_bytes(element_byte_slice) }
254    }
255
256    /// Check if the current buffer contains elements of the specified type. Returns `Some(self)`
257    /// if the type matches and `None` otherwise.
258    #[inline]
259    pub fn check<T: Any>(self) -> Option<Self> {
260        if TypeId::of::<T>() != self.element_type_id() {
261            None
262        } else {
263            Some(self)
264        }
265    }
266
267    /// Check if the current buffer contains elements of the specified type. Returns `None` if the
268    /// check fails, otherwise a reference to self is returned.
269    #[inline]
270    pub fn check_ref<T: Any>(&self) -> Option<&Self> {
271        if TypeId::of::<T>() != self.element_type_id() {
272            None
273        } else {
274            Some(self)
275        }
276    }
277
278    /// Check if the current buffer contains elements of the specified type. Same as `check_ref`
279    /// but consumes and produces a mut reference to self.
280    #[inline]
281    pub fn check_mut<'a, T: Any>(&'a mut self) -> Option<&'a mut Self> {
282        if TypeId::of::<T>() != self.element_type_id() {
283            None
284        } else {
285            Some(self)
286        }
287    }
288
289    /*
290     * Accessors
291     */
292
293    /// Get the `TypeId` of data stored within this buffer.
294    #[inline]
295    pub fn element_type_id(&self) -> TypeId {
296        self.element_type_id
297    }
298
299    /// Get the number of elements stored in this buffer.
300    #[inline]
301    pub fn len(&self) -> usize {
302        debug_assert_eq!(self.data.len() % self.element_size, 0);
303        self.data.len() / self.element_size // element_size is guaranteed to be strictly positive
304    }
305
306    /// Check if there are any elements stored in this buffer.
307    #[inline]
308    pub fn is_empty(&self) -> bool {
309        self.data.is_empty()
310    }
311
312    /// Get the byte capacity of this buffer.
313    #[inline]
314    pub fn byte_capacity(&self) -> usize {
315        self.data.capacity()
316    }
317
318    /// Get the size of the element type in bytes.
319    #[inline]
320    pub fn element_size(&self) -> usize {
321        self.element_size
322    }
323
324    /// Return an iterator to a slice representing typed data.
325    /// Returs `None` if the given type `T` doesn't match the internal.
326    /// # Examples
327    /// ```
328    /// # extern crate data_buffer as buf;
329    /// # use buf::DataBuffer;
330    /// # fn main() {
331    /// let vec = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
332    /// let buf = DataBuffer::from(vec.clone()); // Convert into buffer
333    /// for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
334    ///     assert_eq!(val, vec[i]);
335    /// }
336    /// # }
337    /// ```
338    #[inline]
339    pub fn iter<'a, T: Any + 'a>(&'a self) -> Option<slice::Iter<T>> {
340        self.as_slice::<T>().map(|x| x.iter())
341    }
342
343    /// Return an iterator to a mutable slice representing typed data.
344    /// Returs `None` if the given type `T` doesn't match the internal.
345    #[inline]
346    pub fn iter_mut<'a, T: Any + 'a>(&'a mut self) -> Option<slice::IterMut<T>> {
347        self.as_mut_slice::<T>().map(|x| x.iter_mut())
348    }
349
350    /// Append cloned items from this buffer to a given `Vec<T>`. Return the mutable reference
351    /// `Some(vec)` if type matched the internal type and `None` otherwise.
352    #[inline]
353    pub fn append_clone_to_vec<'a, T>(&self, vec: &'a mut Vec<T>) -> Option<&'a mut Vec<T>>
354    where
355        T: Any + Clone,
356    {
357        vec.extend_from_slice(self.as_slice()?);
358        Some(vec)
359    }
360
361    /// Append copied items from this buffer to a given `Vec<T>`. Return the mutable reference
362    /// `Some(vec)` if type matched the internal type and `None` otherwise. This may be faster than
363    /// `append_clone_to_vec`.
364    #[inline]
365    pub fn append_copy_to_vec<'a, T>(&self, vec: &'a mut Vec<T>) -> Option<&'a mut Vec<T>>
366    where
367        T: Any + Copy,
368    {
369        vec.extend(self.iter()?);
370        Some(vec)
371    }
372
373    /// Clones contents of `self` into the given `Vec`.
374    #[inline]
375    pub fn clone_into_vec<T: Any + Clone>(&self) -> Option<Vec<T>> {
376        let mut vec = Vec::<T>::with_capacity(self.len());
377        match self.append_clone_to_vec(&mut vec) {
378            Some(_) => Some(vec),
379            None => None,
380        }
381    }
382
383    /// Copies contents of `self` into the given `Vec`.
384    #[inline]
385    pub fn copy_into_vec<T: Any + Copy>(&self) -> Option<Vec<T>> {
386        let mut vec = Vec::<T>::with_capacity(self.len());
387        match self.append_copy_to_vec(&mut vec) {
388            Some(_) => Some(vec),
389            None => None,
390        }
391    }
392
393    /// An alternative to using the `Into` trait. This function helps the compiler
394    /// determine the type `T` automatically.
395    #[inline]
396    pub fn into_vec<T: Any>(self) -> Option<Vec<T>> {
397        unsafe { self.check::<T>().map(|x| x.reinterpret_into_vec()) }
398    }
399
400    /// Convert this buffer into a typed slice.
401    /// Returs `None` if the given type `T` doesn't match the internal.
402    #[inline]
403    pub fn as_slice<T: Any>(&self) -> Option<&[T]> {
404        let ptr = self.check_ref::<T>()?.data.as_ptr() as *const T;
405        Some(unsafe { slice::from_raw_parts(ptr, self.len()) })
406    }
407
408    /// Convert this buffer into a typed mutable slice.
409    /// Returs `None` if the given type `T` doesn't match the internal.
410    #[inline]
411    pub fn as_mut_slice<T: Any>(&mut self) -> Option<&mut [T]> {
412        let ptr = self.check_mut::<T>()?.data.as_mut_ptr() as *mut T;
413        Some(unsafe { slice::from_raw_parts_mut(ptr, self.len()) })
414    }
415
416    /// Get `i`'th element of the buffer by value.
417    #[inline]
418    pub fn get<T: Any + Copy>(&self, i: usize) -> Option<T> {
419        assert!(i < self.len());
420        let ptr = self.check_ref::<T>()?.data.as_ptr() as *const T;
421        Some(unsafe { *ptr.add(i) })
422    }
423
424    /// Get a `const` reference to the `i`'th element of the buffer.
425    #[inline]
426    pub fn get_ref<T: Any>(&self, i: usize) -> Option<&T> {
427        assert!(i < self.len());
428        let ptr = self.check_ref::<T>()?.data.as_ptr() as *const T;
429        Some(unsafe { &*ptr.add(i) })
430    }
431
432    /// Get a mutable reference to the `i`'th element of the buffer.
433    #[inline]
434    pub fn get_mut<T: Any>(&mut self, i: usize) -> Option<&mut T> {
435        assert!(i < self.len());
436        let ptr = self.check_mut::<T>()?.data.as_mut_ptr() as *mut T;
437        Some(unsafe { &mut *ptr.add(i) })
438    }
439
440    /*
441     * Advanced methods to probe buffer internals.
442     */
443
444    /// Reserves capacity for at least `additional` more bytes to be inserted in this buffer.
445    #[inline]
446    pub fn reserve_bytes(&mut self, additional: usize) {
447        self.data.reserve(additional);
448    }
449
450    /// Get `i`'th element of the buffer by value without checking type.
451    /// This can be used to reinterpret the internal data as a different type. Note that if the
452    /// size of the given type `T` doesn't match the size of the internal type, `i` will really
453    /// index the `i`th `T` sized chunk in the current buffer. See the implementation for details.
454    #[inline]
455    pub unsafe fn get_unchecked<T: Any + Copy>(&self, i: usize) -> T {
456        let ptr = self.data.as_ptr() as *const T;
457        *ptr.add(i)
458    }
459
460    /// Get a `const` reference to the `i`'th element of the buffer.
461    /// This can be used to reinterpret the internal data as a different type. Note that if the
462    /// size of the given type `T` doesn't match the size of the internal type, `i` will really
463    /// index the `i`th `T` sized chunk in the current buffer. See the implementation for details.
464    #[inline]
465    pub unsafe fn get_unchecked_ref<T: Any>(&self, i: usize) -> &T {
466        let ptr = self.data.as_ptr() as *const T;
467        &*ptr.add(i)
468    }
469
470    /// Get a mutable reference to the `i`'th element of the buffer.
471    /// This can be used to reinterpret the internal data as a different type. Note that if the
472    /// size of the given type `T` doesn't match the size of the internal type, `i` will really
473    /// index the `i`th `T` sized chunk in the current buffer. See the implementation for details.
474    #[inline]
475    pub unsafe fn get_unchecked_mut<T: Any>(&mut self, i: usize) -> &mut T {
476        let ptr = self.data.as_mut_ptr() as *mut T;
477        &mut *ptr.add(i)
478    }
479
480    /// Get a `const` reference to the byte slice of the `i`'th element of the buffer.
481    #[inline]
482    pub fn get_bytes(&self, i: usize) -> &[u8] {
483        debug_assert!(i < self.len());
484        let element_size = self.element_size();
485        &self.data[i * element_size..(i + 1) * element_size]
486    }
487
488    /// Get a mutable reference to the byte slice of the `i`'th element of the buffer.
489    ///
490    /// # Unsafety
491    ///
492    /// This function is marked as unsafe since the returned bytes may be modified
493    /// arbitrarily, which may potentially produce malformed values.
494    #[inline]
495    pub unsafe fn get_bytes_mut(&mut self, i: usize) -> &mut [u8] {
496        debug_assert!(i < self.len());
497        let element_size = self.element_size();
498        &mut self.data[i * element_size..(i + 1) * element_size]
499    }
500
501    /// Move buffer data to a vector with a given type, reinterpreting the data type as
502    /// required.
503    #[inline]
504    pub unsafe fn reinterpret_into_vec<T>(self) -> Vec<T> {
505        reinterpret::reinterpret_vec(self.data)
506    }
507
508    /// Borrow buffer data and reinterpret it as a slice of a given type.
509    #[inline]
510    pub unsafe fn reinterpret_as_slice<T>(&self) -> &[T] {
511        reinterpret::reinterpret_slice(self.data.as_slice())
512    }
513
514    /// Mutably borrow buffer data and reinterpret it as a mutable slice of a given type.
515    #[inline]
516    pub unsafe fn reinterpret_as_mut_slice<T>(&mut self) -> &mut [T] {
517        reinterpret::reinterpret_mut_slice(self.data.as_mut_slice())
518    }
519
520    /// Borrow buffer data and iterate over reinterpreted underlying data.
521    #[inline]
522    pub unsafe fn reinterpret_iter<T>(&self) -> slice::Iter<T> {
523        self.reinterpret_as_slice().iter()
524    }
525
526    /// Mutably borrow buffer data and mutably iterate over reinterpreted underlying data.
527    #[inline]
528    pub unsafe fn reinterpret_iter_mut<T>(&mut self) -> slice::IterMut<T> {
529        self.reinterpret_as_mut_slice().iter_mut()
530    }
531
532    /// Peak at the internal representation of the data.
533    #[inline]
534    pub fn as_bytes(&self) -> &[u8] {
535        self.data.as_slice()
536    }
537
538    /// Get a mutable reference to the internal data representation.
539    ///
540    /// # Unsafety
541    ///
542    /// This function is marked as unsafe since the returned bytes may be modified
543    /// arbitrarily, which may potentially produce malformed values.
544    #[inline]
545    pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
546        self.data.as_mut_slice()
547    }
548
549    /// Iterate over chunks type sized chunks of bytes without interpreting them. This avoids
550    /// needing to know what type data you're dealing with. This type of iterator is useful for
551    /// transferring data from one place to another for a generic buffer.
552    #[inline]
553    pub fn byte_chunks<'a>(&'a self) -> impl Iterator<Item = &'a [u8]> + 'a {
554        let chunk_size = self.element_size();
555        self.data.chunks(chunk_size)
556    }
557
558    /// Mutably iterate over chunks type sized chunks of bytes without interpreting them. This
559    /// avoids needing to know what type data you're dealing with. This type of iterator is useful
560    /// for transferring data from one place to another for a generic buffer, or modifying the
561    /// underlying untyped bytes (e.g. bit twiddling).
562    ///
563    /// # Unsafety
564    ///
565    /// This function is marked as unsafe since the returned bytes may be modified
566    /// arbitrarily, which may potentially produce malformed values.
567    #[inline]
568    pub unsafe fn byte_chunks_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut [u8]> + 'a {
569        let chunk_size = self.element_size();
570        self.data.chunks_mut(chunk_size)
571    }
572
573    /// Add bytes to this buffer. If the size of the given slice coincides with the number of bytes
574    /// occupied by the underlying element type, then these bytes are added to the underlying data
575    /// buffer and a mutable reference to the buffer is returned.
576    /// Otherwise, `None` is returned, and the buffer remains unmodified.
577    #[inline]
578    pub unsafe fn push_bytes(&mut self, bytes: &[u8]) -> Option<&mut Self> {
579        if bytes.len() == self.element_size() {
580            self.data.extend_from_slice(bytes);
581            Some(self)
582        } else {
583            None
584        }
585    }
586
587    /// Add bytes to this buffer. If the size of the given slice is a multiple of the number of bytes
588    /// occupied by the underlying element type, then these bytes are added to the underlying data
589    /// buffer and a mutable reference to the buffer is returned.
590    /// Otherwise, `None` is returned and the buffer is unmodified.
591    #[inline]
592    pub unsafe fn extend_bytes(&mut self, bytes: &[u8]) -> Option<&mut Self> {
593        let element_size = self.element_size();
594        if bytes.len() % element_size == 0 {
595            self.data.extend_from_slice(bytes);
596            Some(self)
597        } else {
598            None
599        }
600    }
601
602    /// Move bytes to this buffer. If the size of the given vector is a multiple of the number of bytes
603    /// occupied by the underlying element type, then these bytes are moved to the underlying data
604    /// buffer and a mutable reference to the buffer is returned.
605    /// Otherwise, `None` is returned and both the buffer and the input vector remain unmodified.
606    #[inline]
607    pub unsafe fn append_bytes(&mut self, bytes: &mut Vec<u8>) -> Option<&mut Self> {
608        let element_size = self.element_size();
609        if bytes.len() % element_size == 0 {
610            self.data.append(bytes);
611            Some(self)
612        } else {
613            None
614        }
615    }
616
617    /// Move bytes to this buffer. The given buffer must have the same underlying type as self.
618    #[inline]
619    pub fn append(&mut self, buf: &mut DataBuffer) -> Option<&mut Self> {
620        if buf.element_type_id() == self.element_type_id() {
621            self.data.append(&mut buf.data);
622            Some(self)
623        } else {
624            None
625        }
626    }
627
628    /// Rotates the slice in-place such that the first `mid` elements of the slice move to the end
629    /// while the last `self.len() - mid` elements move to the front. After calling `rotate_left`,
630    /// the element previously at index `mid` will become the first element in the slice.
631    ///
632    /// # Example
633    ///
634    /// ```
635    /// # use data_buffer::*;
636    /// let mut buf = DataBuffer::from_vec(vec![1u32,2,3,4,5]);
637    /// buf.rotate_left(3);
638    /// assert_eq!(buf.as_slice::<u32>().unwrap(), &[4,5,1,2,3]);
639    /// ```
640    #[inline]
641    pub fn rotate_left(&mut self, mid: usize) {
642        self.data.rotate_left(mid * self.element_size);
643    }
644
645    /// Rotates the slice in-place such that the first `self.len() - k` elements of the slice move
646    /// to the end while the last `k` elements move to the front. After calling `rotate_right`, the
647    /// element previously at index `k` will become the first element in the slice.
648    ///
649    /// # Example
650    ///
651    /// ```
652    /// # use data_buffer::*;
653    /// let mut buf = DataBuffer::from_vec(vec![1u32,2,3,4,5]);
654    /// buf.rotate_right(3);
655    /// assert_eq!(buf.as_slice::<u32>().unwrap(), &[3,4,5,1,2]);
656    /// ```
657    #[inline]
658    pub fn rotate_right(&mut self, k: usize) {
659        self.data.rotate_right(k * self.element_size);
660    }
661
662    /*
663     * Methods specific to buffers storing numeric data
664     */
665
666    #[cfg(feature = "numeric")]
667    /// Cast a numeric `DataBuffer` into the given output `Vec` type.
668    pub fn cast_into_vec<T>(self) -> Vec<T>
669    where
670        T: Any + Copy + NumCast + Zero,
671    {
672        // Helper function (generic on the input) to convert the given DataBuffer into Vec.
673        unsafe fn convert_into_vec<I, O>(buf: DataBuffer) -> Vec<O>
674        where
675            I: Any + NumCast,
676            O: Any + Copy + NumCast + Zero,
677        {
678            debug_assert_eq!(buf.element_type_id(), TypeId::of::<I>()); // Check invariant.
679            buf.reinterpret_into_vec()
680                .into_iter()
681                .map(|elem: I| cast(elem).unwrap_or(O::zero()))
682                .collect()
683        }
684        call_numeric_buffer_fn!( convert_into_vec::<_,T>(self) or { Vec::new() } )
685    }
686
687    #[cfg(feature = "numeric")]
688    /// Display the contents of this buffer reinterpreted in the given type.
689    unsafe fn reinterpret_display<T: Any + fmt::Display>(&self, f: &mut fmt::Formatter) {
690        debug_assert_eq!(self.element_type_id(), TypeId::of::<T>()); // Check invariant.
691        for item in self.reinterpret_iter::<T>() {
692            write!(f, "{} ", item).expect("Error occurred while writing an DataBuffer.");
693        }
694    }
695}
696
697/// Convert a `Vec<T>` to a `DataBuffer`.
698impl<T> From<Vec<T>> for DataBuffer
699where
700    T: Any,
701{
702    #[inline]
703    fn from(vec: Vec<T>) -> DataBuffer {
704        DataBuffer::from_vec(vec)
705    }
706}
707
708/// Convert a `&[T]` to a `DataBuffer`.
709impl<'a, T> From<&'a [T]> for DataBuffer
710where
711    T: Any + Clone,
712{
713    #[inline]
714    fn from(slice: &'a [T]) -> DataBuffer {
715        DataBuffer::from_slice(slice)
716    }
717}
718
719/// Convert a `DataBuffer` to a `Option<Vec<T>>`.
720impl<T> Into<Option<Vec<T>>> for DataBuffer
721where
722    T: Any + Clone,
723{
724    #[inline]
725    fn into(self) -> Option<Vec<T>> {
726        self.into_vec()
727    }
728}
729
730#[cfg(feature = "numeric")]
731/// Implement pretty printing of numeric `DataBuffer` data.
732impl fmt::Display for DataBuffer {
733    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
734        call_numeric_buffer_fn!( self.reinterpret_display::<_>(f) or {
735            println!("Unknown DataBuffer type for pretty printing.");
736        } );
737        write!(f, "")
738    }
739}
740
741#[cfg(test)]
742mod tests {
743    use super::*;
744
745    /// Test various ways to create a data buffer.
746    #[test]
747    fn initialization_test() {
748        // Empty typed buffer.
749        let a = DataBuffer::with_type::<f32>();
750        assert_eq!(a.len(), 0);
751        assert_eq!(a.as_bytes().len(), 0);
752        assert_eq!(a.element_type_id(), TypeId::of::<f32>());
753        assert_eq!(a.byte_capacity(), 0); // Ensure nothing is allocated.
754
755        // Empty buffer typed by the given type id.
756        let b = DataBuffer::with_buffer_type(&a);
757        assert_eq!(b.len(), 0);
758        assert_eq!(b.as_bytes().len(), 0);
759        assert_eq!(b.element_type_id(), TypeId::of::<f32>());
760        assert_eq!(a.byte_capacity(), 0); // Ensure nothing is allocated.
761
762        // Empty typed buffer with a given capacity.
763        let a = DataBuffer::with_capacity::<f32>(4);
764        assert_eq!(a.len(), 0);
765        assert_eq!(a.as_bytes().len(), 0);
766        assert_eq!(a.byte_capacity(), 4 * size_of::<f32>());
767        assert_eq!(a.element_type_id(), TypeId::of::<f32>());
768    }
769
770    /// Test reserving capacity after creation.
771    #[test]
772    fn reserve_bytes() {
773        let mut a = DataBuffer::with_type::<f32>();
774        assert_eq!(a.byte_capacity(), 0);
775        a.reserve_bytes(10);
776        assert_eq!(a.len(), 0);
777        assert_eq!(a.as_bytes().len(), 0);
778        assert!(a.byte_capacity() >= 10);
779    }
780
781    /// Test resizing a buffer.
782    #[test]
783    fn resize() {
784        let mut a = DataBuffer::with_type::<f32>();
785
786        // Increase the size of a.
787        a.resize(3, 1.0f32);
788
789        assert_eq!(a.len(), 3);
790        assert_eq!(a.as_bytes().len(), 12);
791        for i in 0..3 {
792            assert_eq!(a.get::<f32>(i).unwrap(), 1.0f32);
793        }
794
795        // Truncate a.
796        a.resize(2, 1.0f32);
797
798        assert_eq!(a.len(), 2);
799        assert_eq!(a.as_bytes().len(), 8);
800        for i in 0..2 {
801            assert_eq!(a.get::<f32>(i).unwrap(), 1.0f32);
802        }
803    }
804
805    #[test]
806    #[should_panic]
807    fn zero_size_with_type_test() {
808        let _a = DataBuffer::with_type::<()>();
809    }
810
811    #[test]
812    #[should_panic]
813    fn zero_size_with_capacity_test() {
814        let _a = DataBuffer::with_capacity::<()>(2);
815    }
816
817    #[test]
818    #[should_panic]
819    fn zero_size_from_vec_test() {
820        let _a = DataBuffer::from_vec(vec![(); 3]);
821    }
822
823    #[test]
824    #[should_panic]
825    fn zero_size_with_size_test() {
826        let _a = DataBuffer::with_size(3, ());
827    }
828
829    #[test]
830    #[should_panic]
831    fn zero_size_from_slice_test() {
832        let v = vec![(); 3];
833        let _a = DataBuffer::from_slice(&v);
834    }
835
836    #[test]
837    #[should_panic]
838    fn zero_size_copy_from_slice_test() {
839        let v = vec![(); 3];
840        let mut a = DataBuffer::with_size(0, 1i32);
841        a.copy_from_slice(&v);
842    }
843
844    #[test]
845    fn data_integrity_u8_test() {
846        let vec = vec![1u8, 3, 4, 1, 2];
847        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
848        let nu_vec: Vec<u8> = buf.copy_into_vec().unwrap(); // Convert back into vec
849        assert_eq!(vec, nu_vec);
850
851        let vec = vec![1u8, 3, 4, 1, 2, 52, 1, 3, 41, 23, 2];
852        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
853        let nu_vec: Vec<u8> = buf.copy_into_vec().unwrap(); // Convert back into vec
854        assert_eq!(vec, nu_vec);
855    }
856
857    #[test]
858    fn data_integrity_i16_test() {
859        let vec = vec![1i16, -3, 1002, -231, 32];
860        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
861        let nu_vec: Vec<i16> = buf.copy_into_vec().unwrap(); // Convert back into vec
862        assert_eq!(vec, nu_vec);
863
864        let vec = vec![1i16, -3, 1002, -231, 32, 42, -123, 4];
865        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
866        let nu_vec: Vec<i16> = buf.copy_into_vec().unwrap(); // Convert back into vec
867        assert_eq!(vec, nu_vec);
868    }
869
870    #[test]
871    fn data_integrity_i32_test() {
872        let vec = vec![1i32, -3, 1002, -231, 32];
873        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
874        let nu_vec: Vec<i32> = buf.into_vec().unwrap(); // Convert back into vec
875        assert_eq!(vec, nu_vec);
876
877        let vec = vec![1i32, -3, 1002, -231, 32, 42, -123];
878        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
879        let nu_vec: Vec<i32> = buf.into_vec().unwrap(); // Convert back into vec
880        assert_eq!(vec, nu_vec);
881    }
882
883    #[test]
884    fn data_integrity_f32_test() {
885        let vec = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
886        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
887        let nu_vec: Vec<f32> = buf.into_vec().unwrap(); // Convert back into vec
888        assert_eq!(vec, nu_vec);
889
890        let vec = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43, 2e-1];
891        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
892        let nu_vec: Vec<f32> = buf.into_vec().unwrap(); // Convert back into vec
893        assert_eq!(vec, nu_vec);
894    }
895
896    #[test]
897    fn data_integrity_f64_test() {
898        let vec = vec![1f64, -3.0, 10.02, -23.1, 32e-1];
899        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
900        let nu_vec: Vec<f64> = buf.copy_into_vec().unwrap(); // Convert back into vec
901        assert_eq!(vec, nu_vec);
902
903        let vec = vec![1f64, -3.1, 100.2, -2.31, 3.2, 4e2, -1e23];
904        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
905        let nu_vec: Vec<f64> = buf.copy_into_vec().unwrap(); // Convert back into vec
906        assert_eq!(vec, nu_vec);
907    }
908
909    #[cfg(feature = "numeric")]
910    #[test]
911    fn convert_float_test() {
912        let vecf64 = vec![1f64, -3.0, 10.02, -23.1, 32e-1];
913        let buf = DataBuffer::from(vecf64.clone()); // Convert into buffer
914        let nu_vec: Vec<f32> = buf.cast_into_vec(); // Convert back into vec
915        let vecf32 = vec![1f32, -3.0, 10.02, -23.1, 32e-1];
916        assert_eq!(vecf32, nu_vec);
917
918        let buf = DataBuffer::from(vecf32.clone()); // Convert into buffer
919        let nu_vec: Vec<f64> = buf.cast_into_vec(); // Convert back into vec
920        for (&a, &b) in vecf64.iter().zip(nu_vec.iter()) {
921            assert!((a - b).abs() < 1e-6f64 * f64::max(a, b).abs());
922        }
923
924        let vecf64 = vec![1f64, -3.1, 100.2, -2.31, 3.2, 4e2, -1e23];
925        let buf = DataBuffer::from(vecf64.clone()); // Convert into buffer
926        let nu_vec: Vec<f32> = buf.cast_into_vec(); // Convert back into vec
927        let vecf32 = vec![1f32, -3.1, 100.2, -2.31, 3.2, 4e2, -1e23];
928        assert_eq!(vecf32, nu_vec);
929        let buf = DataBuffer::from(vecf32.clone()); // Convert into buffer
930        let nu_vec: Vec<f64> = buf.cast_into_vec(); // Convert back into vec
931        for (&a, &b) in vecf64.iter().zip(nu_vec.iter()) {
932            assert!((a - b).abs() < 1e-6 * f64::max(a, b).abs());
933        }
934    }
935
936    #[derive(Clone, Debug, PartialEq)]
937    struct Foo {
938        a: u8,
939        b: i64,
940        c: f32,
941    }
942
943    #[test]
944    fn from_empty_vec_test() {
945        let vec: Vec<u32> = Vec::new();
946        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
947        let nu_vec: Vec<u32> = buf.into_vec().unwrap(); // Convert back into vec
948        assert_eq!(vec, nu_vec);
949
950        let vec: Vec<String> = Vec::new();
951        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
952        let nu_vec: Vec<String> = buf.into_vec().unwrap(); // Convert back into vec
953        assert_eq!(vec, nu_vec);
954
955        let vec: Vec<Foo> = Vec::new();
956        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
957        let nu_vec: Vec<Foo> = buf.into_vec().unwrap(); // Convert back into vec
958        assert_eq!(vec, nu_vec);
959    }
960
961    #[test]
962    fn from_struct_test() {
963        let f1 = Foo {
964            a: 3,
965            b: -32,
966            c: 54.2,
967        };
968        let f2 = Foo {
969            a: 33,
970            b: -3342432412,
971            c: 323454.2,
972        };
973        let vec = vec![f1.clone(), f2.clone()];
974        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
975        assert_eq!(f1, buf.get_ref::<Foo>(0).unwrap().clone());
976        assert_eq!(f2, buf.get_ref::<Foo>(1).unwrap().clone());
977        let nu_vec: Vec<Foo> = buf.into_vec().unwrap(); // Convert back into vec
978        assert_eq!(vec, nu_vec);
979    }
980
981    #[test]
982    fn from_strings_test() {
983        let vec = vec![
984            String::from("hi"),
985            String::from("hello"),
986            String::from("goodbye"),
987            String::from("bye"),
988            String::from("supercalifragilisticexpialidocious"),
989            String::from("42"),
990        ];
991        let buf = DataBuffer::from(vec.clone()); // Convert into buffer
992        assert_eq!("hi", buf.get_ref::<String>(0).unwrap());
993        assert_eq!("hello", buf.get_ref::<String>(1).unwrap());
994        assert_eq!("goodbye", buf.get_ref::<String>(2).unwrap());
995        let nu_vec: Vec<String> = buf.into_vec().unwrap(); // Convert back into vec
996        assert_eq!(vec, nu_vec);
997    }
998
999    #[test]
1000    fn iter_test() {
1001        // Check iterating over data with a larger size than 8 bits.
1002        let vec_f32 = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
1003        let buf = DataBuffer::from(vec_f32.clone()); // Convert into buffer
1004        for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
1005            assert_eq!(val, vec_f32[i]);
1006        }
1007
1008        // Check iterating over data with the same size.
1009        let vec_u8 = vec![1u8, 3, 4, 1, 2, 4, 128, 32];
1010        let buf = DataBuffer::from(vec_u8.clone()); // Convert into buffer
1011        for (i, &val) in buf.iter::<u8>().unwrap().enumerate() {
1012            assert_eq!(val, vec_u8[i]);
1013        }
1014
1015        // Check unsafe functions:
1016        unsafe {
1017            // TODO: feature gate these two tests for little endian platforms.
1018            // Check iterating over data with a larger size than input.
1019            let vec_u32 = vec![17_040_129u32, 545_260_546]; // little endian
1020            let buf = DataBuffer::from(vec_u8.clone()); // Convert into buffer
1021            for (i, &val) in buf.reinterpret_iter::<u32>().enumerate() {
1022                assert_eq!(val, vec_u32[i]);
1023            }
1024
1025            // Check iterating over data with a smaller size than input
1026            let mut buf2 = DataBuffer::from(vec_u32); // Convert into buffer
1027            for (i, &val) in buf2.reinterpret_iter::<u8>().enumerate() {
1028                assert_eq!(val, vec_u8[i]);
1029            }
1030
1031            // Check mut iterator
1032            buf2.reinterpret_iter_mut::<u8>().for_each(|val| *val += 1);
1033
1034            let u8_check_vec = vec![2u8, 4, 5, 2, 3, 5, 129, 33];
1035            assert_eq!(buf2.reinterpret_into_vec::<u8>(), u8_check_vec);
1036        }
1037    }
1038
1039    #[test]
1040    fn large_sizes_test() {
1041        for i in 1000000..1000010 {
1042            let vec = vec![32u8; i];
1043            let buf = DataBuffer::from(vec.clone()); // Convert into buffer
1044            let nu_vec: Vec<u8> = buf.into_vec().unwrap(); // Convert back into vec
1045            assert_eq!(vec, nu_vec);
1046        }
1047    }
1048
1049    /// This test checks that an error is returned whenever the user tries to access data with the
1050    /// wrong type data.
1051    #[test]
1052    fn wrong_type_test() {
1053        let vec = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
1054        let mut buf = DataBuffer::from(vec.clone()); // Convert into buffer
1055        assert_eq!(vec, buf.clone_into_vec::<f32>().unwrap());
1056
1057        assert!(buf.copy_into_vec::<f64>().is_none());
1058        assert!(buf.as_slice::<f64>().is_none());
1059        assert!(buf.as_mut_slice::<u8>().is_none());
1060        assert!(buf.iter::<[f32; 3]>().is_none());
1061        assert!(buf.get::<i32>(0).is_none());
1062        assert!(buf.get_ref::<i32>(1).is_none());
1063        assert!(buf.get_mut::<i32>(2).is_none());
1064    }
1065
1066    /// Test iterating over chunks of data without having to interpret them.
1067    #[test]
1068    fn byte_chunks_test() {
1069        let vec_f32 = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
1070        let buf = DataBuffer::from(vec_f32.clone()); // Convert into buffer
1071
1072        for (i, val) in buf.byte_chunks().enumerate() {
1073            assert_eq!(
1074                unsafe { reinterpret::reinterpret_slice::<u8, f32>(val)[0] },
1075                vec_f32[i]
1076            );
1077        }
1078    }
1079
1080    /// Test pushing values and bytes to a buffer.
1081    #[test]
1082    fn push_test() {
1083        let mut vec_f32 = vec![1.0_f32, 23.0, 0.01];
1084        let mut buf = DataBuffer::from(vec_f32.clone()); // Convert into buffer
1085        for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
1086            assert_eq!(val, vec_f32[i]);
1087        }
1088
1089        vec_f32.push(42.0f32);
1090        buf.push(42.0f32).unwrap(); // must provide explicit type
1091
1092        for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
1093            assert_eq!(val, vec_f32[i]);
1094        }
1095
1096        vec_f32.push(11.43);
1097        buf.push(11.43f32).unwrap();
1098
1099        for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
1100            assert_eq!(val, vec_f32[i]);
1101        }
1102
1103        // Zero float is always represented by four zero bytes in IEEE format.
1104        vec_f32.push(0.0);
1105        vec_f32.push(0.0);
1106        unsafe { buf.extend_bytes(&[0, 0, 0, 0, 0, 0, 0, 0]) }.unwrap();
1107
1108        for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
1109            assert_eq!(val, vec_f32[i]);
1110        }
1111
1112        // Test byte getters
1113        for i in 5..7 {
1114            assert_eq!(buf.get_bytes(i), &[0, 0, 0, 0]);
1115            assert_eq!(unsafe { buf.get_bytes_mut(i) }, &[0, 0, 0, 0]);
1116        }
1117
1118        vec_f32.push(0.0);
1119        unsafe { buf.push_bytes(&[0, 0, 0, 0]) }.unwrap();
1120
1121        for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
1122            assert_eq!(val, vec_f32[i]);
1123        }
1124    }
1125
1126    /// Test appending to a data buffer from another data buffer.
1127    #[test]
1128    fn append_test() {
1129        let mut buf = DataBuffer::with_type::<f32>(); // Create an empty buffer.
1130
1131        let data = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
1132        // Append an ordianry vector of data.
1133        let mut other_buf = DataBuffer::from_vec(data.clone());
1134        buf.append(&mut other_buf);
1135
1136        assert!(other_buf.is_empty());
1137
1138        for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
1139            assert_eq!(val, data[i]);
1140        }
1141    }
1142
1143    /// Test appending to a data buffer from other slices and vectors.
1144    #[test]
1145    fn extend_append_bytes_test() {
1146        let mut buf = DataBuffer::with_type::<f32>(); // Create an empty buffer.
1147
1148        // Append an ordianry vector of data.
1149        let vec_f32 = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
1150        let mut vec_bytes: Vec<u8> = unsafe { reinterpret::reinterpret_vec(vec_f32.clone()) };
1151        unsafe { buf.append_bytes(&mut vec_bytes) };
1152
1153        for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
1154            assert_eq!(val, vec_f32[i]);
1155        }
1156
1157        buf.clear();
1158        assert_eq!(buf.len(), 0);
1159
1160        // Append a temporary vec.
1161        unsafe { buf.append_bytes(&mut vec![0u8; 4]) };
1162        assert_eq!(buf.get::<f32>(0).unwrap(), 0.0f32);
1163
1164        buf.clear();
1165        assert_eq!(buf.len(), 0);
1166
1167        // Extend buffer with a slice
1168        let slice_bytes: &[u8] = unsafe { reinterpret::reinterpret_slice(&vec_f32) };
1169        unsafe { buf.extend_bytes(slice_bytes) };
1170
1171        for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
1172            assert_eq!(val, vec_f32[i]);
1173        }
1174    }
1175
1176    #[cfg(feature = "serde")]
1177    #[test]
1178    fn serde_test() {
1179        let vec_f32 = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
1180        let buf = DataBuffer::from(vec_f32.clone()); // Convert into buffer
1181        dbg!(&buf);
1182        let buf_str = serde_json::to_string(&buf).expect("Failed to serialize DataBuffer.");
1183        dbg!(&buf_str);
1184        let new_buf = serde_json::from_str(&buf_str).expect("Failed to deserialize DataBuffer.");
1185        dbg!(&new_buf);
1186        assert_eq!(buf, new_buf);
1187    }
1188}