Skip to content

Commit

Permalink
Add a From<&str> impl to Name that adds the string to the map
Browse files Browse the repository at this point in the history
  • Loading branch information
widberg committed Oct 2, 2023
1 parent 0e127e5 commit e3cd7ef
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions bff/src/names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,25 @@ enum SerdeName {
}

impl Name {
// This is a const fn so it can be used in const contexts i.e. bff-derive generated NamedClass
// impl
pub const fn new(name: i32) -> Self {
Self(name)
}
}

impl From<&str> for Name {
fn from(value: &str) -> Self {
let name = crc32::asobo(value.as_bytes()).into();
NAMES
.lock()
.unwrap()
.entry(name)
.or_insert_with(|| value.to_string());
name
}
}

impl Serialize for Name {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match NAMES.lock().unwrap().get(self) {
Expand All @@ -49,14 +63,7 @@ impl<'de> Deserialize<'de> for Name {
let serde_name = SerdeName::deserialize(deserializer)?;
match serde_name {
SerdeName::Name(name) => Ok(Name(name)),
SerdeName::String(string) => {
NAMES
.lock()
.unwrap()
.entry(crc32::asobo(string.as_bytes()).into())
.or_insert_with(|| string.clone());
Ok(crc32::asobo(string.as_bytes()).into())
}
SerdeName::String(string) => Ok(Name::from(string.as_str())),
}
}
}
Expand Down

0 comments on commit e3cd7ef

Please sign in to comment.