pub trait ResponseBody {
// Required method
fn deserialize<T: for<'a> Deserialize<'a>>(
&self,
value: Vec<u8>,
) -> Result<T>;
}Expand description
Trait that represents response body deserialization capabilities.
This trait defines the interface for converting HTTP response bodies from bytes into Rust types. Implementations handle different deserialization formats like JSON, XML, text, etc.
§Requirements
Implementations must:
- Parse bytes into the target Rust type
- Handle deserialization errors appropriately
- Support the target data format
§Examples
§JSON Deserializer
ⓘ
use deboa::client::serde::ResponseBody;
use deboa::Result;
use serde::Deserialize;
struct JsonBody;
impl ResponseBody for JsonBody {
fn deserialize<T: for<'de> Deserialize<'de>>(&self, bytes: &[u8]) -> Result<T> {
serde_json::from_slice(bytes)
.map_err(|e| DeboaError::DeserializationError(e.to_string()))
}
}§Text Deserializer
ⓘ
use deboa::client::serde::ResponseBody;
use deboa::Result;
use std::str;
struct TextBody;
impl ResponseBody for TextBody {
fn deserialize<T: for<'de> Deserialize<'de>>(&self, bytes: &[u8]) -> Result<T> {
let text = str::from_utf8(bytes)
.map_err(|e| DeboaError::DeserializationError(e.to_string()))?;
// For simple string types
if std::any::TypeId::of::<T>() == std::any::TypeId::of::<String>() {
// SAFETY: We've verified the type
Ok(unsafe { std::mem::transmute_copy(&text) })
} else {
Err(DeboaError::DeserializationError("Unsupported type".to_string()))
}
}
}Required Methods§
Sourcefn deserialize<T: for<'a> Deserialize<'a>>(&self, value: Vec<u8>) -> Result<T>
fn deserialize<T: for<'a> Deserialize<'a>>(&self, value: Vec<u8>) -> Result<T>
Deserialize the response body
Converts the given byte vector into the target Rust type.
§Arguments
value- The response body bytes to deserialize
§Returns
Result<T>- The deserialized response body
§Errors
Returns an error if deserialization fails, such as when:
- The bytes cannot be parsed as the target format
- The data structure doesn’t match the expected type
- The bytes contain invalid UTF-8 for text formats
§Type Parameters
T- The target type to deserialize into, must implementDeserialize
§Examples
ⓘ
fn deserialize<T: for<'de> Deserialize<'de>>(&self, value: Vec<u8>) -> Result<T> {
serde_json::from_slice(&value)
.map_err(|e| DeboaError::DeserializationError(e.to_string()))
}Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".