Skip to content

Commit c688732

Browse files
committed
Remove AsRef<[u8]> bounds
1 parent df9683e commit c688732

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

packages/std/src/memory.rs

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,17 +83,35 @@ pub unsafe fn consume_region(ptr: *mut Region) -> Vec<u8> {
8383
/// And since `size` is one of the parameters, it is important to pass in the exact same capacity.
8484
///
8585
/// See: <https://doc.rust-lang.org/stable/alloc/alloc/trait.GlobalAlloc.html#safety-2>
86-
pub unsafe trait RegionSource: AsRef<[u8]> {
86+
pub unsafe trait RegionSource {
87+
fn ptr(&self) -> *const u8;
88+
fn len(&self) -> usize;
8789
fn capacity(&self) -> usize;
8890
}
8991

9092
unsafe impl RegionSource for &[u8] {
93+
fn ptr(&self) -> *const u8 {
94+
self.as_ptr()
95+
}
96+
97+
fn len(&self) -> usize {
98+
(*self).len()
99+
}
100+
91101
fn capacity(&self) -> usize {
92102
self.len()
93103
}
94104
}
95105

96106
unsafe impl RegionSource for Vec<u8> {
107+
fn ptr(&self) -> *const u8 {
108+
self.as_ptr()
109+
}
110+
111+
fn len(&self) -> usize {
112+
self.len()
113+
}
114+
97115
fn capacity(&self) -> usize {
98116
self.capacity()
99117
}
@@ -103,6 +121,14 @@ unsafe impl<T: ?Sized> RegionSource for &T
103121
where
104122
T: RegionSource,
105123
{
124+
fn ptr(&self) -> *const u8 {
125+
(**self).ptr()
126+
}
127+
128+
fn len(&self) -> usize {
129+
(**self).len()
130+
}
131+
106132
fn capacity(&self) -> usize {
107133
(**self).capacity()
108134
}
@@ -116,12 +142,12 @@ pub fn build_region<S>(data: S) -> Box<Region>
116142
where
117143
S: RegionSource,
118144
{
119-
let data_slice = data.as_ref();
120-
let data_ptr = data_slice.as_ptr() as usize;
145+
// Well, this technically violates pointer provenance rules.
146+
// But there isn't a stable API for it, so that's the best we can do, I guess.
121147
build_region_from_components(
122-
u32::try_from(data_ptr).expect("pointer doesn't fit in u32"),
148+
u32::try_from(data.ptr() as usize).expect("pointer doesn't fit in u32"),
123149
u32::try_from(data.capacity()).expect("capacity doesn't fit in u32"),
124-
u32::try_from(data_slice.len()).expect("length doesn't fit in u32"),
150+
u32::try_from(data.len()).expect("length doesn't fit in u32"),
125151
)
126152
}
127153

0 commit comments

Comments
 (0)