loro/crates/rle/src/rle_impl.rs

115 lines
2.6 KiB
Rust
Raw Normal View History

2022-10-24 03:51:36 +00:00
use std::ops::Range;
2022-10-24 09:17:27 +00:00
use crate::{rle_trait::GlobalIndex, HasIndex, HasLength, Mergable, Sliceable};
use append_only_bytes::{AppendOnlyBytes, BytesSlice};
2022-10-26 10:40:08 +00:00
use num::{cast, Integer, NumCast};
2022-10-24 03:51:36 +00:00
use smallvec::{Array, SmallVec};
2022-10-08 08:04:25 +00:00
impl Sliceable for bool {
fn slice(&self, _: usize, _: usize) -> Self {
*self
}
}
2022-10-24 03:51:36 +00:00
impl<T: Integer + NumCast + Copy> Sliceable for Range<T> {
fn slice(&self, start: usize, end: usize) -> Self {
self.start + cast(start).unwrap()..self.start + cast(end).unwrap()
}
}
impl<T: PartialOrd<T> + Copy> Mergable for Range<T> {
fn is_mergable(&self, other: &Self, _: &()) -> bool {
other.start <= self.end && other.start >= self.start
}
fn merge(&mut self, other: &Self, _conf: &())
where
Self: Sized,
{
self.end = other.end;
}
}
impl<T: num::Integer + NumCast + Copy> HasLength for Range<T> {
2022-10-24 06:48:08 +00:00
fn content_len(&self) -> usize {
2022-10-24 03:51:36 +00:00
cast(self.end - self.start).unwrap()
}
}
2022-10-24 09:17:27 +00:00
impl<T: GlobalIndex + NumCast> HasIndex for Range<T> {
type Int = T;
fn get_start_index(&self) -> Self::Int {
self.start
}
}
2022-10-24 03:51:36 +00:00
/// this can make iter return type has len
impl<A, T: HasLength> HasLength for (A, T) {
2022-10-24 06:48:08 +00:00
fn content_len(&self) -> usize {
self.1.content_len()
2022-10-24 03:51:36 +00:00
}
}
/// this can make iter return type has len
impl<T: HasLength> HasLength for &T {
2022-10-24 06:48:08 +00:00
fn content_len(&self) -> usize {
(*self).content_len()
2022-10-24 03:51:36 +00:00
}
}
impl<T: HasLength + Sliceable, A: Array<Item = T>> Sliceable for SmallVec<A> {
fn slice(&self, from: usize, to: usize) -> Self {
let mut index = 0;
let mut ans: SmallVec<A> = smallvec::smallvec![];
if to == from {
return ans;
}
for item in self.iter() {
2022-10-24 06:48:08 +00:00
if index < to && from < index + item.atom_len() {
2022-10-24 03:51:36 +00:00
let start = if index < from { from - index } else { 0 };
2022-10-24 06:48:08 +00:00
ans.push(item.slice(start, item.atom_len().min(to - index)));
2022-10-24 03:51:36 +00:00
}
2022-10-24 06:48:08 +00:00
index += item.atom_len();
2022-10-24 03:51:36 +00:00
}
ans
}
}
impl HasLength for AppendOnlyBytes {
fn content_len(&self) -> usize {
self.len()
}
}
impl HasLength for BytesSlice {
fn content_len(&self) -> usize {
self.len()
}
}
impl Sliceable for BytesSlice {
fn slice(&self, from: usize, to: usize) -> Self {
self.slice_clone(from..to)
}
}
impl Mergable for BytesSlice {
fn is_mergable(&self, other: &Self, _conf: &()) -> bool
where
Self: Sized,
{
self.can_merge(other)
}
fn merge(&mut self, other: &Self, _conf: &())
where
Self: Sized,
{
self.try_merge(other).unwrap()
}
}