Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom Duration and Timestamp types for conversion with serde #89

Open
wants to merge 11 commits into
base: master
Choose a base branch
from

Conversation

fore5fire
Copy link
Contributor

Currently chrono::Duration doesn't implement Seralize and chrono::DateTime serializes to an ISO 8601 string. This change is inspired by the toml crate's approach to preserving date formats across functions available in the Serialize trait to ensure that durations and timestamp are converted into the appropriate CEL types.

Using the newly exposed Duration and Timestamp types is only necessary for types using serde to convert to CEL, but maybe it could be confusing to keep track of where to use the chrono types vs the cel_interpreter types? But it seems like an unnecessary breaking change to use the new types in Value::Duration and Value::Timestamp 🤷🏼

example/src/serde.rs Outdated Show resolved Hide resolved
@fore5fire
Copy link
Contributor Author

I did some research and found the clever idea to use serde's newtype_struct name field as the indicator to do special type handling. Since serde's official recommendation is to silently unwrap newtypes, it's a great way to signal to a custom Serializer but remain compatible with most other implementations

@fore5fire
Copy link
Contributor Author

Updated for the new chrono feature

Comment on lines +802 to +814
fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
assert!(matches!(self, Self::Duration { .. }));
assert_eq!(name, "Duration");
assert_eq!(len, 2);
Ok(SerializeTimestamp::default())
}

fn serialize_str(self, v: &str) -> Result<Value> {
assert!(matches!(self, Self::Timestamp));
Ok(v.parse::<chrono::DateTime<FixedOffset>>()
.map_err(|e| SerializationError::SerdeError(e.to_string()))?
.into())
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we using asserts here instead of returning an error result? This would be fine for application code, but for a library, I don't want to prevent users from being able to deal with bad inputs. If these are considered impossible conditions, please add a SAFETY: comment indicating the invariants that will be upheld and how a reader can prove that these panics will never occur.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants