use core::ptr::null_mut;
use core::sync::atomic::{AtomicUsize, Ordering};
use crossbeam_deque::{Injector, Steal};
use j8lockfree::SegVec;
use crate::block::Block;
use crate::header::Header;
pub(crate) struct Copier {
targets: *const Injector<Block>,
blocks: *const SegVec<Block>,
last: u32,
epoch: u32,
block: Option<Block>,
line: usize,
cursor: *mut u8,
limit: *mut u8,
moved: usize,
total: *const AtomicUsize,
}
impl Drop for Copier {
fn drop(&mut self) {
unsafe { &*self.total }.fetch_add(self.moved, Ordering::Relaxed);
}
}
unsafe impl Send for Copier {}
impl Copier {
pub(crate) fn new(targets: &Injector<Block>, blocks: &SegVec<Block>, total: &AtomicUsize, last: u32, epoch: u32) -> Self {
Self { targets, blocks, last, epoch, block: None, line: 0, cursor: null_mut(), limit: null_mut(), moved: 0, total }
}
pub(crate) unsafe fn copy(&mut self, from: *const Header) -> *const Header {
let bytes = unsafe { &*from }.bytes();
let to = self.alloc(bytes);
self.moved += bytes;
unsafe { core::ptr::copy_nonoverlapping(from.cast::<u8>(), to, bytes) };
let block = Block::containing(to);
block.set_start(to);
block.mark_lines(to, bytes, self.epoch);
let to = to.cast::<Header>().cast_const();
unsafe { &*to }.set_mark(self.epoch);
to
}
fn alloc(&mut self, bytes: usize) -> *mut u8 {
loop {
if self.limit.addr() - self.cursor.addr() >= bytes {
let p = self.cursor;
self.cursor = p.wrapping_add(bytes);
return p;
}
self.refill();
}
}
fn refill(&mut self) {
if let Some(b) = self.block
&& let Some((start, end)) = b.hole(self.line, self.last)
{
self.line = end;
self.cursor = b.line(start);
self.limit = b.line(end);
return;
}
let (targets, blocks) = unsafe { (&*self.targets, &*self.blocks) };
let b = loop {
match targets.steal() {
Steal::Success(b) => break b,
Steal::Retry => {}
Steal::Empty => {
let b = Block::new();
blocks.push(b);
break b;
}
}
};
self.block = Some(b);
self.line = Block::FIRST_LINE;
self.cursor = null_mut();
self.limit = null_mut();
}
}