Skip to content

Commit

Permalink
change error message in try_unpack when entry not found
Browse files Browse the repository at this point in the history
  • Loading branch information
wtzhang23 committed Sep 12, 2024
1 parent 3820e77 commit 556822f
Show file tree
Hide file tree
Showing 10 changed files with 28 additions and 36 deletions.
5 changes: 3 additions & 2 deletions example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ include!(concat!(env!("OUT_DIR"), "/my.messages.rs"));
include!(concat!(env!("OUT_DIR"), "/my.requests.rs"));

fn main() -> Result<(), AnyError> {

let content: Content = Content { body: Some(content::Body::SomeBool(true)) };
let content: Content = Content {
body: Some(content::Body::SomeBool(true)),
};

let foo_msg: Foo = Foo {
data: "Hello World".to_string(),
Expand Down
1 change: 0 additions & 1 deletion wkt-types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,3 @@ mod pbmask;
pub use crate::pbmask::*;

pub use prost_wkt::MessageSerde;

2 changes: 1 addition & 1 deletion wkt-types/src/pbany.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl Any {
/// let back: Box<dyn MessageSerde> = any.try_unpack()?;
/// ```
pub fn try_unpack(self) -> Result<Box<dyn prost_wkt::MessageSerde>, AnyError> {
find_entry(&self.type_url).ok_or_else(|| format!("Failed to deserialize {}. Make sure prost-wkt-build is executed.", self.type_url))
find_entry(&self.type_url).ok_or_else(|| format!("Failed to deserialize {}. Make sure the MessageSerde trait is derived through its proc macro.", self.type_url))
.and_then(|entry| {
(entry.decoder)(&self.value).map_err(|error| {
format!(
Expand Down
3 changes: 2 additions & 1 deletion wkt-types/src/pbempty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ mod tests {

#[test]
fn deserialize_empty() {
let msg: Empty = serde_json::from_str("{}").expect("Could not deserialize `{}` to an Empty struct!");
let msg: Empty =
serde_json::from_str("{}").expect("Could not deserialize `{}` to an Empty struct!");
assert_eq!(msg, EMPTY);
}

Expand Down
26 changes: 9 additions & 17 deletions wkt-types/src/pbstruct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ impl Serialize for Struct {
{
let mut map = serializer.serialize_map(Some(self.fields.len()))?;
for (k, v) in &self.fields {
map.serialize_entry( k, v)?;
map.serialize_entry(k, v)?;
}
map.end()
}
Expand All @@ -217,12 +217,8 @@ impl Serialize for Value {
Some(value::Kind::StringValue(string)) => serializer.serialize_str(string),
Some(value::Kind::BoolValue(boolean)) => serializer.serialize_bool(*boolean),
Some(value::Kind::NullValue(_)) => serializer.serialize_none(),
Some(value::Kind::ListValue(list)) => {
list.serialize(serializer)
}
Some(value::Kind::StructValue(object)) => {
object.serialize(serializer)
}
Some(value::Kind::ListValue(list)) => list.serialize(serializer),
Some(value::Kind::StructValue(object)) => object.serialize(serializer),
_ => serializer.serialize_none(),
}
}
Expand All @@ -244,9 +240,7 @@ impl<'de> Visitor<'de> for ListValueVisitor {
while let Some(el) = seq.next_element()? {
values.push(el)
}
Ok(ListValue {
values
})
Ok(ListValue { values })
}
}

Expand All @@ -271,21 +265,19 @@ impl<'de> Visitor<'de> for StructVisitor {
where
A: MapAccess<'de>,
{
let mut fields: std::collections::HashMap<String, Value> =
std::collections::HashMap::new();
let mut fields: std::collections::HashMap<String, Value> = std::collections::HashMap::new();
while let Some((key, value)) = map.next_entry::<String, Value>()? {
fields.insert(key, value);
}
Ok(Struct {
fields
})
Ok(Struct { fields })
}
}

impl<'de> Deserialize<'de> for Struct {
fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
where
D: Deserializer<'de> {
where
D: Deserializer<'de>,
{
deserializer.deserialize_map(StructVisitor)
}
}
Expand Down
1 change: 0 additions & 1 deletion wkt-types/src/pbtime/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
////////////////////////////////////////////////////////////////////////////////
/// FROM prost-types/src/datetime.rs
////////////////////////////////////////////////////////////////////////////////

use core::fmt;

use crate::Duration;
Expand Down
8 changes: 3 additions & 5 deletions wkt-types/src/pbtime/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,10 @@ impl From<Duration> for chrono::Duration {
// A call to `normalize` should capture all out-of-bound sitations hopefully
// ensuring a panic never happens! Ideally this implementation should be
// deprecated in favour of TryFrom but unfortunately having `TryFrom` along with
// `From` causes a conflict.
// `From` causes a conflict.
value.normalize();
let s = chrono::TimeDelta::try_seconds(value.seconds).expect("invalid or out-of-range seconds");
let s =
chrono::TimeDelta::try_seconds(value.seconds).expect("invalid or out-of-range seconds");
let ns = chrono::Duration::nanoseconds(value.nanos as i64);
s + ns
}
Expand Down Expand Up @@ -276,6 +277,3 @@ impl<'de> Deserialize<'de> for Duration {
deserializer.deserialize_str(DurationVisitor)
}
}



12 changes: 8 additions & 4 deletions wkt-types/src/pbtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ pub use timestamp::TimestampError;

use core::convert::TryFrom;
use core::str::FromStr;
use core::*;
use core::time;
use core::*;
use std::convert::TryInto;

use chrono::prelude::*;
Expand All @@ -26,7 +26,6 @@ include!(concat!(env!("OUT_DIR"), "/pbtime/google.protobuf.rs"));
const NANOS_PER_SECOND: i32 = 1_000_000_000;
const NANOS_MAX: i32 = NANOS_PER_SECOND - 1;


#[cfg(test)]
mod tests {

Expand Down Expand Up @@ -89,12 +88,17 @@ mod tests {
};
let chrono_duration: chrono::Duration = duration.into();
assert_eq!(chrono_duration.num_seconds(), 10);
assert_eq!((chrono_duration - chrono::Duration::try_seconds(10).expect("seconds")).num_nanoseconds(), Some(100));
assert_eq!(
(chrono_duration - chrono::Duration::try_seconds(10).expect("seconds"))
.num_nanoseconds(),
Some(100)
);
}

#[test]
fn test_duration_conversion_chrono_to_pb() {
let chrono_duration = chrono::Duration::try_seconds(10).expect("seconds") + chrono::Duration::nanoseconds(100);
let chrono_duration = chrono::Duration::try_seconds(10).expect("seconds")
+ chrono::Duration::nanoseconds(100);
let duration: Duration = chrono_duration.into();
assert_eq!(duration.seconds, 10);
assert_eq!(duration.nanos, 100);
Expand Down
1 change: 0 additions & 1 deletion wkt-types/src/pbtime/timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,4 +320,3 @@ impl<'de> Deserialize<'de> for Timestamp {
deserializer.deserialize_str(TimestampVisitor)
}
}

5 changes: 2 additions & 3 deletions wkt-types/tests/pbstruct_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn test_flatten_struct() {
let mut fields: HashMap<String, Value> = HashMap::new();
fields.insert("test".to_string(), create_struct());
let strct = Struct {
fields: fields.clone()
fields: fields.clone(),
};
let string_strct = serde_json::to_string_pretty(&strct).expect("Serialized struct");
println!("{string_strct}");
Expand All @@ -46,7 +46,7 @@ fn test_flatten_struct() {
fn test_flatten_list() {
let values: Vec<Value> = vec![Value::null(), Value::from(20.0), Value::from(true)];
let list: ListValue = ListValue {
values: values.clone()
values: values.clone(),
};
let string_list = serde_json::to_string_pretty(&list).expect("Serialized list");
println!("{string_list}");
Expand All @@ -56,5 +56,4 @@ fn test_flatten_list() {
println!("{string}");

assert_eq!(string_list, string);

}

0 comments on commit 556822f

Please sign in to comment.