@@ -49,25 +49,25 @@ impl_write_unsigned_leb128!(write_usize_leb128, usize);
49
49
50
50
macro_rules! impl_read_unsigned_leb128 {
51
51
( $fn_name: ident, $int_ty: ty) => {
52
+ // This returns `Option` to avoid needing to emit the panic paths here.
53
+ // Letting the caller do it instead helps keep our code size small.
52
54
#[ inline]
53
- pub fn $fn_name( slice: & [ u8 ] , position : & mut usize ) -> $int_ty {
55
+ pub fn $fn_name( slice: & mut std :: slice :: Iter < ' _ , u8 > ) -> Option < $int_ty> {
54
56
// The first iteration of this loop is unpeeled. This is a
55
57
// performance win because this code is hot and integer values less
56
58
// than 128 are very common, typically occurring 50-80% or more of
57
59
// the time, even for u64 and u128.
58
- let byte = slice[ * position] ;
59
- * position += 1 ;
60
+ let byte = * ( slice. next( ) ?) ;
60
61
if ( byte & 0x80 ) == 0 {
61
- return byte as $int_ty;
62
+ return Some ( byte as $int_ty) ;
62
63
}
63
64
let mut result = ( byte & 0x7F ) as $int_ty;
64
65
let mut shift = 7 ;
65
66
loop {
66
- let byte = slice[ * position] ;
67
- * position += 1 ;
67
+ let byte = * ( slice. next( ) ?) ;
68
68
if ( byte & 0x80 ) == 0 {
69
69
result |= ( byte as $int_ty) << shift;
70
- return result;
70
+ return Some ( result) ;
71
71
} else {
72
72
result |= ( ( byte & 0x7F ) as $int_ty) << shift;
73
73
}
@@ -126,15 +126,16 @@ impl_write_signed_leb128!(write_isize_leb128, isize);
126
126
127
127
macro_rules! impl_read_signed_leb128 {
128
128
( $fn_name: ident, $int_ty: ty) => {
129
+ // This returns `Option` to avoid needing to emit the panic paths here.
130
+ // Letting the caller do it instead helps keep our code size small.
129
131
#[ inline]
130
- pub fn $fn_name( slice: & [ u8 ] , position : & mut usize ) -> $int_ty {
132
+ pub fn $fn_name( slice: & mut std :: slice :: Iter < ' _ , u8 > ) -> Option < $int_ty> {
131
133
let mut result = 0 ;
132
134
let mut shift = 0 ;
133
135
let mut byte;
134
136
135
137
loop {
136
- byte = slice[ * position] ;
137
- * position += 1 ;
138
+ byte = * ( slice. next( ) ?) ;
138
139
result |= <$int_ty>:: from( byte & 0x7F ) << shift;
139
140
shift += 7 ;
140
141
@@ -148,7 +149,7 @@ macro_rules! impl_read_signed_leb128 {
148
149
result |= ( !0 << shift) ;
149
150
}
150
151
151
- result
152
+ Some ( result)
152
153
}
153
154
} ;
154
155
}
0 commit comments