ps_buffer/methods/from_raw_parts.rs
1use crate::Buffer;
2
3impl Buffer {
4 /// Creates a `Buffer` directly from a pointer, a length, and a capacity.
5 ///
6 /// # Safety
7 ///
8 /// This is highly unsafe due to the number of invariants that aren't
9 /// checked:
10 ///
11 /// * `ptr` must have been allocated using the [`ps_alloc::alloc`] function.
12 /// * `length` needs to be less than or equal to `capacity`.
13 /// * The first `length` values must be properly initialized.
14 /// * `capacity` needs to be the capacity that the pointer was allocated with.
15 /// * The allocated size in bytes must be no larger than `isize::MAX`.
16 ///
17 /// These requirements are always upheld by any `ptr` that has been allocated
18 /// by `Buffer`. Other allocation sources are allowed if the invariants are
19 /// upheld.
20 ///
21 /// Violating these may cause problems like corrupting the allocator's
22 /// internal data structures. `Buffer`'s deallocator will also read bytes
23 /// right before the pointer, which may cause a segmentation fault.
24 ///
25 /// It's also not safe to build one from a non-aligned pointer, because
26 /// the allocator cares about the alignment, and `Buffer` uses 16-byte
27 /// alignment. `Buffer` always deallocates with alignment 16.
28 ///
29 /// If you need to create a `Buffer` from memory which does not uphold there invariants,
30 /// use [`std::slice::from_raw_parts`] and [`Buffer::from_slice`].
31 ///
32 /// The ownership of `ptr` is effectively transferred to the
33 /// `Buffer` which may then deallocate, reallocate or change the
34 /// contents of memory pointed to by the pointer at will. Ensure
35 /// that nothing else uses the pointer after calling this
36 /// function.
37 ///
38 /// *This documenting comment is based on [`Vec::from_raw_parts`].*
39 #[inline]
40 pub const unsafe fn from_raw_parts(ptr: *mut u8, length: usize, capacity: usize) -> Self {
41 Self {
42 ptr,
43 capacity,
44 length,
45 }
46 }
47}