use core::fmt;
use super::{
header, Counter, Error, FinishError, Options, Out, State, WriteError, Writer, HEADER_LEN,
};
use crate::developer::{Dev, DevField, DevType, Developer, Extra, FieldDescription, Kind, Summary};
use crate::messages::{Device, LapTrigger, Leg, Length, Pool, Record, Set};
use crate::raw::RawField;
use crate::types::{Sport, SubSport, Timestamp};
pub const ASYNC_WRITE_LEN: usize = 256;
#[allow(async_fn_in_trait, reason = "a Send bound would shut out single-threaded executors")]
pub trait AsyncSink {
type Error;
async fn begin(&mut self, _file_size: u32) -> Result<(), Self::Error> {
Ok(())
}
async fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
}
impl<S: AsyncSink + ?Sized> AsyncSink for &mut S {
type Error = S::Error;
async fn begin(&mut self, file_size: u32) -> Result<(), S::Error> {
(**self).begin(file_size).await
}
async fn write(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
(**self).write(bytes).await
}
}
#[allow(async_fn_in_trait, reason = "a Send bound would shut out single-threaded executors")]
pub trait AsyncPatchSink: AsyncSink {
async fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error>;
}
impl<S: AsyncPatchSink + ?Sized> AsyncPatchSink for &mut S {
async fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), S::Error> {
(**self).patch(back, bytes).await
}
}
const BEATS_AT_ONCE: usize = 100;
struct Staged<S: AsyncSink> {
sink: S,
stage: [u8; ASYNC_WRITE_LEN],
len: usize,
cap: usize,
error: Option<S::Error>,
torn: bool,
#[cfg(test)]
longest_spill: usize,
}
impl<S: AsyncSink> Staged<S> {
fn new(sink: S, header: &[u8; HEADER_LEN as usize]) -> Self {
let mut stage = [0; ASYNC_WRITE_LEN];
let mut window = Window::new(&mut stage, None);
window.write(header);
Self {
sink,
stage,
len: header.len(),
cap: ASYNC_WRITE_LEN,
error: None,
torn: false,
#[cfg(test)]
longest_spill: 0,
}
}
async fn drain(&mut self) -> Result<(), S::Error> {
let len = core::mem::take(&mut self.len);
self.torn = true;
let written = match self.stage.get(..len) {
Some(bytes) if !bytes.is_empty() => self.sink.write(bytes).await,
_ => Ok(()),
};
self.torn = false;
written
}
async fn put(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
let room = self.stage.get_mut(self.len..self.cap).unwrap_or_default();
let (now, later) = bytes.split_at(room.len().min(bytes.len()));
room.get_mut(..now.len()).unwrap_or_default().copy_from_slice(now);
self.len = self.len.saturating_add(now.len());
self.drain_full().await?;
for chunk in later.chunks(self.cap.max(1)) {
self.stage.get_mut(..chunk.len()).unwrap_or_default().copy_from_slice(chunk);
self.len = chunk.len();
self.drain_full().await?;
}
Ok(())
}
async fn call<R>(
&mut self,
st: &mut State,
call: impl Fn(&mut Writer<'_>) -> R,
) -> Result<R, S::Error> {
let room = self.stage.get_mut(self.len..self.cap).unwrap_or_default();
let mut window = Window::new(room, None);
let result = call(&mut Writer { out: &mut window, st });
if !window.refused {
self.len = self.len.saturating_add(window.kept);
self.drain_full().await?;
return Ok(result);
}
let (mut result, seen, mut done) = self.spill(st, &call, 0);
let rounds = seen.saturating_sub(done).div_ceil(self.cap.max(1));
for _ in 0..rounds {
self.drain().await?;
let (again, _, kept) = self.spill(st, &call, done);
(result, done) = (again, done.saturating_add(kept));
}
self.drain_full().await?;
Ok(result)
}
fn spill<R>(
&mut self,
st: &mut State,
call: &impl Fn(&mut Writer<'_>) -> R,
skip: usize,
) -> (R, usize, usize) {
let room = self.stage.get_mut(self.len..self.cap).unwrap_or_default();
let mut window = Window::new(room, Some(skip));
let mut copy = st.clone();
let result = call(&mut Writer { out: &mut window, st: &mut copy });
#[cfg(test)]
{
self.longest_spill = self.longest_spill.max(window.seen);
}
if skip.saturating_add(window.kept) >= window.seen {
*st = copy;
}
self.len = self.len.saturating_add(window.kept);
(result, window.seen, window.kept)
}
async fn drain_full(&mut self) -> Result<(), S::Error> {
if self.len >= self.cap {
self.drain().await?;
}
Ok(())
}
}
struct Window<'a> {
room: &'a mut [u8],
skip: Option<usize>,
seen: usize,
kept: usize,
refused: bool,
}
impl<'a> Window<'a> {
fn new(room: &'a mut [u8], skip: Option<usize>) -> Self {
Self { room, skip, seen: 0, kept: 0, refused: false }
}
}
impl Out for Window<'_> {
fn write(&mut self, bytes: &[u8]) -> bool {
let from = self.skip.unwrap_or(0).saturating_sub(self.seen);
let src = bytes.get(from..).unwrap_or_default();
let dst = self.room.get_mut(self.kept..).unwrap_or_default();
let n = src.len().min(dst.len());
if let Some((dst, src)) = dst.get_mut(..n).zip(src.get(..n)) {
dst.copy_from_slice(src);
}
self.kept = self.kept.saturating_add(n);
self.seen = self.seen.saturating_add(bytes.len());
true
}
fn fits(&mut self, size: u32) -> bool {
let fits = usize::try_from(size)
.is_ok_and(|size| self.seen.saturating_add(size) <= self.room.len());
self.refused |= self.skip.is_none() && !fits;
!self.refused
}
}
pub struct AsyncWriter<'a, S: AsyncSink> {
st: &'a mut State,
staged: Option<&'a mut Staged<S>>,
}
impl<S: AsyncSink> fmt::Debug for AsyncWriter<'_, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AsyncWriter").field("written", &self.st.written).finish_non_exhaustive()
}
}
macro_rules! calls {
(@ok) => { () };
(@ok $ok:ty) => { $ok };
($(
$name:ident $([$($generics:tt)*])? ($($arg:ident: $ty:ty),*) $(-> $ok:ty)?;
)*) => {$(
#[doc = concat!("[`Writer::", stringify!($name), "`], awaiting the sink.")]
#[doc = concat!("As [`Writer::", stringify!($name), "`].")]
pub async fn $name $(<$($generics)*>)? (
&mut self,
$($arg: $ty),*
) -> Result<calls!(@ok $($ok)?), Error> {
self.call(|w| w.$name($($arg),*)).await
}
)*};
}
impl<S: AsyncSink> AsyncWriter<'_, S> {
calls! {
start(t: Timestamp, creator: &Device<'_>);
device(device: &Device<'_>);
session(t: Timestamp, sport: Sport, sub_sport: SubSport);
pool_swim(t: Timestamp, pool: Pool);
leg(t: Timestamp, leg: &Leg<'_>);
record(record: &Record);
record_with(record: &Record, extras: &[Extra<'_>]);
lap(t: Timestamp);
lap_by(t: Timestamp, trigger: LapTrigger);
pause(t: Timestamp);
resume(t: Timestamp);
length(t: Timestamp, length: &Length);
set(t: Timestamp, set: &Set);
rest(t: Timestamp);
end_rest(t: Timestamp);
developer(developer: &Developer) -> Dev;
declare[T: DevType + ?Sized, K: Kind](
description: &FieldDescription<'_, T, K>
) -> DevField<T, K>;
developer_value[T: DevType + ?Sized, K: Summary](
field: &DevField<T, K>,
value: T::Value<'_>
);
raw_message(global: u16, fields: &[RawField<'_>]);
end(t: Timestamp);
}
pub async fn beat_intervals_ms(&mut self, intervals: &[u16]) -> Result<(), Error> {
self.beats(intervals, true).await
}
pub async fn beat_intervals_1024ths(&mut self, intervals: &[u16]) -> Result<(), Error> {
self.beats(intervals, false).await
}
async fn beats(&mut self, intervals: &[u16], ms: bool) -> Result<(), Error> {
self.call(|w| w.beats_fit(intervals, ms)).await?;
for part in intervals.chunks(BEATS_AT_ONCE) {
self.call(
|w| {
if ms {
w.beat_intervals_ms(part)
} else {
w.beat_intervals_1024ths(part)
}
},
)
.await?;
}
Ok(())
}
async fn call<R>(
&mut self,
f: impl Fn(&mut Writer<'_>) -> Result<R, Error>,
) -> Result<R, Error> {
let Some(staged) = self.staged.as_deref_mut() else {
return f(&mut Writer { out: &mut Counter, st: self.st });
};
if staged.torn {
return Err(Error::Sink);
}
match staged.call(self.st, f).await {
Ok(result) => result,
Err(e) => {
staged.error = Some(e);
self.st.failed = true;
Err(Error::Sink)
}
}
}
}
pub async fn write_async<S, E, F>(
sink: S,
options: Options,
mut source: F,
) -> Result<S, WriteError<S::Error, E>>
where
S: AsyncSink,
E: From<Error>,
F: AsyncFnMut(&mut AsyncWriter<'_, S>) -> Result<(), E>,
{
let mut st = State::new(options, None);
source(&mut AsyncWriter { st: &mut st, staged: None }).await.map_err(WriteError::Source)?;
let plan = st.plan().map_err(|e| WriteError::Source(E::from(e)))?;
let mut sink = sink;
sink.begin(plan.file_size).await.map_err(WriteError::Sink)?;
let header = header(options, plan.data_size);
let mut staged = Staged::new(sink, &header);
let mut st = State::new(options, Some(plan));
let mut w = AsyncWriter { st: &mut st, staged: Some(&mut staged) };
let result = source(&mut w).await;
#[allow(clippy::redundant_closure_for_method_calls, reason = "the path is not higher-ranked")]
let end = w.call(|w| w.close()).await;
if let Some(e) = staged.error.take() {
return Err(WriteError::Sink(e));
}
result.map_err(WriteError::Source)?;
end.map_err(|e| WriteError::Source(E::from(e)))?;
let crc = super::file_crc(&header, &st);
staged.put(&crc).await.map_err(WriteError::Sink)?;
staged.drain().await.map_err(WriteError::Sink)?;
Ok(staged.sink)
}
pub struct AsyncOnePass<S: AsyncPatchSink> {
staged: Staged<S>,
st: State,
}
impl<S: AsyncPatchSink> fmt::Debug for AsyncOnePass<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AsyncOnePass").field("written", &self.st.written).finish_non_exhaustive()
}
}
impl<S: AsyncPatchSink> AsyncOnePass<S> {
pub fn new(sink: S, options: Options) -> Self {
Self { staged: Staged::new(sink, &header(options, 0)), st: State::new(options, None) }
}
pub fn writer(&mut self) -> AsyncWriter<'_, S> {
AsyncWriter { st: &mut self.st, staged: Some(&mut self.staged) }
}
#[allow(clippy::result_large_err, reason = "the error holds the file, to finish again")]
pub async fn finish(mut self) -> Result<S, FinishError<Self, S::Error>> {
match self.try_finish().await {
Ok(()) => Ok(self.staged.sink),
Err(error) => Err(FinishError { error, file: self }),
}
}
pub fn into_sink(self) -> S {
self.staged.sink
}
async fn try_finish(&mut self) -> Result<(), WriteError<S::Error, Error>> {
#[allow(
clippy::redundant_closure_for_method_calls,
reason = "the path is not higher-ranked"
)]
let ended = self.writer().call(|w| w.close()).await;
if let Some(e) = self.staged.error.take() {
return Err(WriteError::Sink(e));
}
ended.map_err(WriteError::Source)?;
let (header, back, crc) = self.st.trailer().map_err(WriteError::Source)?;
let staged = &mut self.staged;
let written = match staged.put(&crc).await {
Ok(()) => match staged.drain().await {
Ok(()) => staged.sink.patch(back, &header).await,
Err(e) => Err(e),
},
Err(e) => Err(e),
};
written.map_err(|e| {
self.st.failed = true;
WriteError::Sink(e)
})
}
}
#[cfg(test)]
mod tests;