From 4c6207a1aebfc25dab9f34c6610cd4daa5b7b1fc Mon Sep 17 00:00:00 2001 From: mwtian <81660174+mwtian@users.noreply.github.com> Date: Fri, 12 Aug 2022 02:55:49 -0700 Subject: [PATCH] Add `bytes_len()` to Params (#848) * add len() to Params * Rename to `len_bytes()` Co-authored-by: Niklas Adolfsson * Update comment. Co-authored-by: Niklas Adolfsson * Update types/src/params.rs * Update types/src/params.rs * Update types/src/params.rs * Update types/src/params.rs Co-authored-by: Niklas Adolfsson --- types/src/params.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/src/params.rs b/types/src/params.rs index 0cea331592..8dcf99654f 100644 --- a/types/src/params.rs +++ b/types/src/params.rs @@ -141,6 +141,14 @@ impl<'a> Params<'a> { pub fn into_owned(self) -> Params<'static> { Params(self.0.map(|s| Cow::owned(s.into_owned()))) } + + /// Return the length of underlying JSON string in number of bytes. + pub fn len_bytes(&self) -> usize { + match self.0 { + Some(ref cow) => cow.len(), + None => 0, + } + } } /// An `Iterator`-like parser for a sequence of [`Params`]. @@ -463,8 +471,10 @@ mod test { let none = Params::new(None); assert!(none.sequence().next::().is_err()); assert!(none.parse::>().is_ok()); + assert_eq!(none.len_bytes(), 0); let array_params = Params::new(Some("[1, 2, 3]")); + assert_eq!(array_params.len_bytes(), 9); let arr: Result<[u64; 3], _> = array_params.parse(); assert!(arr.is_ok()); @@ -476,10 +486,12 @@ mod test { assert!(seq.next::().is_err()); let array_one = Params::new(Some("[1]")); + assert_eq!(array_one.len_bytes(), 3); let one: Result = array_one.one(); assert!(one.is_ok()); let object_params = Params::new(Some(r#"{"beef":99,"dinner":0}"#)); + assert_eq!(object_params.len_bytes(), 22); let obj: Result = object_params.parse(); assert!(obj.is_ok()); }