@@ -142,13 +142,18 @@ impl Encoder {
142142 }
143143 Kind :: Length ( remaining) => {
144144 trace ! ( "sized write, len = {}" , len) ;
145- if len as u64 > * remaining {
146- let limit = * remaining as usize ;
147- * remaining = 0 ;
148- BufKind :: Limited ( msg. take ( limit) )
149- } else {
150- * remaining -= len as u64 ;
151- BufKind :: Exact ( msg)
145+ match usize:: try_from ( * remaining) {
146+ // Holding more than is owed, so write only what is left.
147+ Ok ( limit) if limit < len => {
148+ * remaining = 0 ;
149+ BufKind :: Limited ( msg. take ( limit) )
150+ }
151+ // Ok(_) => Owed at least what we hold, write all of it.
152+ // Err(_) => Owed more than `usize` can represent, write all of it.
153+ Ok ( _) | Err ( _) => {
154+ * remaining -= len as u64 ;
155+ BufKind :: Exact ( msg)
156+ }
152157 }
153158 }
154159 #[ cfg( feature = "server" ) ]
@@ -241,6 +246,7 @@ impl Encoder {
241246 dst. buffer ( msg) ;
242247 !self . is_last
243248 }
249+ #[ allow( clippy:: cast_possible_truncation, reason="usize::MAX > len > remaining, cast truncation is impossible" ) ]
244250 Ordering :: Greater => {
245251 dst. buffer ( msg. take ( remaining as usize ) ) ;
246252 !self . is_last
@@ -328,11 +334,7 @@ where
328334 }
329335}
330336
331- #[ cfg( target_pointer_width = "32" ) ]
332- const USIZE_BYTES : usize = 4 ;
333-
334- #[ cfg( target_pointer_width = "64" ) ]
335- const USIZE_BYTES : usize = 8 ;
337+ const USIZE_BYTES : usize = std:: mem:: size_of :: < usize > ( ) ;
336338
337339// each byte will become 2 hex
338340const CHUNK_SIZE_MAX_BYTES : usize = USIZE_BYTES * 2 ;
@@ -369,6 +371,7 @@ impl Buf for ChunkSize {
369371 }
370372
371373 #[ inline]
374+ #[ allow( clippy:: cast_possible_truncation) ]
372375 fn advance ( & mut self , cnt : usize ) {
373376 assert ! ( cnt <= self . remaining( ) ) ;
374377 self . pos += cnt as u8 ; // just asserted cnt fits in u8
@@ -385,12 +388,14 @@ impl fmt::Debug for ChunkSize {
385388}
386389
387390impl fmt:: Write for ChunkSize {
391+ #[ allow( clippy:: cast_possible_truncation, reason="bytes is structurally always less than u8::MAX" ) ]
388392 fn write_str ( & mut self , num : & str ) -> fmt:: Result {
389393 use std:: io:: Write ;
390394 ( & mut self . bytes [ self . len . into ( ) ..] )
391395 . write_all ( num. as_bytes ( ) )
392396 . expect ( "&mut [u8].write() cannot error" ) ;
393- self . len += num. len ( ) as u8 ; // safe because bytes is never bigger than 256
397+ debug_assert ! ( u8 :: try_from( num. len( ) ) . is_ok( ) ) ;
398+ self . len += num. len ( ) as u8 ; // safe because bytes is never bigger than 255
394399 Ok ( ( ) )
395400 }
396401}
0 commit comments