use crate::error::Result;
use std::fs::File;
#[cfg(unix)]
use std::os::unix::fs::FileExt;
#[cfg(windows)]
use std::os::windows::fs::FileExt;
use std::sync::Arc;
use std::sync::RwLock;
pub trait RandomAccess: Send + Sync {
fn read_at(&self, off: usize, dst: &mut [u8]) -> Result<usize>;
}
#[allow(unused)]
pub type BufferBackedFile = Vec<u8>;
impl RandomAccess for BufferBackedFile {
fn read_at(&self, off: usize, dst: &mut [u8]) -> Result<usize> {
if off > self.len() {
return Ok(0);
}
let remaining = self.len() - off;
let to_read = if dst.len() > remaining {
remaining
} else {
dst.len()
};
(&mut dst[0..to_read]).copy_from_slice(&self[off..off + to_read]);
Ok(to_read)
}
}
#[cfg(unix)]
impl RandomAccess for File {
fn read_at(&self, off: usize, dst: &mut [u8]) -> Result<usize> {
Ok((self as &dyn FileExt).read_at(dst, off as u64)?)
}
}
#[cfg(windows)]
impl RandomAccess for File {
fn read_at(&self, off: usize, dst: &mut [u8]) -> Result<usize> {
Ok((self as &dyn FileExt).seek_read(dst, off as u64)?)
}
}
pub type Shared<T> = Arc<RwLock<T>>;
pub fn share<T>(t: T) -> Arc<RwLock<T>> {
Arc::new(RwLock::new(t))
}
pub trait SSIterator {
fn advance(&mut self) -> bool;
fn current(&self, key: &mut Vec<u8>, val: &mut Vec<u8>) -> bool;
fn current_key(&self) -> Option<&[u8]>;
fn seek(&mut self, key: &[u8]);
fn reset(&mut self);
fn valid(&self) -> bool;
fn prev(&mut self) -> bool;
fn next(&mut self) -> Option<(Vec<u8>, Vec<u8>)> {
if !self.advance() {
return None;
}
let (mut key, mut val) = (vec![], vec![]);
if self.current(&mut key, &mut val) {
Some((key, val))
} else {
None
}
}
fn seek_to_first(&mut self) {
self.reset();
self.advance();
}
}
pub fn current_key_val<It: SSIterator + ?Sized>(it: &It) -> Option<(Vec<u8>, Vec<u8>)> {
let (mut k, mut v) = (vec![], vec![]);
if it.current(&mut k, &mut v) {
Some((k, v))
} else {
None
}
}
impl SSIterator for Box<dyn SSIterator> {
fn advance(&mut self) -> bool {
self.as_mut().advance()
}
fn current(&self, key: &mut Vec<u8>, val: &mut Vec<u8>) -> bool {
self.as_ref().current(key, val)
}
fn current_key(&self) -> Option<&[u8]> {
self.as_ref().current_key()
}
fn seek(&mut self, key: &[u8]) {
self.as_mut().seek(key)
}
fn reset(&mut self) {
self.as_mut().reset()
}
fn valid(&self) -> bool {
self.as_ref().valid()
}
fn prev(&mut self) -> bool {
self.as_mut().prev()
}
}
impl Iterator for dyn SSIterator {
type Item = (Vec<u8>, Vec<u8>);
fn next(&mut self) -> Option<Self::Item> {
self.next()
}
}
const MASK_DELTA: u32 = 0xa282ead8;
pub fn mask_crc(c: u32) -> u32 {
(c.wrapping_shr(15) | c.wrapping_shl(17)).wrapping_add(MASK_DELTA)
}
pub fn unmask_crc(mc: u32) -> u32 {
let rot = mc.wrapping_sub(MASK_DELTA);
rot.wrapping_shr(17) | rot.wrapping_shl(15)
}
#[cfg(test)]
mod tests {}