use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub struct Block(Arc<Shared>);
#[derive(Debug)]
struct Shared {
state: Mutex<State>,
woken: Condvar,
}
#[derive(Debug)]
struct State {
bytes: Vec<u8>,
max_byte_length: Option<usize>,
waiters: Vec<Waiter>,
next: u64,
}
#[derive(Debug)]
struct Waiter {
offset: usize,
id: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wait {
NotEqual,
Ok,
TimedOut,
}
impl Wait {
#[must_use]
pub fn name(self) -> &'static str {
match self {
Self::NotEqual => "not-equal",
Self::Ok => "ok",
Self::TimedOut => "timed-out",
}
}
}
impl Block {
#[must_use]
pub fn new(length: usize) -> Self {
Self(Arc::new(Shared {
state: Mutex::new(State {
bytes: vec![0; length],
max_byte_length: None,
waiters: Vec::new(),
next: 0,
}),
woken: Condvar::new(),
}))
}
#[must_use]
pub fn is(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
fn state(&self) -> MutexGuard<'_, State> {
self.0.state.lock().unwrap_or_else(PoisonError::into_inner)
}
fn with_bytes<R>(&self, read: impl FnOnce(&[u8]) -> R) -> R {
read(&self.state().bytes)
}
fn with_bytes_mut<R>(&self, write: impl FnOnce(&mut [u8]) -> R) -> R {
write(&mut self.state().bytes)
}
fn byte_length(&self) -> usize {
self.state().bytes.len()
}
fn max_byte_length(&self) -> Option<usize> {
self.state().max_byte_length
}
fn allow_resizing_to(&self, max: usize) {
self.state().max_byte_length = Some(max);
}
fn resize(&self, length: usize) -> bool {
let mut state = self.state();
if state.max_byte_length.is_none_or(|max| length > max) {
return false;
}
state.bytes.resize(length, 0);
true
}
pub fn wait(&self, offset: usize, expected: &[u8], timeout: Option<Duration>) -> Wait {
let mut state = self.state();
if state.bytes.get(offset..offset + expected.len()) != Some(expected) {
return Wait::NotEqual;
}
let deadline = timeout.and_then(|timeout| Instant::now().checked_add(timeout));
let id = state.next;
state.next = state.next.wrapping_add(1);
state.waiters.push(Waiter { offset, id });
loop {
if !state.waiters.iter().any(|waiting| waiting.id == id) {
return Wait::Ok;
}
let left = match deadline {
None => None,
Some(deadline) => match deadline.checked_duration_since(Instant::now()) {
Some(left) => Some(left),
None => {
state.waiters.retain(|waiting| waiting.id != id);
return Wait::TimedOut;
}
},
};
state = match left {
None => self
.0
.woken
.wait(state)
.unwrap_or_else(PoisonError::into_inner),
Some(left) => {
self.0
.woken
.wait_timeout(state, left)
.unwrap_or_else(PoisonError::into_inner)
.0
}
};
}
}
pub fn notify(&self, offset: usize, count: usize) -> usize {
let mut state = self.state();
let mut woken = 0;
state.waiters.retain(|waiting| {
if waiting.offset == offset && woken < count {
woken += 1;
return false;
}
true
});
self.0.woken.notify_all();
woken
}
}
#[derive(Debug)]
pub struct Buffer {
bytes: Bytes,
max_byte_length: Option<usize>,
}
#[derive(Debug)]
enum Bytes {
Own(Option<Vec<u8>>),
Shared(Block),
}
impl Buffer {
#[must_use]
pub fn new(length: usize) -> Self {
Self {
bytes: Bytes::Own(Some(vec![0; length])),
max_byte_length: None,
}
}
#[must_use]
pub fn new_shared(length: usize) -> Self {
Self::over(&Block::new(length))
}
#[must_use]
pub fn over(block: &Block) -> Self {
Self {
bytes: Bytes::Shared(block.clone()),
max_byte_length: None,
}
}
pub fn allow_resizing_to(&mut self, max: usize) {
match &self.bytes {
Bytes::Own(_) => self.max_byte_length = Some(max),
Bytes::Shared(block) => block.allow_resizing_to(max),
}
}
#[must_use]
pub fn max_byte_length(&self) -> Option<usize> {
match &self.bytes {
Bytes::Own(_) => self.max_byte_length,
Bytes::Shared(block) => block.max_byte_length(),
}
}
pub fn resize(&mut self, length: usize) -> bool {
match &mut self.bytes {
Bytes::Shared(block) => block.resize(length),
Bytes::Own(bytes) => {
if self.max_byte_length.is_none_or(|max| length > max) {
return false;
}
if let Some(bytes) = bytes.as_mut() {
bytes.resize(length, 0);
}
true
}
}
}
#[must_use]
pub fn shared(&self) -> bool {
matches!(self.bytes, Bytes::Shared(_))
}
#[must_use]
pub fn block(&self) -> Option<&Block> {
match &self.bytes {
Bytes::Own(_) => None,
Bytes::Shared(block) => Some(block),
}
}
pub fn with_bytes<R>(&self, read: impl FnOnce(Option<&[u8]>) -> R) -> R {
match &self.bytes {
Bytes::Own(bytes) => read(bytes.as_deref()),
Bytes::Shared(block) => block.with_bytes(|bytes| read(Some(bytes))),
}
}
pub fn with_bytes_mut<R>(&mut self, write: impl FnOnce(Option<&mut [u8]>) -> R) -> R {
match &mut self.bytes {
Bytes::Own(bytes) => write(bytes.as_deref_mut()),
Bytes::Shared(block) => block.with_bytes_mut(|bytes| write(Some(bytes))),
}
}
pub fn modify_bytes(
&mut self,
offset: usize,
width: usize,
change: impl FnOnce(&[u8]) -> Option<Vec<u8>>,
) -> Option<Vec<u8>> {
self.with_bytes_mut(|bytes| {
let slot = bytes?.get_mut(offset..offset + width)?;
let held = slot.to_vec();
if let Some(written) = change(&held)
&& let Some(target) = slot.get_mut(..written.len())
{
target.copy_from_slice(&written);
}
Some(held)
})
}
#[must_use]
pub fn byte_length(&self) -> usize {
match &self.bytes {
Bytes::Own(bytes) => bytes.as_ref().map_or(0, Vec::len),
Bytes::Shared(block) => block.byte_length(),
}
}
#[must_use]
pub fn detached(&self) -> bool {
matches!(self.bytes, Bytes::Own(None))
}
pub fn detach(&mut self) {
if let Bytes::Own(bytes) = &mut self.bytes {
*bytes = None;
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Element {
Int8,
Uint8,
Int16,
Uint16,
Int32,
Uint32,
BigInt64,
BigUint64,
Float32,
Float64,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Numeric {
Number(f64),
BigInt(crate::bigint::BigInt),
}
impl Element {
#[must_use]
pub fn width(self) -> usize {
match self {
Self::Int8 | Self::Uint8 => 1,
Self::Int16 | Self::Uint16 => 2,
Self::Int32 | Self::Uint32 | Self::Float32 => 4,
Self::BigInt64 | Self::BigUint64 | Self::Float64 => 8,
}
}
#[must_use]
pub fn holds_big(self) -> bool {
matches!(self, Self::BigInt64 | Self::BigUint64)
}
#[must_use]
pub fn name(self) -> &'static str {
match self {
Self::Int8 => "Int8",
Self::Uint8 => "Uint8",
Self::Int16 => "Int16",
Self::Uint16 => "Uint16",
Self::Int32 => "Int32",
Self::Uint32 => "Uint32",
Self::BigInt64 => "BigInt64",
Self::BigUint64 => "BigUint64",
Self::Float32 => "Float32",
Self::Float64 => "Float64",
}
}
#[must_use]
pub fn read(self, bytes: &[u8]) -> Numeric {
let mut eight = [0_u8; 8];
eight[..bytes.len()].copy_from_slice(bytes);
let number = match self {
Self::Int8 => f64::from(eight[0] as i8),
Self::Uint8 => f64::from(eight[0]),
Self::Int16 => f64::from(i16::from_le_bytes([eight[0], eight[1]])),
Self::Uint16 => f64::from(u16::from_le_bytes([eight[0], eight[1]])),
Self::Int32 => f64::from(i32::from_le_bytes([eight[0], eight[1], eight[2], eight[3]])),
Self::Uint32 => f64::from(u32::from_le_bytes([eight[0], eight[1], eight[2], eight[3]])),
Self::BigInt64 | Self::BigUint64 => {
let bits = u64::from_le_bytes(eight);
return Numeric::BigInt(crate::bigint::BigInt::from_bits(
bits,
self == Self::BigInt64,
));
}
Self::Float32 => {
f64::from(f32::from_le_bytes([eight[0], eight[1], eight[2], eight[3]]))
}
Self::Float64 => f64::from_le_bytes(eight),
};
Numeric::Number(number)
}
#[must_use]
pub fn write(self, value: f64) -> Option<Vec<u8>> {
Some(match self {
Self::Int8 | Self::Uint8 => vec![wrap(value, 8) as u8],
Self::Int16 | Self::Uint16 => (wrap(value, 16) as u16).to_le_bytes().to_vec(),
Self::Int32 | Self::Uint32 => (wrap(value, 32) as u32).to_le_bytes().to_vec(),
Self::Float32 => (value as f32).to_le_bytes().to_vec(),
Self::Float64 => value.to_le_bytes().to_vec(),
Self::BigInt64 | Self::BigUint64 => return None,
})
}
#[must_use]
pub fn write_big(self, value: &crate::bigint::BigInt) -> Option<Vec<u8>> {
match self.holds_big() {
true => Some(value.low_u64().to_le_bytes().to_vec()),
false => None,
}
}
#[must_use]
pub fn write_numeric(self, value: &Numeric, clamped: bool) -> Option<Vec<u8>> {
match value {
Numeric::Number(number) => self.write(clamp_if(*number, clamped)),
Numeric::BigInt(big) => self.write_big(big),
}
}
}
fn wrap(value: f64, bits: u32) -> u64 {
let truncated = value.trunc();
let modulus = 2_f64.powi(bits as i32);
let wrapped = truncated.rem_euclid(modulus);
wrapped as u64
}
#[must_use]
pub fn clamp_if(value: f64, clamped: bool) -> f64 {
if !clamped {
return value;
}
let bounded = value.clamp(0.0, 255.0);
let floor = bounded.floor();
match bounded - floor {
half if half > 0.5 => floor + 1.0,
half if half < 0.5 => floor,
_ if floor % 2.0 == 0.0 => floor,
_ => floor + 1.0,
}
}
#[derive(Debug, Clone, Copy)]
pub struct View {
pub buffer: crate::heap::ObjectId,
pub offset: usize,
pub length: usize,
pub element: Option<Element>,
pub tracking: bool,
}
impl View {
#[must_use]
pub fn count(&self) -> usize {
self.element
.map_or(0, |element| self.length / element.width())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bigint::BigInt;
const WIDTHS: [(Element, usize); 10] = [
(Element::Int8, 1),
(Element::Uint8, 1),
(Element::Int16, 2),
(Element::Uint16, 2),
(Element::Int32, 4),
(Element::Uint32, 4),
(Element::BigInt64, 8),
(Element::BigUint64, 8),
(Element::Float32, 4),
(Element::Float64, 8),
];
#[test]
fn a_kind_writes_only_the_numeric_type_it_holds() {
for (element, width) in WIDTHS {
let number = element.write(1.0);
let big = element.write_big(&BigInt::from_u64(1));
match element.holds_big() {
true => {
assert_eq!(number, None, "{} took a Number", element.name());
assert_eq!(
big.map(|bytes| bytes.len()),
Some(width),
"{} refused a BigInt",
element.name()
);
}
false => {
assert_eq!(big, None, "{} took a BigInt", element.name());
assert_eq!(
number.map(|bytes| bytes.len()),
Some(width),
"{} refused a Number",
element.name()
);
}
}
}
}
#[test]
fn write_numeric_picks_the_half_that_matches_and_has_none_for_the_other() {
let one = Numeric::Number(1.0);
let big_one = Numeric::BigInt(BigInt::from_u64(1));
assert_eq!(
Element::Int8.write_numeric(&one, false),
Some(vec![1]),
"a Number into a Number kind"
);
assert_eq!(
Element::BigInt64.write_numeric(&big_one, false),
Some(vec![1, 0, 0, 0, 0, 0, 0, 0]),
"a BigInt into a BigInt kind"
);
assert_eq!(
Element::BigInt64.write_numeric(&one, false),
None,
"a Number into a BigInt kind"
);
assert_eq!(
Element::Int8.write_numeric(&big_one, false),
None,
"a BigInt into a Number kind"
);
assert_eq!(
Element::Uint8.write_numeric(&Numeric::Number(300.0), true),
Some(vec![255]),
"clamped"
);
assert_eq!(
Element::Uint8.write_numeric(&Numeric::Number(300.0), false),
Some(vec![44]),
"unclamped"
);
}
#[test]
fn the_two_bigint_kinds_are_the_same_eight_bytes_read_two_ways() {
let bytes = Element::BigInt64
.write_big(&BigInt::from_u64(1).negate())
.expect("a BigInt kind takes a BigInt"); assert_eq!(bytes, vec![0xFF; 8]);
assert_eq!(
Element::BigInt64.read(&bytes),
Numeric::BigInt(BigInt::from_u64(1).negate()),
"read as signed"
);
assert_eq!(
Element::BigUint64.read(&bytes),
Numeric::BigInt(BigInt::from_u64(u64::MAX)),
"read as unsigned"
);
assert_eq!(
Element::BigUint64.write_big(&BigInt::from_u64(1).negate()),
Some(bytes),
"the sign is a reader's question"
);
}
#[test]
fn a_kinds_width_is_what_its_bytes_take_and_its_name_is_its_accessors() {
for (element, width) in WIDTHS {
assert_eq!(element.width(), width, "{}", element.name());
let bytes = match element.holds_big() {
true => element.write_big(&BigInt::zero()),
false => element.write(0.0),
};
assert_eq!(
bytes.map(|bytes| bytes.len()),
Some(width),
"{} wrote its width",
element.name()
);
}
assert_eq!(Element::BigInt64.name(), "BigInt64");
assert_eq!(Element::BigUint64.name(), "BigUint64");
}
}