@@ -20,6 +20,7 @@ pub fn generate_enum<W: Write>(
2020 descriptor : & EnumDescriptor ,
2121 writer : & mut W ,
2222 use_integers_for_enums : bool ,
23+ ignore_unknown_enum_variants : bool ,
2324) -> Result < ( ) > {
2425 let rust_type = resolver. rust_type ( path) ;
2526
@@ -74,7 +75,13 @@ pub fn generate_enum<W: Write>(
7475 // Generate Deserialize
7576 write_deserialize_start ( 0 , & rust_type, writer) ?;
7677 write_fields_array ( writer, 2 , variants. iter ( ) . map ( |( name, _, _) | name. as_str ( ) ) ) ?;
77- write_visitor ( writer, 2 , & rust_type, & variants) ?;
78+ write_visitor (
79+ writer,
80+ 2 ,
81+ & rust_type,
82+ & variants,
83+ ignore_unknown_enum_variants,
84+ ) ?;
7885
7986 // Use deserialize_any to allow users to provide integers or strings
8087 writeln ! (
@@ -92,7 +99,23 @@ fn write_visitor<W: Write>(
9299 indent : usize ,
93100 rust_type : & str ,
94101 variants : & [ ( String , i32 , String ) ] ,
102+ ignore_unknown_enum_variants : bool ,
95103) -> Result < ( ) > {
104+ // These are what needs to be done for an unknown i32 or string value.
105+ let ( or_unknown_i32, unknown_string_return) = if ignore_unknown_enum_variants {
106+ // If ignore_unknown_enum_variants is set, we will return the default for the enum.
107+ (
108+ format ! ( ".or_else(|| Some({rust_type}::default()))" ) ,
109+ format ! ( "Ok({rust_type}::default())" ) ,
110+ )
111+ } else {
112+ // If ignore_unknown_enum_variants is not set, we will return an Err.
113+ (
114+ "" . into ( ) ,
115+ "Err(serde::de::Error::unknown_variant(value, FIELDS))" . into ( ) ,
116+ )
117+ } ;
118+
96119 // Protobuf supports deserialization of enumerations both from string and integer values
97120 writeln ! (
98121 writer,
@@ -111,7 +134,7 @@ fn write_visitor<W: Write>(
111134{indent} {{
112135{indent} i32::try_from(v)
113136{indent} .ok()
114- {indent} .and_then(|x| x.try_into().ok())
137+ {indent} .and_then(|x| x.try_into().ok(){or_unknown_i32} )
115138{indent} .ok_or_else(|| {{
116139{indent} serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self)
117140{indent} }})
@@ -123,7 +146,7 @@ fn write_visitor<W: Write>(
123146{indent} {{
124147{indent} i32::try_from(v)
125148{indent} .ok()
126- {indent} .and_then(|x| x.try_into().ok())
149+ {indent} .and_then(|x| x.try_into().ok(){or_unknown_i32} )
127150{indent} .ok_or_else(|| {{
128151{indent} serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self)
129152{indent} }})
@@ -151,7 +174,7 @@ fn write_visitor<W: Write>(
151174
152175 writeln ! (
153176 writer,
154- "{indent}_ => Err(serde::de::Error::unknown_variant(value, FIELDS)) ," ,
177+ "{indent}_ => {unknown_string_return} ," ,
155178 indent = Indent ( indent + 3 )
156179 ) ?;
157180 writeln ! ( writer, "{}}}" , Indent ( indent + 2 ) ) ?;
0 commit comments