@@ -31,9 +31,16 @@ impl PgHasArrayType for BitVec {
3131
3232impl Encode < ' _ , Postgres > for BitVec {
3333 fn encode_by_ref ( & self , buf : & mut PgArgumentBuffer ) -> IsNull {
34- buf. extend ( & ( self . len ( ) as i32 ) . to_be_bytes ( ) ) ;
35- buf. extend ( self . to_bytes ( ) ) ;
36-
34+ if let Ok ( len) = i32:: try_from ( self . len ( ) ) {
35+ buf. extend ( & len. to_be_bytes ( ) ) ;
36+ buf. extend_from_slice ( & self . to_bytes ( ) ) ;
37+ } else {
38+ debug_assert ! ( false , "BitVec length is too large to be encoded as i32." ) ;
39+ let len = i32:: MAX ;
40+ buf. extend ( & len. to_be_bytes ( ) ) ;
41+ let truncated = & self . to_bytes ( ) [ 0 ..usize:: try_from ( i32:: MAX ) . unwrap ( ) ] ;
42+ buf. extend_from_slice ( truncated) ;
43+ } ;
3744 IsNull :: No
3845 }
3946
@@ -47,17 +54,18 @@ impl Decode<'_, Postgres> for BitVec {
4754 match value. format ( ) {
4855 PgValueFormat :: Binary => {
4956 let mut bytes = value. as_bytes ( ) ?;
50- let len = bytes. get_i32 ( ) ;
51-
52- if len < 0 {
53- Err ( io:: Error :: new (
57+ let len = if let Ok ( len ) = usize :: try_from ( bytes. get_i32 ( ) ) {
58+ len
59+ } else {
60+ return Err ( io:: Error :: new (
5461 io:: ErrorKind :: InvalidData ,
5562 "Negative VARBIT length." ,
56- ) ) ?
57- }
63+ )
64+ . into ( ) ) ;
65+ } ;
5866
5967 // The smallest amount of data we can read is one byte
60- let bytes_len = ( len as usize + 7 ) / 8 ;
68+ let bytes_len = ( len + 7 ) / 8 ;
6169
6270 if bytes. remaining ( ) != bytes_len {
6371 Err ( io:: Error :: new (
@@ -66,12 +74,12 @@ impl Decode<'_, Postgres> for BitVec {
6674 ) ) ?;
6775 }
6876
69- let mut bitvec = BitVec :: from_bytes ( & bytes) ;
77+ let mut bitvec = BitVec :: from_bytes ( bytes) ;
7078
7179 // Chop off zeroes from the back. We get bits in bytes, so if
7280 // our bitvec is not in full bytes, extra zeroes are added to
7381 // the end.
74- while bitvec. len ( ) > len as usize {
82+ while bitvec. len ( ) > len {
7583 bitvec. pop ( ) ;
7684 }
7785
0 commit comments