Skip to content

Commit 98fe82b

Browse files
committed
[Rust] impl Into for generated enum items
1 parent cc3c466 commit 98fe82b

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

rust/tests/baseline_enum_into.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
use examples_baseline::{
2+
boost_type::BoostType,
3+
};
4+
5+
#[test]
6+
fn test_boost_type_from_str() -> Result<(), ()> {
7+
assert_eq!(<BoostType as Into<u8>>::into(BoostType::TURBO), 84_u8, "BoostType::TURBO into value");
8+
assert_eq!(<BoostType as Into<u8>>::into(BoostType::SUPERCHARGER), 83_u8, "BoostType::SUPERCHARGER into value");
9+
assert_eq!(<BoostType as Into<u8>>::into(BoostType::NITROUS), 78_u8, "BoostType::NITROUS into value");
10+
assert_eq!(<BoostType as Into<u8>>::into(BoostType::KERS), 75_u8, "BoostType::KERS into value");
11+
assert_eq!(<BoostType as Into<u8>>::into(BoostType::NullVal), 0_u8, "BoostType::NullVal into value");
12+
13+
Ok(())
14+
}

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1284,6 +1284,27 @@ private static void generateEnum(
12841284
indent(writer, 1, "}\n");
12851285
indent(writer, 0, "}\n");
12861286

1287+
// Into impl
1288+
indent(writer, 0, "impl Into<%s> for %s {\n", primitiveType, enumRustName);
1289+
indent(writer, 1, "#[inline]\n");
1290+
indent(writer, 1, "fn into(self) -> %s {\n", primitiveType);
1291+
indent(writer, 2, "match self {\n");
1292+
for (final Token token : messageBody)
1293+
{
1294+
final Encoding encoding = token.encoding();
1295+
final String literal = generateRustLiteral(encoding.primitiveType(), encoding.constValue().toString());
1296+
indent(writer, 3, "Self::%s => %s, \n", token.name(), literal);
1297+
}
1298+
{
1299+
final Encoding encoding = messageBody.get(0).encoding();
1300+
final CharSequence nullVal = generateRustLiteral(encoding.primitiveType(),
1301+
encoding.applicableNullValue().toString());
1302+
indent(writer, 3, "Self::NullVal => %s,\n", nullVal);
1303+
}
1304+
indent(writer, 2, "}\n");
1305+
indent(writer, 1, "}\n");
1306+
indent(writer, 0, "}\n");
1307+
12871308
// FromStr impl
12881309
indent(writer, 0, "impl core::str::FromStr for %s {\n", enumRustName);
12891310
indent(writer, 1, "type Err = ();\n\n");

0 commit comments

Comments
 (0)