diff --git a/src/error.rs b/src/error.rs index 249d481..c420438 100644 --- a/src/error.rs +++ b/src/error.rs @@ -5,7 +5,7 @@ use jiter::JsonValue; /// A content-less variant of the [JsonValue] enum, used for reporting errors, see [MerdeJsonError::MismatchedType]. -#[derive(Debug)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum JsonFieldType { /// The JSON value is `null`. @@ -78,6 +78,9 @@ pub enum MerdeJsonError { /// While parsing a [time::Date] or [time::Time], we got an error. InvalidDateTimeValue, + + /// An I/O error occurred. + Io(std::io::Error), } impl From for MerdeJsonError { @@ -86,6 +89,12 @@ impl From for MerdeJsonError { } } +impl From for MerdeJsonError { + fn from(e: std::io::Error) -> Self { + MerdeJsonError::Io(e) + } +} + impl std::fmt::Display for MerdeJsonError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { @@ -120,6 +129,9 @@ impl std::fmt::Display for MerdeJsonError { MerdeJsonError::InvalidDateTimeValue => { write!(f, "Invalid date/time value") } + MerdeJsonError::Io(e) => { + write!(f, "I/O error: {}", e) + } } } } diff --git a/src/lib.rs b/src/lib.rs index 8e223fc..cc437b9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1189,16 +1189,43 @@ where } } -/// Parses a JSON byte string into a [JsonValue]. -pub fn from_slice(data: &[u8]) -> Result, MerdeJsonError> { +/// Deserialize an instance of type `T` from bytes of JSON text. +pub fn from_slice(data: &[u8]) -> Result, MerdeJsonError> { Ok(jiter::JsonValue::parse(data, false)?) } -/// Parses a JSON string into a [JsonValue]. -pub fn from_str(s: &str) -> Result, MerdeJsonError> { +/// Deserialize an instance of type `T` from a string of JSON text. +pub fn from_str(s: &str) -> Result, MerdeJsonError> { from_slice(s.as_bytes()) } +/// Interpret a `JsonValue` as an instance of type `T`. +pub fn from_value<'src: 'val, 'val, T>(value: &'val JsonValue<'src>) -> Result +where + T: JsonDeserialize<'src, 'val>, +{ + T::json_deserialize(Some(value)) +} + +/// Serialize the given data structure as a String of JSON. +pub fn to_string(value: &T) -> String { + value.to_json_string() +} + +/// Serialize the given data structure as a JSON byte vector. +pub fn to_vec(value: &T) -> Vec { + value.to_json_bytes() +} + +/// Serialize the given data structure as JSON into the I/O stream. +pub fn to_writer(mut writer: impl std::io::Write, value: &T) -> std::io::Result<()> +where + T: JsonSerialize, +{ + let bytes = value.to_json_bytes(); + writer.write_all(&bytes) +} + /// Allow turning a value into an "owned" variant, which can then be /// returned, moved, etc. ///