use crate::index::config::{
IndexOrd, IndexTypeId, IndexTypeInternal, IndexTypeUnwrap, IndexTypeWrap, check_over_size_limit,
};
use std::{cmp::Ordering, fmt::Display, str::from_utf8, sync::Arc};
impl IndexTypeWrap for String {
type Wrapper = StringWrapper;
fn wrap(self) -> Self::Wrapper {
StringWrapper::new(self)
}
}
impl IndexTypeUnwrap for String {
type Wrapped = String;
fn unwrap(self) -> Self::Wrapped {
self
}
}
impl IndexTypeUnwrap for StringWrapper {
type Wrapped = String;
fn unwrap(self) -> Self::Wrapped {
self.as_str().to_owned()
}
}
#[derive(Clone, Debug)]
pub struct StringWrapper {
value: Arc<Vec<u8>>,
start: usize,
size: usize,
}
impl PartialEq for StringWrapper {
fn eq(&self, other: &Self) -> bool {
IndexOrd::cmp(self, other) == Ordering::Equal
}
}
impl StringWrapper {
pub(crate) fn new(s: String) -> Self {
let len = s.len();
StringWrapper {
value: Arc::new(s.into_bytes()),
start: 0,
size: len,
}
}
pub(crate) fn new_slice(value: Arc<Vec<u8>>, start: usize, size: usize) -> Self {
Self { value, start, size }
}
fn as_str(&self) -> &str {
from_utf8(&self.value[self.start..self.start + self.size]).unwrap()
}
pub(crate) fn slice(&self) -> &[u8] {
&self.value[self.start..self.start + self.size]
}
pub(crate) fn len(&self) -> usize {
self.size
}
}
impl IndexTypeInternal for StringWrapper {
fn get_id() -> u8 {
12
}
fn get_type_id() -> crate::IndexTypeId {
IndexTypeId::String
}
fn over_size_limit(&self) -> bool {
check_over_size_limit(self.size)
}
}
impl Display for StringWrapper {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl IndexOrd for StringWrapper {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.slice().cmp(other.slice())
}
}