2
2
3
3
use alloc:: alloc:: { Layout , LayoutError , alloc, dealloc} ;
4
4
use core:: error:: Error ;
5
- use core:: fmt;
6
5
use core:: ptr:: NonNull ;
6
+ use core:: { fmt, slice} ;
7
7
8
8
/// Helper class to maintain the lifetime of a memory region allocated with a non-standard alignment.
9
9
/// Facilitates RAII to properly deallocate when lifetime of the object ends.
@@ -51,6 +51,18 @@ impl AlignedBuffer {
51
51
self . ptr . as_ptr ( )
52
52
}
53
53
54
+ /// Get the underlying memory region as immutable slice.
55
+ #[ must_use]
56
+ pub const fn as_slice ( & mut self ) -> & [ u8 ] {
57
+ unsafe { slice:: from_raw_parts ( self . ptr ( ) , self . size ( ) ) }
58
+ }
59
+
60
+ /// Get the underlying memory region as mutable slice.
61
+ #[ must_use]
62
+ pub const fn as_slice_mut ( & mut self ) -> & mut [ u8 ] {
63
+ unsafe { slice:: from_raw_parts_mut ( self . ptr_mut ( ) , self . size ( ) ) }
64
+ }
65
+
54
66
/// Get the size of the aligned memory region managed by this instance.
55
67
#[ must_use]
56
68
pub const fn size ( & self ) -> usize {
@@ -67,6 +79,14 @@ impl AlignedBuffer {
67
79
}
68
80
}
69
81
82
+ /// Fill the aligned memory region with data from the given iterator.
83
+ /// If the given iterator is shorter than the buffer, the remaining area will be left untouched.
84
+ pub fn copy_from_iter ( & mut self , src : impl Iterator < Item = u8 > ) {
85
+ src. take ( self . size ( ) )
86
+ . zip ( self . as_slice_mut ( ) . iter_mut ( ) )
87
+ . for_each ( |( src, dst) | * dst = src) ;
88
+ }
89
+
70
90
/// Check the buffer's alignment against the `required_alignment`.
71
91
pub fn check_alignment ( & self , required_alignment : usize ) -> Result < ( ) , AlignmentError > {
72
92
//TODO: use bfr.addr() when it's available
0 commit comments