@@ -239,7 +239,7 @@ macro_rules! impl_Display {
239
239
const MAX_DEC_N : usize = $unsigned:: MAX . ilog( 10 ) as usize + 1 ;
240
240
let mut buf = [ MaybeUninit :: <u8 >:: uninit( ) ; MAX_DEC_N ] ;
241
241
// Leading zero count & write index in buf.
242
- let mut offset = MAX_DEC_N ;
242
+ let mut offset = buf . len ( ) ;
243
243
// Consume decimals from working copy until none left.
244
244
let mut remain = self ;
245
245
@@ -248,34 +248,45 @@ macro_rules! impl_Display {
248
248
#[ allow( overflowing_literals) ]
249
249
#[ allow( unused_comparisons) ]
250
250
while offset >= 4 && remain > 999 {
251
+ // SAFETY: Offset from the initial buf.len() gets deducted
252
+ // with underflow checks exclusively.
253
+ unsafe { core:: hint:: assert_unchecked( offset <= buf. len( ) ) }
254
+ offset -= 4 ;
255
+
251
256
let quad = remain % 100_00 ;
252
257
remain /= 100_00 ;
253
258
let p1 = ( quad / 100 ) as usize * 2 ;
254
259
let p2 = ( quad % 100 ) as usize * 2 ;
255
- offset -= 4 ;
256
260
buf[ offset + 0 ] . write( DEC_DIGITS_LUT [ p1 + 0 ] ) ;
257
261
buf[ offset + 1 ] . write( DEC_DIGITS_LUT [ p1 + 1 ] ) ;
258
262
buf[ offset + 2 ] . write( DEC_DIGITS_LUT [ p2 + 0 ] ) ;
259
263
buf[ offset + 3 ] . write( DEC_DIGITS_LUT [ p2 + 1 ] ) ;
260
264
}
261
265
262
266
// Format per two digits from the lookup table.
263
- while offset >= 2 && remain > 9 {
267
+ if offset >= 2 && remain > 9 {
268
+ // SAFETY: Offset from the initial buf.len() gets deducted
269
+ // with underflow checks exclusively.
270
+ unsafe { core:: hint:: assert_unchecked( offset <= buf. len( ) ) }
271
+ offset -= 2 ;
272
+
264
273
let p = ( remain % 100 ) as usize * 2 ;
265
274
remain /= 100 ;
266
- offset -= 2 ;
267
275
buf[ offset + 0 ] . write( DEC_DIGITS_LUT [ p + 0 ] ) ;
268
276
buf[ offset + 1 ] . write( DEC_DIGITS_LUT [ p + 1 ] ) ;
269
277
}
270
278
271
279
// Format the last remaining digit, if any.
272
280
if offset != 0 && remain != 0 || offset == MAX_DEC_N {
281
+ // SAFETY: Offset from the initial buf.len() gets deducted
282
+ // with underflow checks exclusively.
283
+ unsafe { core:: hint:: assert_unchecked( offset <= buf. len( ) ) }
284
+ offset -= 1 ;
285
+
273
286
// Either the compiler sees that remain < 10, or it prevents
274
287
// a boundary check up next.
275
288
let p = ( remain % 10 ) as usize * 2 ;
276
289
// not used: remain = 0;
277
-
278
- offset -= 1 ;
279
290
buf[ offset] . write( DEC_DIGITS_LUT [ p + 1 ] ) ;
280
291
}
281
292
0 commit comments