use core::fmt;
use crate::crc::Crc;
use crate::developer::{Extra, KindId};
use crate::messages::{
data_len, kept, record_fields, Activity, DeviceInfo, Event, FieldDef, FieldError, FieldOut,
Fields, FileId, Lap, Mask, Message, Put, Record, RecordFields, Session, RECORD_GLOBAL,
RECORD_TIMESTAMP,
};
use crate::types::Timestamp;
use extra::Extras;
const HEADER_LEN: u8 = 14;
const FRAMING: u32 = HEADER_LEN as u32 + 2;
const LIMIT: u32 = u32::MAX - FRAMING;
const PROTOCOL_VERSION: u8 = 0x20;
pub trait Sink {
type Error;
fn begin(&mut self, _file_size: u32) -> Result<(), Self::Error> {
Ok(())
}
fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
}
impl<S: Sink + ?Sized> Sink for &mut S {
type Error = S::Error;
fn begin(&mut self, file_size: u32) -> Result<(), S::Error> {
(**self).begin(file_size)
}
fn write(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
(**self).write(bytes)
}
}
pub trait PatchSink: Sink {
fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error>;
}
impl<S: PatchSink + ?Sized> PatchSink for &mut S {
fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), S::Error> {
(**self).patch(back, bytes)
}
}
pub struct FnSink<F>(pub F);
impl<F> fmt::Debug for FnSink<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("FnSink").finish_non_exhaustive()
}
}
impl<F: FnMut(&[u8]) -> Result<(), E>, E> Sink for FnSink<F> {
type Error = E;
fn write(&mut self, bytes: &[u8]) -> Result<(), E> {
(self.0)(bytes)
}
}
#[derive(Debug)]
pub struct SliceSink<'a> {
buf: &'a mut [u8],
len: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Full;
impl fmt::Display for Full {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("no room in the slice, or a patch outside what it holds")
}
}
impl core::error::Error for Full {}
impl<'a> SliceSink<'a> {
pub fn new(buf: &'a mut [u8]) -> Self {
Self { buf, len: 0 }
}
#[must_use]
pub fn written(&self) -> &[u8] {
self.buf.get(..self.len).unwrap_or(&[])
}
}
impl Sink for SliceSink<'_> {
type Error = Full;
fn begin(&mut self, file_size: u32) -> Result<(), Full> {
let room = self.buf.len().saturating_sub(self.len);
if usize::try_from(file_size).map_or(true, |n| n > room) {
return Err(Full);
}
Ok(())
}
fn write(&mut self, bytes: &[u8]) -> Result<(), Full> {
let end = self.len.checked_add(bytes.len()).ok_or(Full)?;
let dst = self.buf.get_mut(self.len..end).ok_or(Full)?;
dst.copy_from_slice(bytes);
self.len = end;
Ok(())
}
}
impl PatchSink for SliceSink<'_> {
fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Full> {
let start = usize::try_from(back).ok().and_then(|b| self.len.checked_sub(b)).ok_or(Full)?;
let end = start.checked_add(bytes.len()).filter(|&e| e <= self.len).ok_or(Full)?;
self.buf.get_mut(start..end).ok_or(Full)?.copy_from_slice(bytes);
Ok(())
}
}
#[cfg(feature = "std")]
#[derive(Debug)]
pub struct IoSink<W>(pub W);
#[cfg(feature = "std")]
impl<W: std::io::Write> Sink for IoSink<W> {
type Error = std::io::Error;
fn write(&mut self, bytes: &[u8]) -> std::io::Result<()> {
self.0.write_all(bytes)
}
}
#[cfg(feature = "std")]
impl<W: std::io::Write + std::io::Seek> PatchSink for IoSink<W> {
fn patch(&mut self, back: u32, bytes: &[u8]) -> std::io::Result<()> {
use std::io::{Error, ErrorKind, SeekFrom};
let len = u32::try_from(bytes.len())
.ok()
.filter(|&n| n <= back)
.ok_or_else(|| Error::from(ErrorKind::InvalidInput))?;
let start = self.0.seek(SeekFrom::Current(0i64.saturating_sub(i64::from(back))))?;
self.0.write_all(bytes)?;
if self.0.stream_position()? != start.saturating_add(u64::from(len)) {
return Err(Error::from(ErrorKind::Unsupported));
}
self.0.seek(SeekFrom::Current(i64::from(back.saturating_sub(len))))?;
Ok(())
}
}
#[cfg(feature = "alloc")]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct VecSink(pub alloc::vec::Vec<u8>);
#[cfg(feature = "alloc")]
impl Sink for VecSink {
type Error = core::convert::Infallible;
fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
self.0.extend_from_slice(bytes);
Ok(())
}
}
#[cfg(feature = "alloc")]
impl PatchSink for VecSink {
fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error> {
let len = self.0.len();
let start = usize::try_from(back).ok().and_then(|b| len.checked_sub(b));
let end = start.and_then(|s| s.checked_add(bytes.len())).filter(|&e| e <= len);
if let Some(dst) = start.zip(end).and_then(|(s, e)| self.0.get_mut(s..e)) {
dst.copy_from_slice(bytes);
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
Sink,
SourceChanged,
TooLarge,
StringTooLong,
OutOfRange,
IndexFull,
OutOfOrder,
TimeWentBack,
Paused,
DistanceWentBack,
Unfinished,
GivenByLengths,
Undeclared,
Duplicate,
Reserved,
TooMany,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Sink => "the sink failed",
Self::SourceChanged => "the source wrote different messages on the second pass",
Self::TooLarge => "the file would be 4 GiB or more",
Self::StringTooLong => "string longer than its field",
Self::OutOfRange => "value out of its field's range",
Self::IndexFull => "no message_index left for another lap or session",
Self::OutOfOrder => "the activity is not ready for that call",
Self::TimeWentBack => "a time before one already written",
Self::Paused => "a record, length or set while the timer is paused",
Self::DistanceWentBack => "a total distance less than one already written",
Self::Unfinished => "the activity was not ended",
Self::GivenByLengths => "a distance, speed or cadence that a pool swim's lengths give",
Self::Undeclared => "a developer or field this file did not declare",
Self::Duplicate => "given twice",
Self::Reserved => "a message or field the encoder writes itself",
Self::TooMany => "more developers or fields than the encoder holds",
})
}
}
impl core::error::Error for Error {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WriteError<S, E> {
Sink(S),
Source(E),
}
impl<S, E: fmt::Display> fmt::Display for WriteError<S, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Sink(_) => f.write_str("the sink failed"),
Self::Source(e) => e.fmt(f),
}
}
}
impl<S, E> core::error::Error for WriteError<S, E>
where
S: core::error::Error + 'static,
E: core::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Sink(e) => Some(e),
Self::Source(e) => e.source(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Options {
compressed_timestamps: bool,
profile_version: u16,
utc_offset: Option<i32>,
auto_multisport: bool,
}
impl Options {
#[must_use]
pub const fn new() -> Self {
Self {
compressed_timestamps: false,
profile_version: 2100,
utc_offset: None,
auto_multisport: false,
}
}
#[must_use]
pub const fn auto_multisport(mut self, on: bool) -> Self {
self.auto_multisport = on;
self
}
#[must_use]
pub const fn compressed_timestamps(mut self, on: bool) -> Self {
self.compressed_timestamps = on;
self
}
#[must_use]
pub const fn utc_offset(mut self, seconds: i32) -> Self {
self.utc_offset = Some(seconds);
self
}
#[must_use]
pub const fn profile_version(mut self, version: u16) -> Self {
self.profile_version = version;
self
}
}
impl Default for Options {
fn default() -> Self {
Self::new()
}
}
pub fn size<E, F>(options: Options, mut source: F) -> Result<u32, E>
where
E: From<Error>,
F: FnMut(&mut Writer<'_>) -> Result<(), E>,
{
Ok(plan(options, &mut source, true)?.file_size)
}
pub fn write<S, E, F>(sink: S, options: Options, source: F) -> Result<S, WriteError<S::Error, E>>
where
S: Sink,
E: From<Error>,
F: FnMut(&mut Writer<'_>) -> Result<(), E>,
{
write_with(sink, options, source, true)
}
fn write_with<S, E, F>(
sink: S,
options: Options,
mut source: F,
require_end: bool,
) -> Result<S, WriteError<S::Error, E>>
where
S: Sink,
E: From<Error>,
F: FnMut(&mut Writer<'_>) -> Result<(), E>,
{
let plan = plan(options, &mut source, require_end).map_err(WriteError::Source)?;
let mut out = SinkOut { sink, error: None };
out.sink.begin(plan.file_size).map_err(WriteError::Sink)?;
let header = header(options, plan.data_size);
out.sink.write(&header).map_err(WriteError::Sink)?;
let mut st = State::new(options, Some(plan));
st.require_end = require_end;
let result = source(&mut Writer { out: &mut out, st: &mut st });
let end = Writer { out: &mut out, st: &mut st }.close();
if let Some(e) = out.error.take() {
return Err(WriteError::Sink(e));
}
result.map_err(WriteError::Source)?;
end.map_err(|e| WriteError::Source(E::from(e)))?;
out.sink.write(&file_crc(&header, &st)).map_err(WriteError::Sink)?;
Ok(out.sink)
}
pub struct OnePass<S: PatchSink> {
out: SinkOut<S>,
st: State,
}
impl<S: PatchSink> fmt::Debug for OnePass<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OnePass").field("written", &self.st.written).finish_non_exhaustive()
}
}
impl<S: PatchSink> OnePass<S> {
pub fn new(mut sink: S, options: Options) -> Result<Self, S::Error> {
sink.write(&header(options, 0))?;
Ok(Self { out: SinkOut { sink, error: None }, st: State::new(options, None) })
}
pub fn writer(&mut self) -> Writer<'_> {
Writer { out: &mut self.out, st: &mut self.st }
}
#[allow(clippy::result_large_err, reason = "the error holds the file, to finish again")]
pub fn finish(mut self) -> Result<S, FinishError<Self, S::Error>> {
match self.try_finish() {
Ok(()) => Ok(self.out.sink),
Err(error) => Err(FinishError { error, file: self }),
}
}
pub fn into_sink(self) -> S {
self.out.sink
}
fn try_finish(&mut self) -> Result<(), WriteError<S::Error, Error>> {
let ended = Writer { out: &mut self.out, st: &mut self.st }.close();
if let Some(e) = self.out.error.take() {
return Err(WriteError::Sink(e));
}
ended.map_err(WriteError::Source)?;
let (header, back, crc) = self.st.trailer().map_err(WriteError::Source)?;
let written = self.out.sink.write(&crc).and_then(|()| self.out.sink.patch(back, &header));
written.map_err(|e| {
self.st.failed = true;
WriteError::Sink(e)
})
}
}
pub struct FinishError<F, E> {
error: WriteError<E, Error>,
file: F,
}
impl<F, E> FinishError<F, E> {
pub const fn error(&self) -> &WriteError<E, Error> {
&self.error
}
pub fn into_inner(self) -> F {
self.file
}
pub fn into_parts(self) -> (WriteError<E, Error>, F) {
(self.error, self.file)
}
}
impl<F, E: fmt::Debug> fmt::Debug for FinishError<F, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FinishError").field("error", &self.error).finish_non_exhaustive()
}
}
impl<F, E> fmt::Display for FinishError<F, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.error.fmt(f)
}
}
impl<F, E: core::error::Error + 'static> core::error::Error for FinishError<F, E> {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
self.error.source()
}
}
#[cfg(feature = "alloc")]
pub fn to_vec<E, F>(options: Options, source: F) -> Result<alloc::vec::Vec<u8>, E>
where
E: From<Error>,
F: FnOnce(&mut Writer<'_>) -> Result<(), E>,
{
let Ok(mut file) = OnePass::new(VecSink::default(), options);
source(&mut file.writer())?;
match file.finish().map_err(FinishError::into_parts) {
Ok(VecSink(bytes)) => Ok(bytes),
Err((WriteError::Source(e), _)) => Err(E::from(e)),
Err((WriteError::Sink(never), _)) => match never {},
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Plan {
data_size: u32,
file_size: u32,
data_crc: u16,
}
fn plan<E, F>(options: Options, source: &mut F, require_end: bool) -> Result<Plan, E>
where
E: From<Error>,
F: FnMut(&mut Writer<'_>) -> Result<(), E>,
{
let mut st = State::new(options, None);
st.require_end = require_end;
source(&mut Writer { out: &mut Counter, st: &mut st })?;
Ok(st.plan()?)
}
fn file_crc(header: &[u8], st: &State) -> [u8; 2] {
let mut crc = Crc::new();
crc.update(header);
crc.then(st.data_crc, st.written).value().to_le_bytes()
}
fn header(options: Options, data_size: u32) -> [u8; HEADER_LEN as usize] {
let mut h = [0u8; HEADER_LEN as usize];
let [h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13] = &mut h;
*h0 = HEADER_LEN;
*h1 = PROTOCOL_VERSION;
[*h2, *h3] = options.profile_version.to_le_bytes();
[*h4, *h5, *h6, *h7] = data_size.to_le_bytes();
[*h8, *h9, *h10, *h11] = *b".FIT";
let mut crc = Crc::new();
crc.update(&[*h0, *h1, *h2, *h3, *h4, *h5, *h6, *h7, *h8, *h9, *h10, *h11]);
[*h12, *h13] = crc.value().to_le_bytes();
h
}
trait Out {
fn write(&mut self, bytes: &[u8]) -> bool;
fn fits(&mut self, _size: u32) -> bool {
true
}
}
struct Counter;
impl Out for Counter {
fn write(&mut self, _: &[u8]) -> bool {
true
}
}
struct SinkOut<S: Sink> {
sink: S,
error: Option<S::Error>,
}
impl<S: Sink> Out for SinkOut<S> {
fn write(&mut self, bytes: &[u8]) -> bool {
match self.sink.write(bytes) {
Ok(()) => true,
Err(e) => {
self.error = Some(e);
false
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Layout {
global: u16,
shape: Shape,
raw: extra::RawDefs,
dev: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Shape {
Message { fields: &'static [FieldDef], keep: Mask },
Record { fields: RecordFields, compressed: bool },
}
#[derive(Clone, Debug)]
struct Locals {
held: [Option<(Layout, u32)>; 16],
clock: u32,
}
impl Locals {
const fn new() -> Self {
Self { held: [None; 16], clock: 0 }
}
fn find(&self, layout: Layout) -> (u8, bool) {
let (first, group) = match layout.shape {
Shape::Record { .. } => (0u8, self.held.get(..4)),
Shape::Message { .. } => (4u8, self.held.get(4..)),
};
let group = group.unwrap_or(&[]);
let local = |i: usize| first.saturating_add(u8::try_from(i).unwrap_or(u8::MAX));
if let Some(i) = group.iter().position(|h| h.is_some_and(|(l, _)| l == layout)) {
return (local(i), false);
}
if let Some(i) = group.iter().position(Option::is_none) {
return (local(i), true);
}
let oldest = group
.iter()
.enumerate()
.min_by_key(|(_, h)| h.map_or(0, |(_, used)| used))
.map_or(0, |(i, _)| i);
(local(oldest), true)
}
fn hold(&mut self, local: u8, layout: Layout) {
self.clock = self.clock.wrapping_add(1);
if let Some(h) = self.held.get_mut(usize::from(local)) {
*h = Some((layout, self.clock));
}
}
}
const fn fixed_layout<M: Message>() -> Layout {
let shape = Shape::Message { fields: M::FIELDS, keep: Mask::ALL };
Layout { global: M::GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 }
}
#[derive(Clone, Copy)]
enum Header {
Normal,
Compressed(u8),
}
#[derive(Clone, Copy)]
pub(crate) struct Planned {
layout: Layout,
keep: Mask,
local: u8,
count: u8,
definition: u32,
body: u32,
}
impl Planned {
pub(crate) const fn size(&self) -> u32 {
self.definition.saturating_add(self.body)
}
pub(crate) fn after(&self, before: &Self) -> u32 {
if before.definition > 0 && before.local == self.local && self.definition == 0 {
self.definition_len().saturating_add(self.body)
} else {
self.size()
}
}
fn definition_len(&self) -> u32 {
definition_len(u32::from(self.count), self.layout.dev.count_ones())
}
}
const fn definition_len(fields: u32, dev_fields: u32) -> u32 {
let dev = match dev_fields {
0 => 0,
n => n.saturating_mul(3).saturating_add(1),
};
fields.saturating_mul(3).saturating_add(6).saturating_add(dev)
}
const STAGE: usize = 32;
#[derive(Clone)]
struct State {
options: Options,
plan: Option<Plan>,
stage: [u8; STAGE],
staged: usize,
data_crc: Crc,
written: u32,
locals: Locals,
last_timestamp: Option<Timestamp>,
laps: u16,
sessions: u16,
failed: bool,
act: activity::Act,
require_end: bool,
dev: extra::DevTable,
}
impl State {
fn new(options: Options, plan: Option<Plan>) -> Self {
Self {
options,
plan,
stage: [0; STAGE],
staged: 0,
data_crc: Crc::new(),
written: 0,
locals: Locals::new(),
last_timestamp: None,
laps: 0,
sessions: 0,
failed: false,
act: activity::Act::new(),
require_end: true,
dev: extra::DevTable::new(),
}
}
fn plan(mut self) -> Result<Plan, Error> {
Writer { out: &mut Counter, st: &mut self }.close()?;
let file_size = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
Ok(Plan { data_size: self.written, file_size, data_crc: self.data_crc.value() })
}
fn trailer(&self) -> Result<([u8; HEADER_LEN as usize], u32, [u8; 2]), Error> {
let header = header(self.options, self.written);
let back = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
let crc = file_crc(&header, self);
Ok((header, back, crc))
}
}
pub struct Writer<'a> {
out: &'a mut dyn Out,
st: &'a mut State,
}
impl fmt::Debug for Writer<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Writer").field("written", &self.st.written).finish_non_exhaustive()
}
}
impl Writer<'_> {
pub(crate) fn raw_file_id(&mut self, msg: &FileId) -> Result<(), Error> {
self.fixed(msg, 0)
}
pub(crate) fn raw_device_info(&mut self, msg: &DeviceInfo<'_>) -> Result<(), Error> {
self.fixed(msg, 0)
}
pub(crate) fn raw_event(&mut self, msg: Event) -> Result<(), Error> {
self.fixed(&msg, 0)
}
#[cfg(test)]
pub(crate) fn raw_record(&mut self, msg: Record) -> Result<(), Error> {
self.raw_record_with(msg, &[])
}
fn raw_record_with(&mut self, msg: Record, extras: &[Extra<'_>]) -> Result<(), Error> {
let (layout, defs, header, compressed) = self.record_parts(&msg);
let t = msg.timestamp;
self.message(layout, defs, header, Some(t), Extras::Values(extras), |out| {
if !compressed {
out.u32(t.fit());
}
msg.encode(out);
})
}
pub(crate) fn record_cost(&self, msg: &Record, extras: &[Extra<'_>]) -> Result<u32, Error> {
let (layout, defs, _, compressed) = self.record_parts(msg);
let t = msg.timestamp;
let planned =
self.plan(layout, defs, Extras::Values(extras), &|out: &mut dyn FieldOut| {
if !compressed {
out.u32(t.fit());
}
msg.encode(out);
})?;
Ok(planned.size())
}
fn record_parts(
&self,
msg: &Record,
) -> (Layout, impl Iterator<Item = FieldDef> + Clone, Header, bool) {
let t = msg.timestamp;
let compressed = self.st.options.compressed_timestamps
&& self
.st
.last_timestamp
.and_then(|last| t.fit().checked_sub(last.fit()))
.is_some_and(|gap| gap < 32);
let shape = Shape::Record { fields: msg.fields(), compressed };
let layout = Layout { global: RECORD_GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 };
let defs = core::iter::once(RECORD_TIMESTAMP)
.filter(move |_| !compressed)
.chain(record_fields(msg.fields()));
let header = if compressed {
#[allow(clippy::cast_possible_truncation)]
Header::Compressed((t.fit() & 0x1F) as u8)
} else {
Header::Normal
};
(layout, defs, header, compressed)
}
pub(crate) fn raw_lap(&mut self, msg: &Lap) -> Result<(), Error> {
self.fixed_with(msg, next_index(self.st.laps)?, Extras::Staged(KindId::Lap))?;
self.st.laps = self.st.laps.wrapping_add(1);
self.st.dev.unstage(KindId::Lap);
Ok(())
}
pub(crate) fn raw_session(&mut self, msg: &Session) -> Result<(), Error> {
self.fixed_with(msg, next_index(self.st.sessions)?, Extras::Staged(KindId::Session))?;
self.st.sessions = self.st.sessions.wrapping_add(1);
self.st.dev.unstage(KindId::Session);
Ok(())
}
pub(crate) fn raw_activity(&mut self, msg: &Activity) -> Result<(), Error> {
self.fixed(msg, 0)
}
fn fixed<M: Message>(&mut self, msg: &M, index: u16) -> Result<(), Error> {
self.fixed_with(msg, index, Extras::Values(&[]))
}
fn fixed_with<M: Message>(
&mut self,
msg: &M,
index: u16,
extras: Extras<'_>,
) -> Result<(), Error> {
let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
self.message(layout, defs, Header::Normal, msg.timestamp(), extras, |out| {
msg.encode(out, index);
})
}
pub(crate) fn cost<M: Message>(&self, msg: &M) -> Result<Planned, Error> {
self.cost_with(msg, Extras::Values(&[]))
}
fn cost_with<M: Message>(&self, msg: &M, extras: Extras<'_>) -> Result<Planned, Error> {
let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
self.plan(layout, defs, extras, &|out: &mut dyn FieldOut| msg.encode(out, 0))
}
fn plan<I>(
&self,
mut layout: Layout,
table: I,
extras: Extras<'_>,
encode: &dyn Fn(&mut dyn FieldOut),
) -> Result<Planned, Error>
where
I: Iterator<Item = FieldDef> + Clone,
{
let mut check = Fields::new(table.clone(), None);
encode(&mut check);
refusal(check.refused())?;
let keep = check.present();
if let Shape::Message { keep: k, .. } = &mut layout.shape {
*k = keep;
}
let defs = kept(table, keep);
layout.raw = extra::raw_defs(extras)?;
layout.dev = self.dev_fields(extras)?;
let (local, define) = self.st.locals.find(layout);
let count = defs.clone().count().saturating_add(layout.raw.defs().count());
let count = u8::try_from(count).map_err(|_| Error::TooLarge)?;
let planned = Planned { layout, keep, local, count, definition: 0, body: 0 };
let definition = if define { planned.definition_len() } else { 0 };
let body = data_len(defs)
.saturating_add(data_len(layout.raw.defs()))
.saturating_add(self.st.dev.size(layout.dev))
.saturating_add(1);
Ok(Planned { definition, body, ..planned })
}
fn message<I>(
&mut self,
layout: Layout,
table: I,
header: Header,
timestamp: Option<Timestamp>,
extras: Extras<'_>,
encode: impl Fn(&mut dyn FieldOut),
) -> Result<(), Error>
where
I: Iterator<Item = FieldDef> + Clone,
{
if self.st.failed {
return Err(Error::Sink);
}
let planned = self.plan(layout, table.clone(), extras, &encode)?;
self.reserve(planned.size())?;
let Planned { layout, keep, local, count, definition, .. } = planned;
self.st.locals.hold(local, layout);
if definition > 0 {
let [g0, g1] = layout.global.to_le_bytes();
let flag = if layout.dev == 0 { 0 } else { 0x20 };
self.put(&[0x40 | flag | local, 0, 0, g0, g1, count]);
for f in kept(table.clone(), keep).chain(layout.raw.defs()) {
self.put(&[f.num, f.size, f.base]);
}
if layout.dev != 0 {
self.put_dev_definitions(layout.dev);
}
}
match header {
Header::Normal => self.put(&[local]),
Header::Compressed(low) => self.put(&[0x80 | local << 5 | low]),
}
let mut fields = Fields::new(table, Some(self)).keep(keep);
encode(&mut fields);
fields.finish();
self.put_raw_fields(extras);
self.put_dev_fields(extras, layout.dev);
self.flush();
if self.st.failed {
return Err(Error::Sink);
}
if let Some(t) = timestamp {
self.st.last_timestamp = Some(t);
}
Ok(())
}
fn reserve(&mut self, size: u32) -> Result<(), Error> {
let end = self.room(size)?;
if self.st.plan.is_some_and(|plan| end > plan.data_size) {
return Err(Error::SourceChanged);
}
self.st.written = end;
Ok(())
}
fn room(&mut self, size: u32) -> Result<u32, Error> {
let end = self.st.written.checked_add(size).ok_or(Error::TooLarge)?;
match end.checked_add(self.st.act.kept_for_end()) {
Some(n) if n <= LIMIT => {
self.ahead(size)?;
Ok(end)
}
_ => Err(Error::TooLarge),
}
}
fn ahead(&mut self, size: u32) -> Result<(), Error> {
if self.out.fits(size) {
Ok(())
} else {
Err(Error::Sink)
}
}
fn flush(&mut self) {
if let Some(bytes) = self.st.stage.get(..self.st.staged) {
if !self.st.failed && !bytes.is_empty() && !self.out.write(bytes) {
self.st.failed = true;
}
}
self.st.staged = 0;
}
fn close(&mut self) -> Result<(), Error> {
self.flush();
if self.st.failed {
return Err(Error::Sink);
}
if self.st.require_end && !self.st.act.ended() {
return Err(Error::Unfinished);
}
match self.st.plan {
Some(plan)
if plan.data_size != self.st.written
|| plan.data_crc != self.st.data_crc.value() =>
{
Err(Error::SourceChanged)
}
_ => Ok(()),
}
}
}
impl Put for Writer<'_> {
fn put(&mut self, bytes: &[u8]) {
self.st.data_crc.update(bytes);
for &byte in bytes {
if let Some(slot) = self.st.stage.get_mut(self.st.staged) {
*slot = byte;
self.st.staged = self.st.staged.saturating_add(1);
}
if self.st.staged == STAGE {
self.flush();
}
}
}
}
fn check<M: Message>(msg: &M) -> Result<(), Error> {
let mut fields = Fields::new(M::FIELDS.iter().copied(), None);
msg.encode(&mut fields, 0);
refusal(fields.refused())
}
fn refusal(refused: Option<FieldError>) -> Result<(), Error> {
match refused {
Some(FieldError::StringTooLong) => Err(Error::StringTooLong),
Some(FieldError::OutOfRange) => Err(Error::OutOfRange),
None => Ok(()),
}
}
fn next_index(count: u16) -> Result<u16, Error> {
if count >= 0x0FFF {
Err(Error::IndexFull)
} else {
Ok(count)
}
}
mod activity;
#[cfg(feature = "async")]
mod asynch;
#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
mod embedded_io;
mod extra;
#[cfg(test)]
mod tests;
#[cfg(feature = "async")]
pub use asynch::{
write_async, AsyncOnePass, AsyncPatchSink, AsyncSink, AsyncWriter, ASYNC_WRITE_LEN,
};
#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
pub use embedded_io::{EmbeddedIo, EmbeddedIoError};