vortex_buffer/
buffer.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::type_name;
5use std::cmp::Ordering;
6use std::collections::Bound;
7use std::fmt::Debug;
8use std::fmt::Formatter;
9use std::hash::Hash;
10use std::hash::Hasher;
11use std::marker::PhantomData;
12use std::ops::Deref;
13use std::ops::RangeBounds;
14
15use bytes::Buf;
16use bytes::Bytes;
17use vortex_error::VortexExpect;
18use vortex_error::vortex_panic;
19
20use crate::Alignment;
21use crate::BufferMut;
22use crate::ByteBuffer;
23use crate::debug::TruncatedDebug;
24use crate::trusted_len::TrustedLen;
25
26/// An immutable buffer of items of `T`.
27pub struct Buffer<T> {
28    pub(crate) bytes: Bytes,
29    pub(crate) length: usize,
30    pub(crate) alignment: Alignment,
31    pub(crate) _marker: PhantomData<T>,
32}
33
34impl<T> Clone for Buffer<T> {
35    #[inline]
36    fn clone(&self) -> Self {
37        Self {
38            bytes: self.bytes.clone(),
39            length: self.length,
40            alignment: self.alignment,
41            _marker: PhantomData,
42        }
43    }
44}
45
46impl<T> Default for Buffer<T> {
47    fn default() -> Self {
48        Self {
49            bytes: Default::default(),
50            length: 0,
51            alignment: Alignment::of::<T>(),
52            _marker: PhantomData,
53        }
54    }
55}
56
57impl<T> PartialEq for Buffer<T> {
58    #[inline]
59    fn eq(&self, other: &Self) -> bool {
60        self.bytes == other.bytes
61    }
62}
63
64impl<T: PartialEq> PartialEq<Vec<T>> for Buffer<T> {
65    fn eq(&self, other: &Vec<T>) -> bool {
66        self.as_ref() == other.as_slice()
67    }
68}
69
70impl<T: PartialEq> PartialEq<Buffer<T>> for Vec<T> {
71    fn eq(&self, other: &Buffer<T>) -> bool {
72        self.as_slice() == other.as_ref()
73    }
74}
75
76impl<T> Eq for Buffer<T> {}
77
78impl<T> Ord for Buffer<T> {
79    #[inline]
80    fn cmp(&self, other: &Self) -> Ordering {
81        self.bytes.cmp(&other.bytes)
82    }
83}
84
85impl<T> PartialOrd for Buffer<T> {
86    #[inline]
87    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
88        Some(self.cmp(other))
89    }
90}
91
92impl<T> Hash for Buffer<T> {
93    #[inline]
94    fn hash<H: Hasher>(&self, state: &mut H) {
95        self.bytes.as_ref().hash(state)
96    }
97}
98
99impl<T> Buffer<T> {
100    /// Returns a new `Buffer<T>` copied from the provided `Vec<T>`, `&[T]`, etc.
101    ///
102    /// Due to our underlying usage of `bytes::Bytes`, we are unable to take zero-copy ownership
103    /// of the provided `Vec<T>` while maintaining the ability to convert it back into a mutable
104    /// buffer. We could fix this by forking `Bytes`, or in many other complex ways, but for now
105    /// callers should prefer to construct `Buffer<T>` from a `BufferMut<T>`.
106    pub fn copy_from(values: impl AsRef<[T]>) -> Self {
107        BufferMut::copy_from(values).freeze()
108    }
109
110    /// Returns a new `Buffer<T>` copied from the provided slice and with the requested alignment.
111    pub fn copy_from_aligned(values: impl AsRef<[T]>, alignment: Alignment) -> Self {
112        BufferMut::copy_from_aligned(values, alignment).freeze()
113    }
114
115    /// Create a new zeroed `Buffer` with the given value.
116    pub fn zeroed(len: usize) -> Self {
117        Self::zeroed_aligned(len, Alignment::of::<T>())
118    }
119
120    /// Create a new zeroed `Buffer` with the given value.
121    pub fn zeroed_aligned(len: usize, alignment: Alignment) -> Self {
122        BufferMut::zeroed_aligned(len, alignment).freeze()
123    }
124
125    /// Create a new empty `ByteBuffer` with the provided alignment.
126    pub fn empty() -> Self {
127        BufferMut::empty().freeze()
128    }
129
130    /// Create a new empty `ByteBuffer` with the provided alignment.
131    pub fn empty_aligned(alignment: Alignment) -> Self {
132        BufferMut::empty_aligned(alignment).freeze()
133    }
134
135    /// Create a new full `ByteBuffer` with the given value.
136    pub fn full(item: T, len: usize) -> Self
137    where
138        T: Copy,
139    {
140        BufferMut::full(item, len).freeze()
141    }
142
143    /// Create a `Buffer<T>` zero-copy from a `ByteBuffer`.
144    ///
145    /// ## Panics
146    ///
147    /// Panics if the buffer is not aligned to the size of `T`, or the length is not a multiple of
148    /// the size of `T`.
149    pub fn from_byte_buffer(buffer: ByteBuffer) -> Self {
150        // TODO(ngates): should this preserve the current alignment of the buffer?
151        Self::from_byte_buffer_aligned(buffer, Alignment::of::<T>())
152    }
153
154    /// Create a `Buffer<T>` zero-copy from a `ByteBuffer`.
155    ///
156    /// ## Panics
157    ///
158    /// Panics if the buffer is not aligned to the given alignment, if the length is not a multiple
159    /// of the size of `T`, or if the given alignment is not aligned to that of `T`.
160    pub fn from_byte_buffer_aligned(buffer: ByteBuffer, alignment: Alignment) -> Self {
161        Self::from_bytes_aligned(buffer.into_inner(), alignment)
162    }
163
164    /// Create a `Buffer<T>` zero-copy from a `Bytes`.
165    ///
166    /// ## Panics
167    ///
168    /// Panics if the buffer is not aligned to the size of `T`, or the length is not a multiple of
169    /// the size of `T`.
170    pub fn from_bytes_aligned(bytes: Bytes, alignment: Alignment) -> Self {
171        if !alignment.is_aligned_to(Alignment::of::<T>()) {
172            vortex_panic!(
173                "Alignment {} must be compatible with the scalar type's alignment {}",
174                alignment,
175                Alignment::of::<T>(),
176            );
177        }
178        if bytes.as_ptr().align_offset(*alignment) != 0 {
179            vortex_panic!(
180                "Bytes alignment must align to the requested alignment {}",
181                alignment,
182            );
183        }
184        if !bytes.len().is_multiple_of(size_of::<T>()) {
185            vortex_panic!(
186                "Bytes length {} must be a multiple of the scalar type's size {}",
187                bytes.len(),
188                size_of::<T>()
189            );
190        }
191        let length = bytes.len() / size_of::<T>();
192        Self {
193            bytes,
194            length,
195            alignment,
196            _marker: Default::default(),
197        }
198    }
199
200    /// Create a buffer with values from the TrustedLen iterator.
201    /// Should be preferred over `from_iter` when the iterator is known to be `TrustedLen`.
202    pub fn from_trusted_len_iter<I: TrustedLen<Item = T>>(iter: I) -> Self {
203        let (_, upper_bound) = iter.size_hint();
204        let mut buffer = BufferMut::with_capacity(
205            upper_bound.vortex_expect("TrustedLen iterator has no upper bound"),
206        );
207        buffer.extend_trusted(iter);
208        buffer.freeze()
209    }
210
211    /// Clear the buffer, preserving existing capacity.
212    pub fn clear(&mut self) {
213        self.bytes.clear();
214        self.length = 0;
215    }
216
217    /// Returns the length of the buffer in elements of type T.
218    #[inline(always)]
219    pub fn len(&self) -> usize {
220        self.length
221    }
222
223    /// Returns whether the buffer is empty.
224    #[inline(always)]
225    pub fn is_empty(&self) -> bool {
226        self.length == 0
227    }
228
229    /// Returns the alignment of the buffer.
230    #[inline(always)]
231    pub fn alignment(&self) -> Alignment {
232        self.alignment
233    }
234
235    /// Returns a slice over the buffer of elements of type T.
236    #[inline(always)]
237    pub fn as_slice(&self) -> &[T] {
238        // SAFETY: alignment of Buffer is checked on construction
239        unsafe { std::slice::from_raw_parts(self.bytes.as_ptr().cast(), self.length) }
240    }
241
242    /// Return a view over the buffer as an opaque byte slice.
243    #[inline(always)]
244    pub fn as_bytes(&self) -> &[u8] {
245        self.bytes.as_ref()
246    }
247
248    /// Returns an iterator over the buffer of elements of type T.
249    pub fn iter(&self) -> Iter<'_, T> {
250        Iter {
251            inner: self.as_slice().iter(),
252        }
253    }
254
255    /// Returns a slice of self for the provided range.
256    ///
257    /// # Panics
258    ///
259    /// Requires that `begin <= end` and `end <= self.len()`.
260    /// Also requires that both `begin` and `end` are aligned to the buffer's required alignment.
261    #[inline(always)]
262    pub fn slice(&self, range: impl RangeBounds<usize>) -> Self {
263        self.slice_with_alignment(range, self.alignment)
264    }
265
266    /// Returns a slice of self for the provided range, with no guarantees about the resulting
267    /// alignment.
268    ///
269    /// # Panics
270    ///
271    /// Requires that `begin <= end` and `end <= self.len()`.
272    #[inline(always)]
273    pub fn slice_unaligned(&self, range: impl RangeBounds<usize>) -> Self {
274        self.slice_with_alignment(range, Alignment::of::<u8>())
275    }
276
277    /// Returns a slice of self for the provided range, ensuring the resulting slice has the
278    /// given alignment.
279    ///
280    /// # Panics
281    ///
282    /// Requires that `begin <= end` and `end <= self.len()`.
283    /// Also requires that both `begin` and `end` are aligned to the given alignment.
284    pub fn slice_with_alignment(
285        &self,
286        range: impl RangeBounds<usize>,
287        alignment: Alignment,
288    ) -> Self {
289        let len = self.len();
290        let begin = match range.start_bound() {
291            Bound::Included(&n) => n,
292            Bound::Excluded(&n) => n.checked_add(1).vortex_expect("out of range"),
293            Bound::Unbounded => 0,
294        };
295        let end = match range.end_bound() {
296            Bound::Included(&n) => n.checked_add(1).vortex_expect("out of range"),
297            Bound::Excluded(&n) => n,
298            Bound::Unbounded => len,
299        };
300
301        if begin > end {
302            vortex_panic!(
303                "range start must not be greater than end: {:?} <= {:?}",
304                begin,
305                end
306            );
307        }
308        if end > len {
309            vortex_panic!("range end out of bounds: {:?} > {:?}", end, len);
310        }
311
312        if end == begin {
313            // We prefer to return a new empty buffer instead of sharing this one and creating a
314            // strong reference just to hold an empty slice.
315            return Self::empty_aligned(alignment);
316        }
317
318        let begin_byte = begin * size_of::<T>();
319        let end_byte = end * size_of::<T>();
320
321        if !begin_byte.is_multiple_of(*alignment) {
322            vortex_panic!("range start must be aligned to {alignment:?}");
323        }
324        if !alignment.is_aligned_to(Alignment::of::<T>()) {
325            vortex_panic!("Slice alignment must at least align to type T")
326        }
327
328        Self {
329            bytes: self.bytes.slice(begin_byte..end_byte),
330            length: end - begin,
331            alignment,
332            _marker: Default::default(),
333        }
334    }
335
336    /// Returns a slice of self that is equivalent to the given subset.
337    ///
338    /// When processing the buffer you will often end up with `&[T]` that is a subset
339    /// of the underlying buffer. This function turns the slice into a slice of the buffer
340    /// it has been taken from.
341    ///
342    /// # Panics:
343    /// Requires that the given sub slice is in fact contained within the Bytes buffer; otherwise this function will panic.
344    #[inline(always)]
345    pub fn slice_ref(&self, subset: &[T]) -> Self {
346        self.slice_ref_with_alignment(subset, Alignment::of::<T>())
347    }
348
349    /// Returns a slice of self that is equivalent to the given subset.
350    ///
351    /// When processing the buffer you will often end up with `&[T]` that is a subset
352    /// of the underlying buffer. This function turns the slice into a slice of the buffer
353    /// it has been taken from.
354    ///
355    /// # Panics:
356    /// Requires that the given sub slice is in fact contained within the Bytes buffer; otherwise this function will panic.
357    /// Also requires that the given alignment aligns to the type of slice and is smaller or equal to the buffers alignment
358    pub fn slice_ref_with_alignment(&self, subset: &[T], alignment: Alignment) -> Self {
359        if !alignment.is_aligned_to(Alignment::of::<T>()) {
360            vortex_panic!("slice_ref alignment must at least align to type T")
361        }
362
363        if !self.alignment.is_aligned_to(alignment) {
364            vortex_panic!("slice_ref subset alignment must at least align to the buffer alignment")
365        }
366
367        if subset.as_ptr().align_offset(*alignment) != 0 {
368            vortex_panic!("slice_ref subset must be aligned to {:?}", alignment);
369        }
370
371        let subset_u8 =
372            unsafe { std::slice::from_raw_parts(subset.as_ptr().cast(), size_of_val(subset)) };
373
374        Self {
375            bytes: self.bytes.slice_ref(subset_u8),
376            length: subset.len(),
377            alignment,
378            _marker: Default::default(),
379        }
380    }
381
382    /// Returns the underlying aligned buffer.
383    pub fn inner(&self) -> &Bytes {
384        debug_assert_eq!(
385            self.length * size_of::<T>(),
386            self.bytes.len(),
387            "Own length has to be the same as the underlying bytes length"
388        );
389        &self.bytes
390    }
391
392    /// Returns the underlying aligned buffer.
393    pub fn into_inner(self) -> Bytes {
394        debug_assert_eq!(
395            self.length * size_of::<T>(),
396            self.bytes.len(),
397            "Own length has to be the same as the underlying bytes length"
398        );
399        self.bytes
400    }
401
402    /// Return the ByteBuffer for this `Buffer<T>`.
403    pub fn into_byte_buffer(self) -> ByteBuffer {
404        ByteBuffer {
405            bytes: self.bytes,
406            length: self.length * size_of::<T>(),
407            alignment: self.alignment,
408            _marker: Default::default(),
409        }
410    }
411
412    /// Try to convert self into `BufferMut<T>` if there is only a single strong reference.
413    pub fn try_into_mut(self) -> Result<BufferMut<T>, Self> {
414        self.bytes
415            .try_into_mut()
416            .map(|bytes| BufferMut {
417                bytes,
418                length: self.length,
419                alignment: self.alignment,
420                _marker: Default::default(),
421            })
422            .map_err(|bytes| Self {
423                bytes,
424                length: self.length,
425                alignment: self.alignment,
426                _marker: Default::default(),
427            })
428    }
429
430    /// Convert self into `BufferMut<T>`, cloning the data if there are multiple strong references.
431    pub fn into_mut(self) -> BufferMut<T> {
432        self.try_into_mut()
433            .unwrap_or_else(|buffer| BufferMut::<T>::copy_from(&buffer))
434    }
435
436    /// Returns whether a `Buffer<T>` is aligned to the given alignment.
437    pub fn is_aligned(&self, alignment: Alignment) -> bool {
438        self.bytes.as_ptr().align_offset(*alignment) == 0
439    }
440
441    /// Return a `Buffer<T>` with the given alignment. Where possible, this will be zero-copy.
442    pub fn aligned(mut self, alignment: Alignment) -> Self {
443        if self.as_ptr().align_offset(*alignment) == 0 {
444            self.alignment = alignment;
445            self
446        } else {
447            #[cfg(feature = "warn-copy")]
448            {
449                let bt = std::backtrace::Backtrace::capture();
450                tracing::warn!(
451                    "Buffer is not aligned to requested alignment {alignment}, copying: {bt}"
452                )
453            }
454            Self::copy_from_aligned(self, alignment)
455        }
456    }
457
458    /// Return a `Buffer<T>` with the given alignment. Panics if the buffer is not aligned.
459    pub fn ensure_aligned(mut self, alignment: Alignment) -> Self {
460        if self.as_ptr().align_offset(*alignment) == 0 {
461            self.alignment = alignment;
462            self
463        } else {
464            vortex_panic!("Buffer is not aligned to requested alignment {}", alignment)
465        }
466    }
467}
468
469impl<T> Buffer<T> {
470    /// Transmute a `Buffer<T>` into a `Buffer<U>`.
471    ///
472    /// # Safety
473    ///
474    /// The caller must ensure that all possible bit representations of type `T` are valid when
475    /// interpreted as type `U`.
476    /// See [`std::mem::transmute`] for more details.
477    ///
478    /// # Panics
479    ///
480    /// Panics if the type `U` does not have the same size and alignment as `T`.
481    pub unsafe fn transmute<U>(self) -> Buffer<U> {
482        assert_eq!(size_of::<T>(), size_of::<U>(), "Buffer type size mismatch");
483        assert_eq!(
484            align_of::<T>(),
485            align_of::<U>(),
486            "Buffer type alignment mismatch"
487        );
488
489        Buffer {
490            bytes: self.bytes,
491            length: self.length,
492            alignment: self.alignment,
493            _marker: PhantomData,
494        }
495    }
496}
497
498/// An iterator over Buffer elements.
499///
500/// This is an analog to the `std::slice::Iter` type.
501pub struct Iter<'a, T> {
502    inner: std::slice::Iter<'a, T>,
503}
504
505impl<'a, T> Iterator for Iter<'a, T> {
506    type Item = &'a T;
507
508    #[inline]
509    fn next(&mut self) -> Option<Self::Item> {
510        self.inner.next()
511    }
512
513    #[inline]
514    fn size_hint(&self) -> (usize, Option<usize>) {
515        self.inner.size_hint()
516    }
517
518    #[inline]
519    fn count(self) -> usize {
520        self.inner.count()
521    }
522
523    #[inline]
524    fn last(self) -> Option<Self::Item> {
525        self.inner.last()
526    }
527
528    #[inline]
529    fn nth(&mut self, n: usize) -> Option<Self::Item> {
530        self.inner.nth(n)
531    }
532}
533
534impl<T> ExactSizeIterator for Iter<'_, T> {
535    #[inline]
536    fn len(&self) -> usize {
537        self.inner.len()
538    }
539}
540
541impl<T: Debug> Debug for Buffer<T> {
542    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
543        f.debug_struct(&format!("Buffer<{}>", type_name::<T>()))
544            .field("length", &self.length)
545            .field("alignment", &self.alignment)
546            .field("as_slice", &TruncatedDebug(self.as_slice()))
547            .finish()
548    }
549}
550
551impl<T> Deref for Buffer<T> {
552    type Target = [T];
553
554    #[inline]
555    fn deref(&self) -> &Self::Target {
556        self.as_slice()
557    }
558}
559
560impl<T> AsRef<[T]> for Buffer<T> {
561    #[inline]
562    fn as_ref(&self) -> &[T] {
563        self.as_slice()
564    }
565}
566
567impl<T> FromIterator<T> for Buffer<T> {
568    #[inline]
569    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
570        BufferMut::from_iter(iter).freeze()
571    }
572}
573
574// Helper struct to allow us to zero-copy any vec into a buffer
575#[repr(transparent)]
576struct Wrapper<T>(Vec<T>);
577
578impl<T> AsRef<[u8]> for Wrapper<T> {
579    fn as_ref(&self) -> &[u8] {
580        let data = self.0.as_ptr().cast::<u8>();
581        let len = self.0.len() * size_of::<T>();
582        unsafe { std::slice::from_raw_parts(data, len) }
583    }
584}
585
586impl<T> From<Vec<T>> for Buffer<T>
587where
588    T: Send + 'static,
589{
590    fn from(value: Vec<T>) -> Self {
591        let original_len = value.len();
592        let wrapped_vec = Wrapper(value);
593
594        let bytes = Bytes::from_owner(wrapped_vec);
595
596        assert_eq!(bytes.as_ptr().align_offset(align_of::<T>()), 0);
597
598        Self {
599            bytes,
600            length: original_len,
601            alignment: Alignment::of::<T>(),
602            _marker: PhantomData,
603        }
604    }
605}
606
607impl From<Bytes> for ByteBuffer {
608    fn from(bytes: Bytes) -> Self {
609        let length = bytes.len();
610        Self {
611            bytes,
612            length,
613            alignment: Alignment::of::<u8>(),
614            _marker: Default::default(),
615        }
616    }
617}
618
619impl Buf for ByteBuffer {
620    #[inline]
621    fn remaining(&self) -> usize {
622        self.len()
623    }
624
625    #[inline]
626    fn chunk(&self) -> &[u8] {
627        self.as_slice()
628    }
629
630    #[inline]
631    fn advance(&mut self, cnt: usize) {
632        if !cnt.is_multiple_of(*self.alignment) {
633            vortex_panic!(
634                "Cannot advance buffer by {} items, resulting alignment is not {}",
635                cnt,
636                self.alignment
637            );
638        }
639        self.bytes.advance(cnt);
640        self.length -= cnt;
641    }
642}
643
644/// Owned iterator over a [`Buffer`].
645pub struct BufferIterator<T> {
646    buffer: Buffer<T>,
647    index: usize,
648}
649
650impl<T: Copy> Iterator for BufferIterator<T> {
651    type Item = T;
652
653    #[inline]
654    fn next(&mut self) -> Option<Self::Item> {
655        (self.index < self.buffer.len()).then(move || {
656            let value = self.buffer[self.index];
657            self.index += 1;
658            value
659        })
660    }
661
662    #[inline]
663    fn size_hint(&self) -> (usize, Option<usize>) {
664        let remaining = self.buffer.len() - self.index;
665        (remaining, Some(remaining))
666    }
667}
668
669impl<T: Copy> IntoIterator for Buffer<T> {
670    type Item = T;
671    type IntoIter = BufferIterator<T>;
672
673    #[inline]
674    fn into_iter(self) -> Self::IntoIter {
675        BufferIterator {
676            buffer: self,
677            index: 0,
678        }
679    }
680}
681
682impl<T> From<BufferMut<T>> for Buffer<T> {
683    #[inline]
684    fn from(value: BufferMut<T>) -> Self {
685        value.freeze()
686    }
687}
688
689#[cfg(test)]
690mod test {
691    use bytes::Buf;
692
693    use crate::Alignment;
694    use crate::Buffer;
695    use crate::ByteBuffer;
696    use crate::buffer;
697
698    #[test]
699    fn align() {
700        let buf = buffer![0u8, 1, 2];
701        let aligned = buf.aligned(Alignment::new(32));
702        assert_eq!(aligned.alignment(), Alignment::new(32));
703        assert_eq!(aligned.as_slice(), &[0, 1, 2]);
704    }
705
706    #[test]
707    fn slice() {
708        let buf = buffer![0, 1, 2, 3, 4];
709        assert_eq!(buf.slice(1..3).as_slice(), &[1, 2]);
710        assert_eq!(buf.slice(1..=3).as_slice(), &[1, 2, 3]);
711    }
712
713    #[test]
714    fn slice_unaligned() {
715        let buf = buffer![0i32, 1, 2, 3, 4].into_byte_buffer();
716        // With a regular slice, this would panic. See [`slice_bad_alignment`].
717        let sliced = buf.slice_unaligned(1..2);
718        // Verify the slice has the expected length (1 byte from index 1 to 2).
719        assert_eq!(sliced.len(), 1);
720        // The original buffer has i32 values [0, 1, 2, 3, 4].
721        // In little-endian bytes, 0i32 = [0, 0, 0, 0], so byte at index 1 is 0.
722        assert_eq!(sliced.as_slice(), &[0]);
723    }
724
725    #[test]
726    #[should_panic]
727    fn slice_bad_alignment() {
728        let buf = buffer![0i32, 1, 2, 3, 4].into_byte_buffer();
729        // We should only be able to slice this buffer on 4-byte (i32) boundaries.
730        buf.slice(1..2);
731    }
732
733    #[test]
734    fn bytes_buf() {
735        let mut buf = ByteBuffer::copy_from("helloworld".as_bytes());
736        assert_eq!(buf.remaining(), 10);
737        assert_eq!(buf.chunk(), b"helloworld");
738
739        Buf::advance(&mut buf, 5);
740        assert_eq!(buf.remaining(), 5);
741        assert_eq!(buf.as_slice(), b"world");
742        assert_eq!(buf.chunk(), b"world");
743    }
744
745    #[test]
746    fn from_vec() {
747        let vec = vec![1, 2, 3, 4, 5];
748        let buff = Buffer::from(vec.clone());
749        assert!(buff.is_aligned(Alignment::of::<i32>()));
750        assert_eq!(vec, buff);
751    }
752
753    #[test]
754    fn test_slice_unaligned_end_pos() {
755        let data = vec![0u8; 2];
756        // Overalign the u8 vector.
757        let aligned_buffer = Buffer::copy_from_aligned(&data, Alignment::new(8));
758        // Previously, `Buffer::slice` incorrectly asserted that the end position
759        // must be aligned. That assertion has been removed such that the end
760        // position can be arbitrary and only the beginning of the slice needs
761        // to be aligned.
762        aligned_buffer.slice(0..1);
763    }
764}