Expand description
This crate provides simple traits for reading and writing objects.
The traits ObjectReader
and ObjectWriter
are not intended as a generalized serialization
framework like serde, they are provided to simply read/write specific object
types in specific formats. These traits were refactored from the rdftk_io
crate that provided a
number of parsers and generators for different RDF representations.
As a number of implementations require options to configure parsers and generators the trait
HasOptions
can be implemented to provide this in a common manner.
§Example Writer
- The type
TestObject
is the type we wich to be able to write, it has a single string field. - The type
TestError
is required as it can be created from an IO error instance. - The type
TestOptions
are the options that configure our generator, currently only defining the amount of indentation before writingTestObject
instances. - The type TestWriter` is where the magic starts, …
- It contains a field for the options above.
- It implements the trait
HasOptions
using the macroimpl_has_options!
. - It implements the trait
ObjectWriter
.
- We the construct an example instance of the test object and an instance of the writer with options.
- Finally, we write the example object and compare it to expected results.
use objio::{impl_has_options, HasOptions, ObjectWriter};
use std::io::Write;
#[derive(Debug, Default)]
struct TestObject { // our writeable type
value: String,
}
#[derive(Debug, Default)]
struct TestError {} // implements From<std::io::Error>
#[derive(Debug, Default)]
struct TestOptions {
indent: usize,
}
#[derive(Debug, Default)]
struct TestWriter {
options: TestOptions,
}
impl_has_options!(TestWriter, TestOptions);
impl ObjectWriter<TestObject> for TestWriter {
type Error = TestError;
fn write<W>(&self, w: &mut W, object: &TestObject) -> Result<(), Self::Error>
where
W: Write,
{
let indent = self.options.indent;
let value = &object.value;
w.write_all(format!("{:indent$}{value}", "").as_bytes())?;
Ok(())
}
}
let example = TestObject::from("Hello");
let writer = TestWriter::default().with_options(TestOptions { indent: 2 });
assert_eq!(
writer.write_to_string(&example).unwrap(),
" Hello".to_string()
);
Macros§
- impl_
has_ options - Provides a boiler-place implementation of
HasOptions
. - impl_
into_ string_ writer - Provides a simple implementation of
ObjectWriter
where an existing implementation ofInto<String>
provides the serialized form. - impl_
to_ string_ writer - Provides a simple implementation of
ObjectWriter
where the existing implementation ofDisplay
provides the serialized form via theToString
trait.
Traits§
- HasOptions
- This trait is implemented by reader or writer types to attach option instances for configuration.
- Object
Reader - The trait implemented by types which read instances of
T
. - Object
Writer - The trait implemented by types which write instances of
T
.