@@ -67,6 +67,23 @@ pub struct ByteAddressableBuffer<T> {
67
67
pub data : T ,
68
68
}
69
69
70
+ fn bounds_check < T > ( data : & [ u32 ] , byte_index : u32 ) {
71
+ let sizeof = mem:: size_of :: < T > ( ) as u32 ;
72
+ if byte_index % 4 != 0 {
73
+ panic ! ( "`byte_index` should be a multiple of 4" ) ;
74
+ }
75
+ if byte_index + sizeof > data. len ( ) as u32 {
76
+ let last_byte = byte_index + sizeof;
77
+ panic ! (
78
+ "index out of bounds: the len is {} but loading {} bytes at `byte_index` {} reads until {} (exclusive)" ,
79
+ data. len( ) ,
80
+ sizeof,
81
+ byte_index,
82
+ last_byte,
83
+ ) ;
84
+ }
85
+ }
86
+
70
87
impl < ' a > ByteAddressableBuffer < & ' a [ u32 ] > {
71
88
/// Creates a `ByteAddressableBuffer` from the untyped blob of data.
72
89
#[ inline]
@@ -80,16 +97,7 @@ impl<'a> ByteAddressableBuffer<&'a [u32]> {
80
97
/// # Safety
81
98
/// See [`Self`].
82
99
pub unsafe fn load < T > ( & self , byte_index : u32 ) -> T {
83
- if byte_index % 4 != 0 {
84
- panic ! ( "`byte_index` should be a multiple of 4" ) ;
85
- }
86
- if byte_index + mem:: size_of :: < T > ( ) as u32 > self . data . len ( ) as u32 {
87
- panic ! (
88
- "index out of bounds: the len is {} but the `byte_index` is {}" ,
89
- self . data. len( ) ,
90
- byte_index
91
- ) ;
92
- }
100
+ bounds_check :: < T > ( self . data , byte_index) ;
93
101
buffer_load_intrinsic ( self . data , byte_index)
94
102
}
95
103
@@ -116,16 +124,7 @@ impl<'a> ByteAddressableBuffer<&'a mut [u32]> {
116
124
/// # Safety
117
125
/// See [`Self`].
118
126
pub unsafe fn load < T > ( & self , byte_index : u32 ) -> T {
119
- if byte_index % 4 != 0 {
120
- panic ! ( "`byte_index` should be a multiple of 4" ) ;
121
- }
122
- if byte_index + mem:: size_of :: < T > ( ) as u32 > self . data . len ( ) as u32 {
123
- panic ! (
124
- "index out of bounds: the len is {} but the `byte_index` is {}" ,
125
- self . data. len( ) ,
126
- byte_index
127
- ) ;
128
- }
127
+ bounds_check :: < T > ( self . data , byte_index) ;
129
128
buffer_load_intrinsic ( self . data , byte_index)
130
129
}
131
130
@@ -144,9 +143,7 @@ impl<'a> ByteAddressableBuffer<&'a mut [u32]> {
144
143
/// # Safety
145
144
/// See [`Self`].
146
145
pub unsafe fn store < T > ( & mut self , byte_index : u32 , value : T ) {
147
- if byte_index + mem:: size_of :: < T > ( ) as u32 > self . data . len ( ) as u32 {
148
- panic ! ( "Index out of range" ) ;
149
- }
146
+ bounds_check :: < T > ( self . data , byte_index) ;
150
147
buffer_store_intrinsic ( self . data , byte_index, value) ;
151
148
}
152
149
0 commit comments