Create and use real error types in the codecs

This commit is contained in:
Clément Renault
2023-11-28 10:11:17 +01:00
parent d32eb11329
commit 548c8247c2
7 changed files with 43 additions and 38 deletions

View File

@@ -3,6 +3,7 @@ use std::marker::PhantomData;
use heed::{BoxedError, BytesDecode, BytesEncode};
use crate::heed_codec::SliceTooShortError;
use crate::{try_split_array_at, DocumentId, FieldId};
pub struct FieldDocIdFacetCodec<C>(PhantomData<C>);
@@ -14,10 +15,10 @@ where
type DItem = (FieldId, DocumentId, C::DItem);
fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, BoxedError> {
let (field_id_bytes, bytes) = try_split_array_at(bytes).unwrap();
let (field_id_bytes, bytes) = try_split_array_at(bytes).ok_or(SliceTooShortError)?;
let field_id = u16::from_be_bytes(field_id_bytes);
let (document_id_bytes, bytes) = try_split_array_at(bytes).unwrap();
let (document_id_bytes, bytes) = try_split_array_at(bytes).ok_or(SliceTooShortError)?;
let document_id = u32::from_be_bytes(document_id_bytes);
let value = C::bytes_decode(bytes)?;

View File

@@ -2,8 +2,10 @@ use std::borrow::Cow;
use std::convert::TryInto;
use heed::{BoxedError, BytesDecode};
use thiserror::Error;
use crate::facet::value_encoding::f64_into_bytes;
use crate::heed_codec::SliceTooShortError;
pub struct OrderedF64Codec;
@@ -12,7 +14,7 @@ impl<'a> BytesDecode<'a> for OrderedF64Codec {
fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, BoxedError> {
if bytes.len() < 16 {
Err(BoxedError::from("invalid slice length"))
Err(SliceTooShortError.into())
} else {
bytes[8..].try_into().map(f64::from_be_bytes).map_err(Into::into)
}
@@ -26,8 +28,7 @@ impl heed::BytesEncode<'_> for OrderedF64Codec {
let mut buffer = [0u8; 16];
// write the globally ordered float
let bytes = f64_into_bytes(*f)
.ok_or_else(|| BoxedError::from("cannot generate a globally ordered float"))?;
let bytes = f64_into_bytes(*f).ok_or(InvalidGloballyOrderedFloatError { float: *f })?;
buffer[..8].copy_from_slice(&bytes[..]);
// Then the f64 value just to be able to read it back
let bytes = f.to_be_bytes();
@@ -36,3 +37,9 @@ impl heed::BytesEncode<'_> for OrderedF64Codec {
Ok(Cow::Owned(buffer.to_vec()))
}
}
#[derive(Error, Debug)]
#[error("the float {float} cannot be converted to a globally ordered representation")]
pub struct InvalidGloballyOrderedFloatError {
float: f64,
}