docs(Codec trait): Add function comments
@@ -14,20 +14,23 @@ pub use ::async_trait;
pub use eyre;
pub use stencila_schema;
-/// A codec for for decoding/encoding nodes
+/// A codec for decoding and encoding Stencila document nodes to one or more formats
///
-/// Defines similar functions to `serde_json` (and other `serde` crates) for
+/// This trait defines similar functions to `serde_json` (and other `serde` crates) for
/// converting nodes to/from strings, files, readers etc.
#[async_trait]
pub trait Codec {
+ /// Decode a document node from a string
fn from_str(_str: &str) -> Result<Node> {
bail!("Decoding from string is not implemented for this format")
}
+ /// Decode a document node from a string asynchronously
async fn from_str_async(str: &str) -> Result<Node> {
Self::from_str(str)
}
+ /// Decode a document node from a `BufReader`
async fn from_buffer<T: Read>(reader: &mut BufReader<T>) -> Result<Node>
where
T: Send + Sync,
@@ -37,12 +40,18 @@ pub trait Codec {
Self::from_str(&content)
}
+ /// Decode a document node from a file
+ ///
+ /// This function reads the file as a string and passes that on to `from_str`
+ /// for decoding. If working with binary formats, you should override this function
+ /// to read the file as bytes instead.
async fn from_file(file: &mut File) -> Result<Node> {
let mut content = String::new();
file.read_to_string(&mut content)?;
Self::from_str(&content)
}
+ /// Decode a document node from a file system path
async fn from_path<T: AsRef<Path>>(path: &T) -> Result<Node>
where
T: Send + Sync,
@@ -51,14 +60,17 @@ pub trait Codec {
Self::from_file(&mut file).await
}
+ /// Encode a document node to a string
fn to_string(_node: &Node, _options: Option<EncodeOptions>) -> Result<String> {
bail!("Encoding to string is not implemented for this format")
}
+ /// Encode a document node to a string asynchronously
async fn to_string_async(node: &Node, options: Option<EncodeOptions>) -> Result<String> {
Self::to_string(node, options)
}
+ /// Encode a document node to a `BufWriter`
async fn to_buffer<T: Write>(
node: &Node,
writer: &mut BufWriter<T>,
@@ -72,12 +84,14 @@ pub trait Codec {
Ok(())
}
+ /// Encode a document node to a file
async fn to_file(node: &Node, file: &mut File, options: Option<EncodeOptions>) -> Result<()> {
let content = Self::to_string(node, options)?;
file.write_all(content.as_bytes())?;
Ok(())
}
+ /// Encode a document node to a file system path
async fn to_path<T: AsRef<Path>>(
node: &Node,
path: &T,
