#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceContents {
pub uri: String,
pub mime_type: Option<String>,
pub body: ResourceBody,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceBody {
Text(String),
Blob(String),
}
impl ResourceContents {
#[must_use]
pub fn text(uri: impl Into<String>, text: impl Into<String>) -> Self {
Self {
uri: uri.into(),
mime_type: None,
body: ResourceBody::Text(text.into()),
}
}
#[must_use]
pub fn blob(uri: impl Into<String>, base64: impl Into<String>) -> Self {
Self {
uri: uri.into(),
mime_type: None,
body: ResourceBody::Blob(base64.into()),
}
}
#[must_use]
pub fn with_mime_type(mut self, mime_type: impl Into<String>) -> Self {
self.mime_type = Some(mime_type.into());
self
}
}
#[cfg(test)]
mod tests {
use super::{ResourceBody, ResourceContents};
#[test]
fn a_text_resource_carries_its_body_as_text() -> Result<(), String> {
let contents = ResourceContents::text("test://a", "hello");
match contents.body {
ResourceBody::Text(ref text) if text == "hello" => {}
other => return Err(format!("the body was {other:?}")),
}
if contents.uri != "test://a" {
return Err(format!("the uri was {:?}", contents.uri));
}
Ok(())
}
#[test]
fn a_blob_resource_carries_its_body_as_a_blob() -> Result<(), String> {
let contents = ResourceContents::blob("test://a", "aGk=");
match contents.body {
ResourceBody::Blob(ref data) if data == "aGk=" => Ok(()),
other => Err(format!("the body was {other:?}")),
}
}
#[test]
fn a_media_type_attaches_without_touching_the_body() -> Result<(), String> {
let contents = ResourceContents::text("test://a", "hello").with_mime_type("text/markdown");
match contents.mime_type.as_deref() {
Some("text/markdown") => {}
other => return Err(format!("the mime type was {other:?}")),
}
match &contents.body {
ResourceBody::Text(text) if text == "hello" => Ok(()),
other => Err(format!("the body became {other:?}")),
}
}
}