@@ -3,6 +3,7 @@ use serde::ser::{Serialize, SerializeMap, SerializeSeq, SerializeStruct, Seriali
33
44use bson:: { Array , Bson , Document , UtcDateTime } ;
55use oid:: ObjectId ;
6+ use try_from:: TryFrom ;
67
78use super :: { to_bson, EncoderError , EncoderResult } ;
89
@@ -88,8 +89,12 @@ impl Serializer for Encoder {
8889 }
8990
9091 #[ inline]
91- fn serialize_u8 ( self , _value : u8 ) -> EncoderResult < Bson > {
92- Err ( EncoderError :: UnsupportedUnsignedType )
92+ fn serialize_u8 ( self , value : u8 ) -> EncoderResult < Bson > {
93+ if cfg ! ( feature = "u2i" ) {
94+ Ok ( Bson :: I32 ( value as i32 ) )
95+ } else {
96+ Err ( EncoderError :: UnsupportedUnsignedType )
97+ }
9398 }
9499
95100 #[ inline]
@@ -98,8 +103,12 @@ impl Serializer for Encoder {
98103 }
99104
100105 #[ inline]
101- fn serialize_u16 ( self , _value : u16 ) -> EncoderResult < Bson > {
102- Err ( EncoderError :: UnsupportedUnsignedType )
106+ fn serialize_u16 ( self , value : u16 ) -> EncoderResult < Bson > {
107+ if cfg ! ( feature = "u2i" ) {
108+ Ok ( Bson :: I32 ( value as i32 ) )
109+ } else {
110+ Err ( EncoderError :: UnsupportedUnsignedType )
111+ }
103112 }
104113
105114 #[ inline]
@@ -108,8 +117,12 @@ impl Serializer for Encoder {
108117 }
109118
110119 #[ inline]
111- fn serialize_u32 ( self , _value : u32 ) -> EncoderResult < Bson > {
112- Err ( EncoderError :: UnsupportedUnsignedType )
120+ fn serialize_u32 ( self , value : u32 ) -> EncoderResult < Bson > {
121+ if cfg ! ( feature = "u2i" ) {
122+ Ok ( Bson :: I64 ( value as i64 ) )
123+ } else {
124+ Err ( EncoderError :: UnsupportedUnsignedType )
125+ }
113126 }
114127
115128 #[ inline]
@@ -118,8 +131,15 @@ impl Serializer for Encoder {
118131 }
119132
120133 #[ inline]
121- fn serialize_u64 ( self , _value : u64 ) -> EncoderResult < Bson > {
122- Err ( EncoderError :: UnsupportedUnsignedType )
134+ fn serialize_u64 ( self , value : u64 ) -> EncoderResult < Bson > {
135+ if cfg ! ( feature = "u2i" ) {
136+ match i64:: try_from ( value) {
137+ Ok ( ivalue) => Ok ( Bson :: I64 ( ivalue) ) ,
138+ Err ( _) => Err ( EncoderError :: UnsignedTypesValueExceedsRange ( value) ) ,
139+ }
140+ } else {
141+ Err ( EncoderError :: UnsupportedUnsignedType )
142+ }
123143 }
124144
125145 #[ inline]
0 commit comments