Skip to content

Commit 20ac5cf

Browse files
committed
[Rust] impl FromStr for generated enum items
1 parent ae002c2 commit 20ac5cf

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
use examples_baseline::{
2+
boost_type::BoostType,
3+
};
4+
5+
#[test]
6+
fn test_boost_type_from_str() -> Result<(), ()> {
7+
assert_eq!("TURBO".parse::<BoostType>()?, BoostType::TURBO, "Parse \"TURBO\" as BoostType");
8+
assert_eq!("SUPERCHARGER".parse::<BoostType>()?, BoostType::SUPERCHARGER, "Parse \"SUPERCHARGER\" as BoostType");
9+
assert_eq!("NITROUS".parse::<BoostType>()?, BoostType::NITROUS, "Parse \"NITROUS\" as BoostType");
10+
assert_eq!("KERS".parse::<BoostType>()?, BoostType::KERS, "Parse \"KERS\" as BoostType");
11+
12+
assert_eq!("Turbo".parse::<BoostType>()?, BoostType::NullVal, "Parse \"Turbo\" as BoostType");
13+
assert_eq!("Supercharger".parse::<BoostType>()?, BoostType::NullVal, "Parse \"Supercharger\" as BoostType");
14+
assert_eq!("Nitrous".parse::<BoostType>()?, BoostType::NullVal, "Parse \"Nitrous\" as BoostType");
15+
assert_eq!("Kers".parse::<BoostType>()?, BoostType::NullVal, "Parse \"Kers\" as BoostType");
16+
17+
assert_eq!("AA".parse::<BoostType>()?, BoostType::NullVal, "Parse \"AA\" as BoostType");
18+
assert_eq!("".parse::<BoostType>().unwrap(), BoostType::NullVal, "Parse \"\" as BoostType");
19+
20+
Ok(())
21+
}

sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/rust/RustGenerator.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1283,6 +1283,22 @@ private static void generateEnum(
12831283
indent(writer, 2, "}\n");
12841284
indent(writer, 1, "}\n");
12851285
indent(writer, 0, "}\n");
1286+
1287+
// FromStr impl
1288+
indent(writer, 0, "impl core::str::FromStr for %s {\n", enumRustName);
1289+
indent(writer, 1, "type Err = ();\n\n");
1290+
indent(writer, 1, "#[inline]\n");
1291+
indent(writer, 1, "fn from_str(v: &str) -> core::result::Result<Self, Self::Err> {\n", primitiveType);
1292+
indent(writer, 2, "match v {\n");
1293+
for (final Token token : messageBody)
1294+
{
1295+
indent(writer, 3, "\"%1$s\" => core::result::Result::Ok(Self::%1$s), \n", token.name());
1296+
}
1297+
// default => NullVal
1298+
indent(writer, 3, "_ => core::result::Result::Ok(Self::NullVal),\n");
1299+
indent(writer, 2, "}\n");
1300+
indent(writer, 1, "}\n");
1301+
indent(writer, 0, "}\n");
12861302
}
12871303

12881304
private static void generateComposites(

0 commit comments

Comments
 (0)