milli_core/heed_codec/
str_ref.rs

1use std::borrow::Cow;
2
3use heed::{BoxedError, BytesDecode, BytesEncode};
4
5/// A codec for values of type `&str`. Unlike `Str`, its `EItem` and `DItem` associated
6/// types are equivalent (= `&'a str`) and these values can reside within another structure.
7pub struct StrRefCodec;
8impl<'a> BytesEncode<'a> for StrRefCodec {
9    type EItem = &'a str;
10
11    fn bytes_encode(item: &'a &'a str) -> Result<Cow<'a, [u8]>, BoxedError> {
12        Ok(Cow::Borrowed(item.as_bytes()))
13    }
14}
15impl<'a> BytesDecode<'a> for StrRefCodec {
16    type DItem = &'a str;
17
18    fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, BoxedError> {
19        std::str::from_utf8(bytes).map_err(Into::into)
20    }
21}