]>
git.proxmox.com Git - rustc.git/blob - vendor/tendril/src/buf32.rs
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
7 //! Provides an unsafe owned buffer type, used in implementing `Tendril`.
9 use std
::{mem, ptr, slice, u32}
;
13 pub const MIN_CAP
: u32 = 16;
15 pub const MAX_LEN
: usize = u32::MAX
as usize;
17 /// A buffer points to a header of type `H`, which is followed by `MIN_CAP` or more
26 fn bytes_to_vec_capacity
<H
>(x
: u32) -> usize {
27 let header
= mem
::size_of
::<H
>();
28 debug_assert
!(header
> 0);
29 let x
= (x
as usize).checked_add(header
).expect(OFLOW
);
30 // Integer ceil https://stackoverflow.com/a/2745086/1162888
31 1 + ((x
- 1) / header
)
36 pub unsafe fn with_capacity(mut cap
: u32, h
: H
) -> Buf32
<H
> {
41 let mut vec
= Vec
::<H
>::with_capacity(bytes_to_vec_capacity
::<H
>(cap
));
42 let ptr
= vec
.as_mut_ptr();
54 pub unsafe fn destroy(self) {
55 mem
::drop(Vec
::from_raw_parts(
58 bytes_to_vec_capacity
::<H
>(self.cap
),
63 pub unsafe fn data_ptr(&self) -> *mut u8 {
64 (self.ptr
as *mut u8).offset(mem
::size_of
::<H
>() as isize)
68 pub unsafe fn data(&self) -> &[u8] {
69 slice
::from_raw_parts(self.data_ptr(), self.len
as usize)
73 pub unsafe fn data_mut(&mut self) -> &mut [u8] {
74 slice
::from_raw_parts_mut(self.data_ptr(), self.len
as usize)
77 /// Grow the capacity to at least `new_cap`.
79 /// This will panic if the capacity calculation overflows `u32`.
81 pub unsafe fn grow(&mut self, new_cap
: u32) {
82 if new_cap
<= self.cap
{
86 let new_cap
= new_cap
.checked_next_power_of_two().expect(OFLOW
);
87 let mut vec
= Vec
::from_raw_parts(self.ptr
, 0, bytes_to_vec_capacity
::<H
>(self.cap
));
88 vec
.reserve_exact(bytes_to_vec_capacity
::<H
>(new_cap
));
89 self.ptr
= vec
.as_mut_ptr();
103 let mut b
= Buf32
::with_capacity(0, 0u8);
104 assert_eq
!(b
"", b
.data());
107 ptr
::copy_nonoverlapping(b
"Hello".as_ptr(), b
.data_ptr(), 5);
109 assert_eq
!(b
"", b
.data());
111 assert_eq
!(b
"Hello", b
.data());
114 assert
!(b
.cap
>= 1337);
115 assert_eq
!(b
"Hello", b
.data());