@@ -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" ) ]
@@ -242,8 +247,15 @@ impl Encoder {
242247 !self . is_last
243248 }
244249 Ordering :: Greater => {
245- dst. buffer ( msg. take ( remaining as usize ) ) ;
246- !self . is_last
250+ match usize:: try_from ( remaining) {
251+ Ok ( limit) => {
252+ dst. buffer ( msg. take ( limit) ) ;
253+ !self . is_last
254+ }
255+ // if len > remaining (this arm), then remaining must be < usize::MAX transitively.
256+ // usize::MAX > len > remaining -> remaining cannot fail to cast.
257+ _ => unreachable ! ( "it is impossible that remaining > usize::MAX" )
258+ }
247259 }
248260 Ordering :: Less => {
249261 dst. buffer ( msg) ;
@@ -328,11 +340,7 @@ where
328340 }
329341}
330342
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 ;
343+ const USIZE_BYTES : usize = std:: mem:: size_of :: < usize > ( ) ;
336344
337345// each byte will become 2 hex
338346const CHUNK_SIZE_MAX_BYTES : usize = USIZE_BYTES * 2 ;
@@ -369,6 +377,7 @@ impl Buf for ChunkSize {
369377 }
370378
371379 #[ inline]
380+ #[ allow( clippy:: cast_possible_truncation) ]
372381 fn advance ( & mut self , cnt : usize ) {
373382 assert ! ( cnt <= self . remaining( ) ) ;
374383 self . pos += cnt as u8 ; // just asserted cnt fits in u8
@@ -385,12 +394,14 @@ impl fmt::Debug for ChunkSize {
385394}
386395
387396impl fmt:: Write for ChunkSize {
397+ #[ allow( clippy:: cast_possible_truncation, reason="bytes is structurally always less than u8::MAX" ) ]
388398 fn write_str ( & mut self , num : & str ) -> fmt:: Result {
389399 use std:: io:: Write ;
390400 ( & mut self . bytes [ self . len . into ( ) ..] )
391401 . write_all ( num. as_bytes ( ) )
392402 . expect ( "&mut [u8].write() cannot error" ) ;
393- self . len += num. len ( ) as u8 ; // safe because bytes is never bigger than 256
403+ debug_assert ! ( u8 :: try_from( num. len( ) ) . is_ok( ) ) ;
404+ self . len += num. len ( ) as u8 ; // safe because bytes is never bigger than 255
394405 Ok ( ( ) )
395406 }
396407}
0 commit comments