diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c2a72c..220a81e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,11 @@ JMdict was updated to 2021-09-17. This requires the following changes in enum va - added `SenseTopic::Psychiatry` - added `SenseTopic::Railway` +Further changes: + +- The `all_variants()` method was added to `trait Enum`. +- The `from_constant_name()` method was added to `trait Enum`. + # v1.0.0 (2021-04-18) Initial stable release. No changes from v0.99.1. diff --git a/jmdict-enums/build.rs b/jmdict-enums/build.rs index 2e627b8..b38e422 100644 --- a/jmdict-enums/build.rs +++ b/jmdict-enums/build.rs @@ -439,6 +439,28 @@ fn process(e: Enum) -> String { lines.push(" }".into()); lines.push(" }\n".into()); + //fn from_constant_name(&str) -> Self + lines.push(" fn from_constant_name(text: &str) -> Option {".into()); + lines.push(" match text {".into()); + for v in e.variants.iter().filter(|v| v.enabled) { + lines.push(format!( + " \"{}\" => Some({}::{}),", + v.name, e.name, v.name + )); + } + lines.push(" _ => None,".into()); + lines.push(" }".into()); + lines.push(" }\n".into()); + + //fn all_variants() -> &'static [Self] + lines.push(" fn all_variants() -> &'static [Self] {".into()); + lines.push(" &[".into()); + for v in e.variants.iter().filter(|v| v.enabled) { + lines.push(format!(" {}::{},", e.name, v.name)); + } + lines.push(" ]".into()); + lines.push(" }\n".into()); + //end impl Enum lines.push("}\n".into()); diff --git a/jmdict-enums/src/lib.rs b/jmdict-enums/src/lib.rs index 82f634b..c532820 100644 --- a/jmdict-enums/src/lib.rs +++ b/jmdict-enums/src/lib.rs @@ -43,6 +43,10 @@ pub trait EnumPayload { ///Common methods provided by all enums in this crate. pub trait Enum: Sized { + ///Returns a list of all variant values in this enum. No particular order is guaranteed or + ///implied. + fn all_variants() -> &'static [Self]; + ///Returns the string that marks this enum variant in the JMdict. For values that JMdict ///represents as XML entities, only the entity name is returned, e.g. `adj-n` instead of ///`&adj-n;`. @@ -55,6 +59,11 @@ pub trait Enum: Sized { ///Returns the variant name. This is used to generate Rust code for this enum. The `impl ///Display` for enums uses this same representation. fn constant_name(&self) -> &'static str; + + ///Returns the variant that is identified the given name in Rust code, or `None` if there is no + ///such variant. This is the reverse of `self.constant_name()`, i.e. + ///`Self::from_constant_name(self.constant_name()) == Some(self)`. + fn from_constant_name(name: &str) -> Option; } ///PriorityInCorpus appears in struct [Priority]. It describes how often a dictionary entry