• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vortex-data / vortex / 16980313501

15 Aug 2025 01:01AM UTC coverage: 87.714% (-0.006%) from 87.72%
16980313501

Pull #2456

github

web-flow
Merge 02c3c7f9e into aaf3e36ad
Pull Request #2456: feat: basic BoolBuffer / BoolBufferMut

1267 of 1420 new or added lines in 110 files covered. (89.23%)

4 existing lines in 3 files now uncovered.

56995 of 64978 relevant lines covered (87.71%)

658370.36 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.03
/vortex-buffer/src/buffer.rs
1
// SPDX-License-Identifier: Apache-2.0
2
// SPDX-FileCopyrightText: Copyright the Vortex contributors
3

4
use std::any::type_name;
5
use std::cmp::Ordering;
6
use std::collections::Bound;
7
use std::fmt::{Debug, Formatter};
8
use std::hash::{Hash, Hasher};
9
use std::ops::{Deref, RangeBounds};
10

11
use bytes::{Buf, Bytes};
12
use vortex_error::{VortexExpect, vortex_panic};
13

14
use crate::debug::TruncatedDebug;
15
use crate::trusted_len::TrustedLen;
16
use crate::{Alignment, BitChunks, BufferMut, ByteBuffer};
17

18
/// An immutable buffer of items of `T`.
19
#[derive(Clone)]
20
pub struct Buffer<T> {
21
    pub(crate) bytes: Bytes,
22
    pub(crate) length: usize,
23
    pub(crate) alignment: Alignment,
24
    pub(crate) _marker: std::marker::PhantomData<T>,
25
}
26

27
impl<T> PartialEq for Buffer<T> {
28
    fn eq(&self, other: &Self) -> bool {
391,482✔
29
        self.bytes == other.bytes
391,482✔
30
    }
391,482✔
31
}
32

33
impl<T> Eq for Buffer<T> {}
34

35
impl<T> Ord for Buffer<T> {
36
    fn cmp(&self, other: &Self) -> Ordering {
9,853✔
37
        self.bytes.cmp(&other.bytes)
9,853✔
38
    }
9,853✔
39
}
40

41
impl<T> PartialOrd for Buffer<T> {
42
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
×
43
        Some(self.cmp(other))
×
44
    }
×
45
}
46

47
impl<T> Hash for Buffer<T> {
48
    fn hash<H: Hasher>(&self, state: &mut H) {
8,724✔
49
        self.bytes.as_ref().hash(state)
8,724✔
50
    }
8,724✔
51
}
52

53
impl<T> Buffer<T> {
54
    /// Returns a new `Buffer<T>` copied from the provided `Vec<T>`, `&[T]`, etc.
55
    ///
56
    /// Due to our underlying usage of `bytes::Bytes`, we are unable to take zero-copy ownership
57
    /// of the provided `Vec<T>` while maintaining the ability to convert it back into a mutable
58
    /// buffer. We could fix this by forking `Bytes`, or in many other complex ways, but for now
59
    /// callers should prefer to construct `Buffer<T>` from a `BufferMut<T>`.
60
    pub fn copy_from(values: impl AsRef<[T]>) -> Self {
18,272✔
61
        BufferMut::copy_from(values).freeze()
18,272✔
62
    }
18,272✔
63

64
    /// Returns a new `Buffer<T>` copied from the provided slice and with the requested alignment.
65
    pub fn copy_from_aligned(values: impl AsRef<[T]>, alignment: Alignment) -> Self {
3,225✔
66
        BufferMut::copy_from_aligned(values, alignment).freeze()
3,225✔
67
    }
3,225✔
68

69
    /// Create a new zeroed `Buffer` with the given value.
70
    pub fn zeroed(len: usize) -> Self {
28,087✔
71
        Self::zeroed_aligned(len, Alignment::of::<T>())
28,087✔
72
    }
28,087✔
73

74
    /// Create a new zeroed `Buffer` with the given value.
75
    pub fn zeroed_aligned(len: usize, alignment: Alignment) -> Self {
37,007✔
76
        BufferMut::zeroed_aligned(len, alignment).freeze()
37,007✔
77
    }
37,007✔
78

79
    /// Create a new empty `ByteBuffer` with the provided alignment.
80
    pub fn empty() -> Self {
579,333✔
81
        BufferMut::empty().freeze()
579,333✔
82
    }
579,333✔
83

84
    /// Create a new empty `ByteBuffer` with the provided alignment.
85
    pub fn empty_aligned(alignment: Alignment) -> Self {
10,452✔
86
        BufferMut::empty_aligned(alignment).freeze()
10,452✔
87
    }
10,452✔
88

89
    /// Create a new full `ByteBuffer` with the given value.
90
    pub fn full(item: T, len: usize) -> Self
268,239✔
91
    where
268,239✔
92
        T: Copy,
268,239✔
93
    {
94
        BufferMut::full(item, len).freeze()
268,239✔
95
    }
268,239✔
96

97
    /// Create a `Buffer<T>` zero-copy from a `ByteBuffer`.
98
    ///
99
    /// ## Panics
100
    ///
101
    /// Panics if the buffer is not aligned to the size of `T`, or the length is not a multiple of
102
    /// the size of `T`.
103
    pub fn from_byte_buffer(buffer: ByteBuffer) -> Self {
3,430,898✔
104
        // TODO(ngates): should this preserve the current alignment of the buffer?
105
        Self::from_byte_buffer_aligned(buffer, Alignment::of::<T>())
3,430,898✔
106
    }
3,430,898✔
107

108
    /// Create a `Buffer<T>` zero-copy from a `ByteBuffer`.
109
    ///
110
    /// ## Panics
111
    ///
112
    /// Panics if the buffer is not aligned to the given alignment, if the length is not a multiple
113
    /// of the size of `T`, or if the given alignment is not aligned to that of `T`.
114
    pub fn from_byte_buffer_aligned(buffer: ByteBuffer, alignment: Alignment) -> Self {
3,574,091✔
115
        Self::from_bytes_aligned(buffer.into_inner(), alignment)
3,574,091✔
116
    }
3,574,091✔
117

118
    /// Create a `Buffer<T>` zero-copy from a `Bytes`.
119
    ///
120
    /// ## Panics
121
    ///
122
    /// Panics if the buffer is not aligned to the size of `T`, or the length is not a multiple of
123
    /// the size of `T`.
124
    pub fn from_bytes_aligned(bytes: Bytes, alignment: Alignment) -> Self {
3,917,289✔
125
        if !alignment.is_aligned_to(Alignment::of::<T>()) {
3,917,289✔
126
            vortex_panic!(
×
127
                "Alignment {} must be compatible with the scalar type's alignment {}",
×
128
                alignment,
129
                Alignment::of::<T>(),
×
130
            );
131
        }
3,917,289✔
132
        if bytes.as_ptr().align_offset(*alignment) != 0 {
3,917,289✔
133
            vortex_panic!(
×
134
                "Bytes alignment must align to the requested alignment {}",
×
135
                alignment,
136
            );
137
        }
3,917,289✔
138
        if bytes.len() % size_of::<T>() != 0 {
3,917,289✔
139
            vortex_panic!(
×
140
                "Bytes length {} must be a multiple of the scalar type's size {}",
×
141
                bytes.len(),
×
142
                size_of::<T>()
143
            );
144
        }
3,917,289✔
145
        let length = bytes.len() / size_of::<T>();
3,917,289✔
146
        Self {
3,917,289✔
147
            bytes,
3,917,289✔
148
            length,
3,917,289✔
149
            alignment,
3,917,289✔
150
            _marker: Default::default(),
3,917,289✔
151
        }
3,917,289✔
152
    }
3,917,289✔
153

154
    /// Create a buffer with values from the TrustedLen iterator.
155
    /// Should be preferred over `from_iter` when the iterator is known to be `TrustedLen`.
156
    pub fn from_trusted_len_iter<I: TrustedLen<Item = T>>(iter: I) -> Self {
2,018✔
157
        let (_, high) = iter.size_hint();
2,018✔
158
        let mut buffer =
2,018✔
159
            BufferMut::with_capacity(high.vortex_expect("TrustedLen iterator has no upper bound"));
2,018✔
160
        buffer.extend_trusted(iter);
2,018✔
161
        buffer.freeze()
2,018✔
162
    }
2,018✔
163

164
    /// Returns the length of the buffer in elements of type T.
165
    #[inline(always)]
166
    pub fn len(&self) -> usize {
275,905,748✔
167
        self.length
275,905,748✔
168
    }
275,905,748✔
169

170
    /// Returns whether the buffer is empty.
171
    #[inline(always)]
172
    pub fn is_empty(&self) -> bool {
144,475✔
173
        self.length == 0
144,475✔
174
    }
144,475✔
175

176
    /// Returns the alignment of the buffer.
177
    #[inline(always)]
178
    pub fn alignment(&self) -> Alignment {
112,974✔
179
        self.alignment
112,974✔
180
    }
112,974✔
181

182
    /// Returns a slice over the buffer of elements of type T.
183
    #[inline(always)]
184
    pub fn as_slice(&self) -> &[T] {
218,919,829✔
185
        let raw_slice = self.bytes.as_ref();
218,919,829✔
186
        // SAFETY: alignment of Buffer is checked on construction
187
        unsafe { std::slice::from_raw_parts(raw_slice.as_ptr().cast(), self.length) }
218,919,829✔
188
    }
218,919,829✔
189

190
    /// Returns an iterator over the buffer of elements of type T.
191
    pub fn iter(&self) -> Iter<'_, T> {
54,080✔
192
        Iter {
54,080✔
193
            inner: self.as_slice().iter(),
54,080✔
194
        }
54,080✔
195
    }
54,080✔
196

197
    /// Returns a slice of self for the provided range.
198
    ///
199
    /// # Panics
200
    ///
201
    /// Requires that `begin <= end` and `end <= self.len()`.
202
    /// Also requires that both `begin` and `end` are aligned to the buffer's required alignment.
203
    #[inline(always)]
204
    pub fn slice(&self, range: impl RangeBounds<usize>) -> Self {
7,890,951✔
205
        self.slice_with_alignment(range, self.alignment)
7,890,951✔
206
    }
7,890,951✔
207

208
    /// Returns a slice of self for the provided range, with no guarantees about the resulting
209
    /// alignment.
210
    ///
211
    /// # Panics
212
    ///
213
    /// Requires that `begin <= end` and `end <= self.len()`.
214
    #[inline(always)]
215
    pub fn slice_unaligned(&self, range: impl RangeBounds<usize>) -> Self {
3✔
216
        self.slice_with_alignment(range, Alignment::of::<u8>())
3✔
217
    }
3✔
218

219
    /// Returns a slice of self for the provided range, ensuring the resulting slice has the
220
    /// given alignment.
221
    ///
222
    /// # Panics
223
    ///
224
    /// Requires that `begin <= end` and `end <= self.len()`.
225
    /// Also requires that both `begin` and `end` are aligned to the given alignment.
226
    pub fn slice_with_alignment(
8,692,276✔
227
        &self,
8,692,276✔
228
        range: impl RangeBounds<usize>,
8,692,276✔
229
        alignment: Alignment,
8,692,276✔
230
    ) -> Self {
8,692,276✔
231
        let len = self.len();
8,692,276✔
232
        let begin = match range.start_bound() {
8,692,276✔
233
            Bound::Included(&n) => n,
8,690,338✔
234
            Bound::Excluded(&n) => n.checked_add(1).vortex_expect("out of range"),
×
235
            Bound::Unbounded => 0,
1,938✔
236
        };
237
        let end = match range.end_bound() {
8,692,276✔
238
            Bound::Included(&n) => n.checked_add(1).vortex_expect("out of range"),
1✔
239
            Bound::Excluded(&n) => n,
8,692,275✔
240
            Bound::Unbounded => len,
×
241
        };
242

243
        if begin > end {
8,692,276✔
244
            vortex_panic!(
×
245
                "range start must not be greater than end: {:?} <= {:?}",
×
246
                begin,
247
                end
248
            );
249
        }
8,692,276✔
250
        if end > len {
8,692,276✔
251
            vortex_panic!("range end out of bounds: {:?} <= {:?}", end, len);
×
252
        }
8,692,276✔
253

254
        if end == begin {
8,692,276✔
255
            // We prefer to return a new empty buffer instead of sharing this one and creating a
256
            // strong reference just to hold an empty slice.
257
            return Self::empty_aligned(alignment);
10,452✔
258
        }
8,681,824✔
259

260
        let begin_byte = begin * size_of::<T>();
8,681,824✔
261
        let end_byte = end * size_of::<T>();
8,681,824✔
262

263
        if !begin_byte.is_multiple_of(*alignment) {
8,681,824✔
264
            vortex_panic!("range start must be aligned to {alignment:?}");
1✔
265
        }
8,681,823✔
266
        if !end_byte.is_multiple_of(*alignment) {
8,681,823✔
NEW
267
            vortex_panic!("range end must be aligned to {alignment:?}");
×
268
        }
8,681,823✔
269
        if !alignment.is_aligned_to(Alignment::of::<T>()) {
8,681,823✔
270
            vortex_panic!("Slice alignment must at least align to type T")
×
271
        }
8,681,823✔
272

273
        Self {
8,681,823✔
274
            bytes: self.bytes.slice(begin_byte..end_byte),
8,681,823✔
275
            length: end - begin,
8,681,823✔
276
            alignment,
8,681,823✔
277
            _marker: Default::default(),
8,681,823✔
278
        }
8,681,823✔
279
    }
8,692,275✔
280

281
    /// Returns a slice of self that is equivalent to the given subset.
282
    ///
283
    /// When processing the buffer you will often end up with &\[T\] that is a subset
284
    /// of the underlying buffer. This function turns the slice into a slice of the buffer
285
    /// it has been taken from.
286
    ///
287
    /// # Panics:
288
    /// Requires that the given sub slice is in fact contained within the Bytes buffer; otherwise this function will panic.
289
    #[inline(always)]
290
    pub fn slice_ref(&self, subset: &[T]) -> Self {
256,517✔
291
        self.slice_ref_with_alignment(subset, Alignment::of::<T>())
256,517✔
292
    }
256,517✔
293

294
    /// Returns a slice of self that is equivalent to the given subset.
295
    ///
296
    /// When processing the buffer you will often end up with &\[T\] that is a subset
297
    /// of the underlying buffer. This function turns the slice into a slice of the buffer
298
    /// it has been taken from.
299
    ///
300
    /// # Panics:
301
    /// Requires that the given sub slice is in fact contained within the Bytes buffer; otherwise this function will panic.
302
    /// Also requires that the given alignment aligns to the type of slice and is smaller or equal to the buffers alignment
303
    pub fn slice_ref_with_alignment(&self, subset: &[T], alignment: Alignment) -> Self {
328,527✔
304
        if !alignment.is_aligned_to(Alignment::of::<T>()) {
328,527✔
305
            vortex_panic!("slice_ref alignment must at least align to type T")
×
306
        }
328,527✔
307

308
        if !self.alignment.is_aligned_to(alignment) {
328,527✔
309
            vortex_panic!("slice_ref subset alignment must at least align to the buffer alignment")
×
310
        }
328,527✔
311

312
        if subset.as_ptr().align_offset(*alignment) != 0 {
328,527✔
313
            vortex_panic!("slice_ref subset must be aligned to {:?}", alignment);
×
314
        }
328,527✔
315

316
        let subset_u8 =
328,527✔
317
            unsafe { std::slice::from_raw_parts(subset.as_ptr().cast(), size_of_val(subset)) };
328,527✔
318

319
        Self {
328,527✔
320
            bytes: self.bytes.slice_ref(subset_u8),
328,527✔
321
            length: subset.len(),
328,527✔
322
            alignment,
328,527✔
323
            _marker: Default::default(),
328,527✔
324
        }
328,527✔
325
    }
328,527✔
326

327
    /// Returns the underlying aligned buffer.
328
    pub fn inner(&self) -> &Bytes {
×
329
        debug_assert_eq!(
×
330
            self.length * size_of::<T>(),
×
331
            self.bytes.len(),
×
332
            "Own length has to be the same as the underlying bytes length"
×
333
        );
334
        &self.bytes
×
335
    }
×
336

337
    /// Returns the underlying aligned buffer.
338
    pub fn into_inner(self) -> Bytes {
4,459,619✔
339
        debug_assert_eq!(
4,459,619✔
340
            self.length * size_of::<T>(),
4,459,619✔
341
            self.bytes.len(),
4,459,619✔
342
            "Own length has to be the same as the underlying bytes length"
×
343
        );
344
        self.bytes
4,459,619✔
345
    }
4,459,619✔
346

347
    /// Return the ByteBuffer for this `Buffer<T>`.
348
    pub fn into_byte_buffer(self) -> ByteBuffer {
6,389,671✔
349
        ByteBuffer {
6,389,671✔
350
            bytes: self.bytes,
6,389,671✔
351
            length: self.length * size_of::<T>(),
6,389,671✔
352
            alignment: self.alignment,
6,389,671✔
353
            _marker: Default::default(),
6,389,671✔
354
        }
6,389,671✔
355
    }
6,389,671✔
356

357
    /// Convert self into `BufferMut<T>`, copying if there are multiple strong references.
358
    pub fn into_mut(self) -> BufferMut<T> {
4,528✔
359
        self.try_into_mut()
4,528✔
360
            .unwrap_or_else(|buffer| BufferMut::<T>::copy_from(&buffer))
4,528✔
361
    }
4,528✔
362

363
    /// Try to convert self into `BufferMut<T>` if there is only a single strong reference.
364
    pub fn try_into_mut(self) -> Result<BufferMut<T>, Self> {
88,549✔
365
        self.bytes
88,549✔
366
            .try_into_mut()
88,549✔
367
            .map(|bytes| BufferMut {
88,549✔
368
                bytes,
38,058✔
369
                length: self.length,
38,058✔
370
                alignment: self.alignment,
38,058✔
371
                _marker: Default::default(),
38,058✔
372
            })
38,058✔
373
            .map_err(|bytes| Self {
88,549✔
374
                bytes,
50,491✔
375
                length: self.length,
50,491✔
376
                alignment: self.alignment,
50,491✔
377
                _marker: Default::default(),
50,491✔
378
            })
50,491✔
379
    }
88,549✔
380

381
    /// Returns an accessor which can be used to perform bitwise operations in u64 sized chunks
382
    pub fn bit_chunks(self, bit_offset: usize, bit_length: usize) -> BitChunks {
116,482✔
383
        BitChunks::new(self.into_byte_buffer(), bit_offset, bit_length)
116,482✔
384
    }
116,482✔
385

386
    /// Returns whether a `Buffer<T>` is aligned to the given alignment.
387
    pub fn is_aligned(&self, alignment: Alignment) -> bool {
7,678✔
388
        self.bytes.as_ptr().align_offset(*alignment) == 0
7,678✔
389
    }
7,678✔
390

391
    /// Return a `Buffer<T>` with the given alignment. Where possible, this will be zero-copy.
392
    pub fn aligned(mut self, alignment: Alignment) -> Self {
556,438✔
393
        if self.as_ptr().align_offset(*alignment) == 0 {
556,438✔
394
            self.alignment = alignment;
554,736✔
395
            self
554,736✔
396
        } else {
397
            #[cfg(feature = "warn-copy")]
398
            {
399
                let bt = std::backtrace::Backtrace::capture();
1,412✔
400
                log::warn!(
1,412✔
401
                    "Buffer is not aligned to requested alignment {alignment}, copying: {bt}"
402
                )
403
            }
404
            Self::copy_from_aligned(self, alignment)
1,702✔
405
        }
406
    }
556,438✔
407

408
    /// Return a `Buffer<T>` with the given alignment. Panics if the buffer is not aligned.
409
    pub fn ensure_aligned(mut self, alignment: Alignment) -> Self {
×
410
        if self.as_ptr().align_offset(*alignment) == 0 {
×
411
            self.alignment = alignment;
×
412
            self
×
413
        } else {
414
            vortex_panic!("Buffer is not aligned to requested alignment {}", alignment)
×
415
        }
416
    }
×
417

418
    /// Align the buffer to alignment of U
419
    pub fn align_to<U>(mut self) -> (Buffer<T>, Buffer<U>, Buffer<T>) {
71,270✔
420
        let offset = self.as_ptr().align_offset(align_of::<U>());
71,270✔
421
        if offset > self.len() {
71,270✔
NEW
422
            (
×
NEW
423
                self,
×
NEW
424
                Buffer::empty_aligned(Alignment::of::<U>()),
×
NEW
425
                Buffer::empty_aligned(Alignment::of::<T>()),
×
NEW
426
            )
×
427
        } else {
428
            let left = self.bytes.split_to(offset);
71,270✔
429
            let (us_len, _) = self.align_to_offsets::<U>();
71,270✔
430
            let trailer = self.bytes.split_off(us_len * size_of::<U>());
71,270✔
431
            (
71,270✔
432
                Buffer::from_bytes_aligned(left, Alignment::of::<T>()),
71,270✔
433
                Buffer::from_bytes_aligned(self.bytes, Alignment::of::<U>()),
71,270✔
434
                Buffer::from_bytes_aligned(trailer, Alignment::of::<T>()),
71,270✔
435
            )
71,270✔
436
        }
437
    }
71,270✔
438

439
    /// Adapted from standard library slice::align_to_offsets
440
    /// Function to calculate lengths of the middle and trailing slice for `align_to`.
441
    fn align_to_offsets<U>(&self) -> (usize, usize) {
71,270✔
442
        // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
443
        // lowest number of `T`s. And how many `T`s we need for each such "multiple".
444
        //
445
        // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
446
        // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
447
        // place of every 3 Ts in the `rest` slice. A bit more complicated.
448
        //
449
        // Formula to calculate this is:
450
        //
451
        // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
452
        // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
453
        //
454
        // Expanded and simplified:
455
        //
456
        // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
457
        // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
458
        //
459
        // Luckily since all this is constant-evaluated... performance here matters not!
NEW
460
        const fn gcd(a: usize, b: usize) -> usize {
×
NEW
461
            if b == 0 { a } else { gcd(b, a % b) }
×
NEW
462
        }
×
463

464
        // Explicitly wrap the function call in a const block so it gets
465
        // constant-evaluated even in debug mode.
466
        let gcd: usize = const { gcd(size_of::<T>(), size_of::<U>()) };
71,270✔
467
        let ts: usize = size_of::<U>() / gcd;
71,270✔
468
        let us: usize = size_of::<T>() / gcd;
71,270✔
469

470
        // Armed with this knowledge, we can find how many `U`s we can fit!
471
        let us_len = self.len() / ts * us;
71,270✔
472
        // And how many `T`s will be in the trailing slice!
473
        let ts_len = self.len() % ts;
71,270✔
474
        (us_len, ts_len)
71,270✔
475
    }
71,270✔
476
}
477

478
/// An iterator over Buffer elements.
479
///
480
/// This is an analog to the `std::slice::Iter` type.
481
pub struct Iter<'a, T> {
482
    inner: std::slice::Iter<'a, T>,
483
}
484

485
impl<'a, T> Iterator for Iter<'a, T> {
486
    type Item = &'a T;
487

488
    fn next(&mut self) -> Option<Self::Item> {
93,863,655✔
489
        self.inner.next()
93,863,655✔
490
    }
93,863,655✔
491

492
    fn size_hint(&self) -> (usize, Option<usize>) {
12,556✔
493
        self.inner.size_hint()
12,556✔
494
    }
12,556✔
495

496
    fn count(self) -> usize {
×
497
        self.inner.count()
×
498
    }
×
499

500
    fn last(self) -> Option<Self::Item> {
×
501
        self.inner.last()
×
502
    }
×
503

504
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
×
505
        self.inner.nth(n)
×
506
    }
×
507
}
508

509
impl<T> ExactSizeIterator for Iter<'_, T> {
510
    fn len(&self) -> usize {
×
511
        self.inner.len()
×
512
    }
×
513
}
514

515
impl<T: Debug> Debug for Buffer<T> {
516
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
80✔
517
        f.debug_struct(&format!("Buffer<{}>", type_name::<T>()))
80✔
518
            .field("length", &self.length)
80✔
519
            .field("alignment", &self.alignment)
80✔
520
            .field("as_slice", &TruncatedDebug(self.as_slice()))
80✔
521
            .finish()
80✔
522
    }
80✔
523
}
524

525
impl<T> Deref for Buffer<T> {
526
    type Target = [T];
527

528
    fn deref(&self) -> &Self::Target {
213,700,271✔
529
        self.as_slice()
213,700,271✔
530
    }
213,700,271✔
531
}
532

533
impl<T> AsRef<[T]> for Buffer<T> {
534
    fn as_ref(&self) -> &[T] {
5,036,074✔
535
        self.as_slice()
5,036,074✔
536
    }
5,036,074✔
537
}
538

539
impl<T> FromIterator<T> for Buffer<T> {
540
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
108,183✔
541
        BufferMut::from_iter(iter).freeze()
108,183✔
542
    }
108,183✔
543
}
544

545
/// Only for `Buffer<u8>` can we zero-copy from a `Vec<u8>` since we can use a 1-byte alignment.
546
impl From<Vec<u8>> for ByteBuffer {
547
    fn from(value: Vec<u8>) -> Self {
604,924✔
548
        Self::from(Bytes::from(value))
604,924✔
549
    }
604,924✔
550
}
551

552
/// Only for `Buffer<u8>` can we zero-copy from a `Bytes` since we can use a 1-byte alignment.
553
impl From<Bytes> for ByteBuffer {
554
    fn from(bytes: Bytes) -> Self {
605,698✔
555
        let length = bytes.len();
605,698✔
556
        Self {
605,698✔
557
            bytes,
605,698✔
558
            length,
605,698✔
559
            alignment: Alignment::of::<u8>(),
605,698✔
560
            _marker: Default::default(),
605,698✔
561
        }
605,698✔
562
    }
605,698✔
563
}
564

565
impl Buf for ByteBuffer {
566
    fn remaining(&self) -> usize {
2✔
567
        self.len()
2✔
568
    }
2✔
569

570
    fn chunk(&self) -> &[u8] {
2✔
571
        self.as_slice()
2✔
572
    }
2✔
573

574
    fn advance(&mut self, cnt: usize) {
1✔
575
        if !cnt.is_multiple_of(*self.alignment) {
1✔
576
            vortex_panic!(
×
577
                "Cannot advance buffer by {} items, resulting alignment is not {}",
×
578
                cnt,
579
                self.alignment
580
            );
581
        }
1✔
582
        self.bytes.advance(cnt);
1✔
583
        self.length -= cnt;
1✔
584
    }
1✔
585
}
586

587
/// Owned iterator over a [`Buffer`].
588
pub struct BufferIterator<T> {
589
    buffer: Buffer<T>,
590
    index: usize,
591
}
592

593
impl<T: Copy> Iterator for BufferIterator<T> {
594
    type Item = T;
595

596
    fn next(&mut self) -> Option<Self::Item> {
82,882,937✔
597
        (self.index < self.buffer.len()).then(move || {
82,882,937✔
598
            let value = self.buffer[self.index];
82,238,954✔
599
            self.index += 1;
82,238,954✔
600
            value
82,238,954✔
601
        })
82,238,954✔
602
    }
82,882,937✔
603

604
    fn size_hint(&self) -> (usize, Option<usize>) {
11,581✔
605
        let remaining = self.buffer.len() - self.index;
11,581✔
606
        (remaining, Some(remaining))
11,581✔
607
    }
11,581✔
608
}
609

610
impl<T: Copy> IntoIterator for Buffer<T> {
611
    type Item = T;
612
    type IntoIter = BufferIterator<T>;
613

614
    fn into_iter(self) -> Self::IntoIter {
643,192✔
615
        BufferIterator {
643,192✔
616
            buffer: self,
643,192✔
617
            index: 0,
643,192✔
618
        }
643,192✔
619
    }
643,192✔
620
}
621

622
impl<T> From<BufferMut<T>> for Buffer<T> {
623
    fn from(value: BufferMut<T>) -> Self {
67,952✔
624
        value.freeze()
67,952✔
625
    }
67,952✔
626
}
627

628
#[cfg(test)]
629
mod test {
630
    use bytes::Buf;
631

632
    use crate::{Alignment, ByteBuffer, buffer};
633

634
    #[test]
635
    fn align() {
1✔
636
        let buf = buffer![0u8, 1, 2];
1✔
637
        let aligned = buf.aligned(Alignment::new(32));
1✔
638
        assert_eq!(aligned.alignment(), Alignment::new(32));
1✔
639
        assert_eq!(aligned.as_slice(), &[0, 1, 2]);
1✔
640
    }
1✔
641

642
    #[test]
643
    fn slice() {
1✔
644
        let buf = buffer![0, 1, 2, 3, 4];
1✔
645
        assert_eq!(buf.slice(1..3).as_slice(), &[1, 2]);
1✔
646
        assert_eq!(buf.slice(1..=3).as_slice(), &[1, 2, 3]);
1✔
647
    }
1✔
648

649
    #[test]
650
    fn slice_unaligned() {
1✔
651
        let buf = buffer![0i32, 1, 2, 3, 4].into_byte_buffer();
1✔
652
        // With a regular slice, this would panic. See [`slice_bad_alignment`].
653
        buf.slice_unaligned(1..2);
1✔
654
    }
1✔
655

656
    #[test]
657
    #[should_panic]
658
    fn slice_bad_alignment() {
1✔
659
        let buf = buffer![0i32, 1, 2, 3, 4].into_byte_buffer();
1✔
660
        // We should only be able to slice this buffer on 4-byte (i32) boundaries.
661
        buf.slice(1..2);
1✔
662
    }
1✔
663

664
    #[test]
665
    fn bytes_buf() {
1✔
666
        let mut buf = ByteBuffer::copy_from("helloworld".as_bytes());
1✔
667
        assert_eq!(buf.remaining(), 10);
1✔
668
        assert_eq!(buf.chunk(), b"helloworld");
1✔
669

670
        Buf::advance(&mut buf, 5);
1✔
671
        assert_eq!(buf.remaining(), 5);
1✔
672
        assert_eq!(buf.as_slice(), b"world");
1✔
673
        assert_eq!(buf.chunk(), b"world");
1✔
674
    }
1✔
675
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc