Trait mokuroku::Document

source ·
pub trait Document: Sized {
    // Required methods
    fn from_bytes(key: &[u8], value: &[u8]) -> Result<Self, Error>;
    fn to_bytes(&self) -> Result<Vec<u8>, Error>;
    fn map(&self, view: &str, emitter: &Emitter<'_>) -> Result<(), Error>;
}
Expand description

Document defines operations required for building the index.

Any data that should contribute to an index should be represented by a type that implements this trait, and be stored in the database using the Database wrapper method put().

The primary reason for this trait is that when put() is called with an instance of Document, there is no need to deserialize the value when calling map(), since it is already in its natural form. The map() function will eventually receive every view name that was initially provided when opening the database, and it is up to each Document implementation to ignore views that are not relevant.

This example is using the serde crate, which provides the Serialize and Deserialize derivations.

#[derive(Serialize, Deserialize)]
struct Asset {
    #[serde(skip)]
    key: String,
    location: String,
    tags: Vec<String>,
}

impl Document for Asset {
    fn from_bytes(key: &[u8], value: &[u8]) -> Result<Self, Error> {
        let mut serde_result: Asset = serde_cbor::from_slice(value).map_err(|err| Error::Serde(format!("{}", err)))?;
        serde_result.key = str::from_utf8(key)?.to_owned();
        Ok(serde_result)
    }

    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
        let encoded: Vec<u8> = serde_cbor::to_vec(self).map_err(|err| Error::Serde(format!("{}", err)))?;
        Ok(encoded)
    }

    fn map(&self, view: &str, emitter: &Emitter) -> Result<(), Error> {
        if view == "tags" {
            for tag in &self.tags {
                emitter.emit(tag.as_bytes(), Some(&self.location.as_bytes()))?;
            }
        }
        Ok(())
    }
}

Required Methods§

source

fn from_bytes(key: &[u8], value: &[u8]) -> Result<Self, Error>

Deserializes a sequence of bytes to return a value of this type.

The key is provided in case it is required for proper deserialization. For example, the document may be deserialized from the raw value, and then the unique identifier copied from the raw key.

source

fn to_bytes(&self) -> Result<Vec<u8>, Error>

Serializes this value into a sequence of bytes.

source

fn map(&self, view: &str, emitter: &Emitter<'_>) -> Result<(), Error>

Map this document to zero or more index key/value pairs.

Object Safety§

This trait is not object safe.

Implementors§