1use core::fmt;
2
3use crate::crc::Crc;
4use crate::developer::{Extra, KindId};
5use crate::messages::{
6 data_len, kept, record_fields, Activity, DeviceInfo, Event, FieldDef, FieldError, FieldOut,
7 Fields, FileId, Lap, Mask, Message, Put, Record, RecordFields, Session, RECORD_GLOBAL,
8 RECORD_TIMESTAMP,
9};
10use crate::types::Timestamp;
11use extra::Extras;
12
13const HEADER_LEN: u8 = 14;
14const FRAMING: u32 = HEADER_LEN as u32 + 2;
16const LIMIT: u32 = u32::MAX - FRAMING;
18const PROTOCOL_VERSION: u8 = 0x20;
19
20pub trait Sink {
23 type Error;
25
26 fn begin(&mut self, _file_size: u32) -> Result<(), Self::Error> {
34 Ok(())
35 }
36
37 fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
43}
44
45impl<S: Sink + ?Sized> Sink for &mut S {
46 type Error = S::Error;
47
48 fn begin(&mut self, file_size: u32) -> Result<(), S::Error> {
49 (**self).begin(file_size)
50 }
51
52 fn write(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
53 (**self).write(bytes)
54 }
55}
56
57pub trait PatchSink: Sink {
59 fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error>;
67}
68
69impl<S: PatchSink + ?Sized> PatchSink for &mut S {
70 fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), S::Error> {
71 (**self).patch(back, bytes)
72 }
73}
74
75pub struct FnSink<F>(pub F);
90
91impl<F> fmt::Debug for FnSink<F> {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.debug_tuple("FnSink").finish_non_exhaustive()
94 }
95}
96
97impl<F: FnMut(&[u8]) -> Result<(), E>, E> Sink for FnSink<F> {
98 type Error = E;
99
100 fn write(&mut self, bytes: &[u8]) -> Result<(), E> {
101 (self.0)(bytes)
102 }
103}
104
105#[derive(Debug)]
107pub struct SliceSink<'a> {
108 buf: &'a mut [u8],
109 len: usize,
110}
111
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub struct Full;
115
116impl fmt::Display for Full {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.write_str("no room in the slice, or a patch outside what it holds")
119 }
120}
121
122impl core::error::Error for Full {}
123
124impl<'a> SliceSink<'a> {
125 pub fn new(buf: &'a mut [u8]) -> Self {
127 Self { buf, len: 0 }
128 }
129
130 #[must_use]
132 pub fn written(&self) -> &[u8] {
133 self.buf.get(..self.len).unwrap_or(&[])
134 }
135}
136
137impl Sink for SliceSink<'_> {
138 type Error = Full;
139
140 fn begin(&mut self, file_size: u32) -> Result<(), Full> {
141 let room = self.buf.len().saturating_sub(self.len);
142 if usize::try_from(file_size).map_or(true, |n| n > room) {
143 return Err(Full);
144 }
145 Ok(())
146 }
147
148 fn write(&mut self, bytes: &[u8]) -> Result<(), Full> {
149 let end = self.len.checked_add(bytes.len()).ok_or(Full)?;
150 let dst = self.buf.get_mut(self.len..end).ok_or(Full)?;
151 dst.copy_from_slice(bytes);
152 self.len = end;
153 Ok(())
154 }
155}
156
157impl PatchSink for SliceSink<'_> {
158 fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Full> {
159 let start = usize::try_from(back).ok().and_then(|b| self.len.checked_sub(b)).ok_or(Full)?;
160 let end = start.checked_add(bytes.len()).filter(|&e| e <= self.len).ok_or(Full)?;
161 self.buf.get_mut(start..end).ok_or(Full)?.copy_from_slice(bytes);
162 Ok(())
163 }
164}
165
166#[cfg(feature = "std")]
168#[derive(Debug)]
169pub struct IoSink<W>(pub W);
170
171#[cfg(feature = "std")]
172impl<W: std::io::Write> Sink for IoSink<W> {
173 type Error = std::io::Error;
174
175 fn write(&mut self, bytes: &[u8]) -> std::io::Result<()> {
176 self.0.write_all(bytes)
177 }
178}
179
180#[cfg(feature = "std")]
181impl<W: std::io::Write + std::io::Seek> PatchSink for IoSink<W> {
182 fn patch(&mut self, back: u32, bytes: &[u8]) -> std::io::Result<()> {
183 use std::io::{Error, ErrorKind, SeekFrom};
184 let len = u32::try_from(bytes.len())
185 .ok()
186 .filter(|&n| n <= back)
187 .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?;
188 let start = self.0.seek(SeekFrom::Current(0i64.saturating_sub(i64::from(back))))?;
189 self.0.write_all(bytes)?;
190 if self.0.stream_position()? != start.saturating_add(u64::from(len)) {
192 return Err(Error::from(ErrorKind::Unsupported));
193 }
194 self.0.seek(SeekFrom::Current(i64::from(back.saturating_sub(len))))?;
195 Ok(())
196 }
197}
198
199#[cfg(feature = "alloc")]
216#[derive(Clone, Debug, Default, PartialEq, Eq)]
217pub struct VecSink(pub alloc::vec::Vec<u8>);
218
219#[cfg(feature = "alloc")]
220impl Sink for VecSink {
221 type Error = core::convert::Infallible;
222
223 fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
224 self.0.extend_from_slice(bytes);
225 Ok(())
226 }
227}
228
229#[cfg(feature = "alloc")]
230impl PatchSink for VecSink {
231 fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error> {
232 let len = self.0.len();
233 let start = usize::try_from(back).ok().and_then(|b| len.checked_sub(b));
234 let end = start.and_then(|s| s.checked_add(bytes.len())).filter(|&e| e <= len);
235 if let Some(dst) = start.zip(end).and_then(|(s, e)| self.0.get_mut(s..e)) {
236 dst.copy_from_slice(bytes);
237 }
238 Ok(())
239 }
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244#[non_exhaustive]
245pub enum Error {
246 Sink,
248 SourceChanged,
251 TooLarge,
254 StringTooLong,
256 OutOfRange,
260 IndexFull,
263 OutOfOrder,
270 TimeWentBack,
272 Paused,
274 DistanceWentBack,
276 Unfinished,
278 GivenByLengths,
281 Undeclared,
284 Duplicate,
286 Reserved,
289 TooMany,
292}
293
294impl fmt::Display for Error {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 f.write_str(match self {
297 Self::Sink => "the sink failed",
298 Self::SourceChanged => "the source wrote different messages on the second pass",
299 Self::TooLarge => "the file would be 4 GiB or more",
300 Self::StringTooLong => "string longer than its field",
301 Self::OutOfRange => "value out of its field's range",
302 Self::IndexFull => "no message_index left for another lap or session",
303 Self::OutOfOrder => "the activity is not ready for that call",
304 Self::TimeWentBack => "a time before one already written",
305 Self::Paused => "a record, length or set while the timer is paused",
306 Self::DistanceWentBack => "a total distance less than one already written",
307 Self::Unfinished => "the activity was not ended",
308 Self::GivenByLengths => "a distance, speed or cadence that a pool swim's lengths give",
309 Self::Undeclared => "a developer or field this file did not declare",
310 Self::Duplicate => "given twice",
311 Self::Reserved => "a message or field the encoder writes itself",
312 Self::TooMany => "more developers or fields than the encoder holds",
313 })
314 }
315}
316
317impl core::error::Error for Error {}
318
319#[derive(Clone, Copy, Debug, PartialEq, Eq)]
325pub enum WriteError<S, E> {
326 Sink(S),
328 Source(E),
330}
331
332impl<S, E: fmt::Display> fmt::Display for WriteError<S, E> {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 match self {
335 Self::Sink(_) => f.write_str("the sink failed"),
336 Self::Source(e) => e.fmt(f),
337 }
338 }
339}
340
341impl<S, E> core::error::Error for WriteError<S, E>
342where
343 S: core::error::Error + 'static,
344 E: core::error::Error + 'static,
345{
346 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
347 match self {
348 Self::Sink(e) => Some(e),
349 Self::Source(e) => e.source(),
350 }
351 }
352}
353
354#[derive(Clone, Copy, Debug, PartialEq, Eq)]
356pub struct Options {
357 compressed_timestamps: bool,
358 profile_version: u16,
359 utc_offset: Option<i32>,
360 auto_multisport: bool,
361}
362
363impl Options {
364 #[must_use]
366 pub const fn new() -> Self {
367 Self {
368 compressed_timestamps: false,
369 profile_version: 2100,
370 utc_offset: None,
371 auto_multisport: false,
372 }
373 }
374
375 #[must_use]
379 pub const fn auto_multisport(mut self, on: bool) -> Self {
380 self.auto_multisport = on;
381 self
382 }
383
384 #[must_use]
388 pub const fn compressed_timestamps(mut self, on: bool) -> Self {
389 self.compressed_timestamps = on;
390 self
391 }
392
393 #[must_use]
396 pub const fn utc_offset(mut self, seconds: i32) -> Self {
397 self.utc_offset = Some(seconds);
398 self
399 }
400
401 #[must_use]
403 pub const fn profile_version(mut self, version: u16) -> Self {
404 self.profile_version = version;
405 self
406 }
407}
408
409impl Default for Options {
410 fn default() -> Self {
411 Self::new()
412 }
413}
414
415pub fn size<E, F>(options: Options, mut source: F) -> Result<u32, E>
421where
422 E: From<Error>,
423 F: FnMut(&mut Writer<'_>) -> Result<(), E>,
424{
425 Ok(plan(options, &mut source, true)?.file_size)
426}
427
428pub fn write<S, E, F>(sink: S, options: Options, source: F) -> Result<S, WriteError<S::Error, E>>
457where
458 S: Sink,
459 E: From<Error>,
460 F: FnMut(&mut Writer<'_>) -> Result<(), E>,
461{
462 write_with(sink, options, source, true)
463}
464
465fn write_with<S, E, F>(
467 sink: S,
468 options: Options,
469 mut source: F,
470 require_end: bool,
471) -> Result<S, WriteError<S::Error, E>>
472where
473 S: Sink,
474 E: From<Error>,
475 F: FnMut(&mut Writer<'_>) -> Result<(), E>,
476{
477 let plan = plan(options, &mut source, require_end).map_err(WriteError::Source)?;
478 let mut out = SinkOut { sink, error: None };
479 out.sink.begin(plan.file_size).map_err(WriteError::Sink)?;
480 let header = header(options, plan.data_size);
481 out.sink.write(&header).map_err(WriteError::Sink)?;
482
483 let mut st = State::new(options, Some(plan));
484 st.require_end = require_end;
485 let result = source(&mut Writer { out: &mut out, st: &mut st });
486 let end = Writer { out: &mut out, st: &mut st }.close();
487 if let Some(e) = out.error.take() {
488 return Err(WriteError::Sink(e));
489 }
490 result.map_err(WriteError::Source)?;
491 end.map_err(|e| WriteError::Source(E::from(e)))?;
492 out.sink.write(&file_crc(&header, &st)).map_err(WriteError::Sink)?;
493 Ok(out.sink)
494}
495
496pub struct OnePass<S: PatchSink> {
517 out: SinkOut<S>,
518 st: State,
519}
520
521impl<S: PatchSink> fmt::Debug for OnePass<S> {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 f.debug_struct("OnePass").field("written", &self.st.written).finish_non_exhaustive()
524 }
525}
526
527impl<S: PatchSink> OnePass<S> {
528 pub fn new(mut sink: S, options: Options) -> Result<Self, S::Error> {
534 sink.write(&header(options, 0))?;
535 Ok(Self { out: SinkOut { sink, error: None }, st: State::new(options, None) })
536 }
537
538 pub fn writer(&mut self) -> Writer<'_> {
540 Writer { out: &mut self.out, st: &mut self.st }
541 }
542
543 #[allow(clippy::result_large_err, reason = "the error holds the file, to finish again")]
552 pub fn finish(mut self) -> Result<S, FinishError<Self, S::Error>> {
553 match self.try_finish() {
554 Ok(()) => Ok(self.out.sink),
555 Err(error) => Err(FinishError { error, file: self }),
556 }
557 }
558
559 pub fn into_sink(self) -> S {
562 self.out.sink
563 }
564
565 fn try_finish(&mut self) -> Result<(), WriteError<S::Error, Error>> {
566 let ended = Writer { out: &mut self.out, st: &mut self.st }.close();
567 if let Some(e) = self.out.error.take() {
568 return Err(WriteError::Sink(e));
569 }
570 ended.map_err(WriteError::Source)?;
571 let (header, back, crc) = self.st.trailer().map_err(WriteError::Source)?;
572 let written = self.out.sink.write(&crc).and_then(|()| self.out.sink.patch(back, &header));
574 written.map_err(|e| {
575 self.st.failed = true;
576 WriteError::Sink(e)
577 })
578 }
579}
580
581pub struct FinishError<F, E> {
584 error: WriteError<E, Error>,
585 file: F,
586}
587
588impl<F, E> FinishError<F, E> {
589 pub const fn error(&self) -> &WriteError<E, Error> {
591 &self.error
592 }
593
594 pub fn into_inner(self) -> F {
596 self.file
597 }
598
599 pub fn into_parts(self) -> (WriteError<E, Error>, F) {
601 (self.error, self.file)
602 }
603}
604
605impl<F, E: fmt::Debug> fmt::Debug for FinishError<F, E> {
606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607 f.debug_struct("FinishError").field("error", &self.error).finish_non_exhaustive()
608 }
609}
610
611impl<F, E> fmt::Display for FinishError<F, E> {
612 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613 self.error.fmt(f)
614 }
615}
616
617impl<F, E: core::error::Error + 'static> core::error::Error for FinishError<F, E> {
618 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
619 self.error.source()
620 }
621}
622
623#[cfg(feature = "alloc")]
629pub fn to_vec<E, F>(options: Options, source: F) -> Result<alloc::vec::Vec<u8>, E>
630where
631 E: From<Error>,
632 F: FnOnce(&mut Writer<'_>) -> Result<(), E>,
633{
634 let Ok(mut file) = OnePass::new(VecSink::default(), options);
635 source(&mut file.writer())?;
636 match file.finish().map_err(FinishError::into_parts) {
637 Ok(VecSink(bytes)) => Ok(bytes),
638 Err((WriteError::Source(e), _)) => Err(E::from(e)),
639 Err((WriteError::Sink(never), _)) => match never {},
640 }
641}
642
643#[derive(Clone, Copy, Debug, PartialEq, Eq)]
645struct Plan {
646 data_size: u32,
647 file_size: u32,
648 data_crc: u16,
649}
650
651fn plan<E, F>(options: Options, source: &mut F, require_end: bool) -> Result<Plan, E>
652where
653 E: From<Error>,
654 F: FnMut(&mut Writer<'_>) -> Result<(), E>,
655{
656 let mut st = State::new(options, None);
657 st.require_end = require_end;
658 source(&mut Writer { out: &mut Counter, st: &mut st })?;
659 Ok(st.plan()?)
660}
661
662fn file_crc(header: &[u8], st: &State) -> [u8; 2] {
663 let mut crc = Crc::new();
664 crc.update(header);
665 crc.then(st.data_crc, st.written).value().to_le_bytes()
666}
667
668fn header(options: Options, data_size: u32) -> [u8; HEADER_LEN as usize] {
669 let mut h = [0u8; HEADER_LEN as usize];
670 let [h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13] = &mut h;
671 *h0 = HEADER_LEN;
672 *h1 = PROTOCOL_VERSION;
673 [*h2, *h3] = options.profile_version.to_le_bytes();
674 [*h4, *h5, *h6, *h7] = data_size.to_le_bytes();
675 [*h8, *h9, *h10, *h11] = *b".FIT";
676 let mut crc = Crc::new();
677 crc.update(&[*h0, *h1, *h2, *h3, *h4, *h5, *h6, *h7, *h8, *h9, *h10, *h11]);
678 [*h12, *h13] = crc.value().to_le_bytes();
679 h
680}
681
682trait Out {
683 fn write(&mut self, bytes: &[u8]) -> bool;
685
686 fn fits(&mut self, _size: u32) -> bool {
689 true
690 }
691}
692
693struct Counter;
694
695impl Out for Counter {
696 fn write(&mut self, _: &[u8]) -> bool {
697 true
698 }
699}
700
701struct SinkOut<S: Sink> {
702 sink: S,
703 error: Option<S::Error>,
704}
705
706impl<S: Sink> Out for SinkOut<S> {
707 fn write(&mut self, bytes: &[u8]) -> bool {
708 match self.sink.write(bytes) {
709 Ok(()) => true,
710 Err(e) => {
711 self.error = Some(e);
712 false
713 }
714 }
715 }
716}
717
718#[derive(Clone, Copy, Debug, PartialEq, Eq)]
720struct Layout {
721 global: u16,
722 shape: Shape,
723 raw: extra::RawDefs,
725 dev: u32,
727}
728
729#[derive(Clone, Copy, Debug, PartialEq, Eq)]
731enum Shape {
732 Message { fields: &'static [FieldDef], keep: Mask },
733 Record { fields: RecordFields, compressed: bool },
734}
735
736#[derive(Clone, Debug)]
739struct Locals {
740 held: [Option<(Layout, u32)>; 16],
741 clock: u32,
742}
743
744impl Locals {
745 const fn new() -> Self {
746 Self { held: [None; 16], clock: 0 }
747 }
748
749 fn find(&self, layout: Layout) -> (u8, bool) {
751 let (first, group) = match layout.shape {
752 Shape::Record { .. } => (0u8, self.held.get(..4)),
753 Shape::Message { .. } => (4u8, self.held.get(4..)),
754 };
755 let group = group.unwrap_or(&[]);
756 let local = |i: usize| first.saturating_add(u8::try_from(i).unwrap_or(u8::MAX));
757 if let Some(i) = group.iter().position(|h| h.is_some_and(|(l, _)| l == layout)) {
758 return (local(i), false);
759 }
760 if let Some(i) = group.iter().position(Option::is_none) {
761 return (local(i), true);
762 }
763 let oldest = group
764 .iter()
765 .enumerate()
766 .min_by_key(|(_, h)| h.map_or(0, |(_, used)| used))
767 .map_or(0, |(i, _)| i);
768 (local(oldest), true)
769 }
770
771 fn hold(&mut self, local: u8, layout: Layout) {
772 self.clock = self.clock.wrapping_add(1);
773 if let Some(h) = self.held.get_mut(usize::from(local)) {
774 *h = Some((layout, self.clock));
775 }
776 }
777}
778
779const fn fixed_layout<M: Message>() -> Layout {
781 let shape = Shape::Message { fields: M::FIELDS, keep: Mask::ALL };
782 Layout { global: M::GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 }
783}
784
785#[derive(Clone, Copy)]
787enum Header {
788 Normal,
789 Compressed(u8),
791}
792
793#[derive(Clone, Copy)]
795pub(crate) struct Planned {
796 layout: Layout,
797 keep: Mask,
798 local: u8,
799 count: u8,
800 definition: u32,
802 body: u32,
804}
805
806impl Planned {
807 pub(crate) const fn size(&self) -> u32 {
809 self.definition.saturating_add(self.body)
810 }
811
812 pub(crate) fn after(&self, before: &Self) -> u32 {
815 if before.definition > 0 && before.local == self.local && self.definition == 0 {
816 self.definition_len().saturating_add(self.body)
817 } else {
818 self.size()
819 }
820 }
821
822 fn definition_len(&self) -> u32 {
823 definition_len(u32::from(self.count), self.layout.dev.count_ones())
824 }
825}
826
827const fn definition_len(fields: u32, dev_fields: u32) -> u32 {
830 let dev = match dev_fields {
831 0 => 0,
832 n => n.saturating_mul(3).saturating_add(1),
833 };
834 fields.saturating_mul(3).saturating_add(6).saturating_add(dev)
835}
836
837const STAGE: usize = 32;
838
839#[derive(Clone)]
841struct State {
842 options: Options,
843 plan: Option<Plan>,
844 stage: [u8; STAGE],
845 staged: usize,
846 data_crc: Crc,
847 written: u32,
848 locals: Locals,
849 last_timestamp: Option<Timestamp>,
850 laps: u16,
851 sessions: u16,
852 failed: bool,
853 act: activity::Act,
854 require_end: bool,
855 dev: extra::DevTable,
856}
857
858impl State {
859 fn new(options: Options, plan: Option<Plan>) -> Self {
860 Self {
861 options,
862 plan,
863 stage: [0; STAGE],
864 staged: 0,
865 data_crc: Crc::new(),
866 written: 0,
867 locals: Locals::new(),
868 last_timestamp: None,
869 laps: 0,
870 sessions: 0,
871 failed: false,
872 act: activity::Act::new(),
873 require_end: true,
874 dev: extra::DevTable::new(),
875 }
876 }
877
878 fn plan(mut self) -> Result<Plan, Error> {
880 Writer { out: &mut Counter, st: &mut self }.close()?;
881 let file_size = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
882 Ok(Plan { data_size: self.written, file_size, data_crc: self.data_crc.value() })
883 }
884
885 fn trailer(&self) -> Result<([u8; HEADER_LEN as usize], u32, [u8; 2]), Error> {
888 let header = header(self.options, self.written);
889 let back = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
890 let crc = file_crc(&header, self);
891 Ok((header, back, crc))
892 }
893}
894
895pub struct Writer<'a> {
898 out: &'a mut dyn Out,
899 st: &'a mut State,
900}
901
902impl fmt::Debug for Writer<'_> {
903 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
904 f.debug_struct("Writer").field("written", &self.st.written).finish_non_exhaustive()
905 }
906}
907
908impl Writer<'_> {
909 pub(crate) fn raw_file_id(&mut self, msg: &FileId) -> Result<(), Error> {
911 self.fixed(msg, 0)
912 }
913
914 pub(crate) fn raw_device_info(&mut self, msg: &DeviceInfo<'_>) -> Result<(), Error> {
915 self.fixed(msg, 0)
916 }
917
918 pub(crate) fn raw_event(&mut self, msg: Event) -> Result<(), Error> {
919 self.fixed(&msg, 0)
920 }
921
922 #[cfg(test)]
923 pub(crate) fn raw_record(&mut self, msg: Record) -> Result<(), Error> {
924 self.raw_record_with(msg, &[])
925 }
926
927 fn raw_record_with(&mut self, msg: Record, extras: &[Extra<'_>]) -> Result<(), Error> {
928 let (layout, defs, header, compressed) = self.record_parts(&msg);
929 let t = msg.timestamp;
930 self.message(layout, defs, header, Some(t), Extras::Values(extras), |out| {
931 if !compressed {
932 out.u32(t.fit());
933 }
934 msg.encode(out);
935 })
936 }
937
938 pub(crate) fn record_cost(&self, msg: &Record, extras: &[Extra<'_>]) -> Result<u32, Error> {
940 let (layout, defs, _, compressed) = self.record_parts(msg);
941 let t = msg.timestamp;
942 let planned =
943 self.plan(layout, defs, Extras::Values(extras), &|out: &mut dyn FieldOut| {
944 if !compressed {
945 out.u32(t.fit());
946 }
947 msg.encode(out);
948 })?;
949 Ok(planned.size())
950 }
951
952 fn record_parts(
954 &self,
955 msg: &Record,
956 ) -> (Layout, impl Iterator<Item = FieldDef> + Clone, Header, bool) {
957 let t = msg.timestamp;
958 let compressed = self.st.options.compressed_timestamps
959 && self
960 .st
961 .last_timestamp
962 .and_then(|last| t.fit().checked_sub(last.fit()))
963 .is_some_and(|gap| gap < 32);
964 let shape = Shape::Record { fields: msg.fields(), compressed };
965 let layout = Layout { global: RECORD_GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 };
966 let defs = core::iter::once(RECORD_TIMESTAMP)
967 .filter(move |_| !compressed)
968 .chain(record_fields(msg.fields()));
969 let header = if compressed {
970 #[allow(clippy::cast_possible_truncation)]
971 Header::Compressed((t.fit() & 0x1F) as u8)
972 } else {
973 Header::Normal
974 };
975 (layout, defs, header, compressed)
976 }
977
978 pub(crate) fn raw_lap(&mut self, msg: &Lap) -> Result<(), Error> {
980 self.fixed_with(msg, next_index(self.st.laps)?, Extras::Staged(KindId::Lap))?;
981 self.st.laps = self.st.laps.wrapping_add(1);
982 self.st.dev.unstage(KindId::Lap);
983 Ok(())
984 }
985
986 pub(crate) fn raw_session(&mut self, msg: &Session) -> Result<(), Error> {
988 self.fixed_with(msg, next_index(self.st.sessions)?, Extras::Staged(KindId::Session))?;
989 self.st.sessions = self.st.sessions.wrapping_add(1);
990 self.st.dev.unstage(KindId::Session);
991 Ok(())
992 }
993
994 pub(crate) fn raw_activity(&mut self, msg: &Activity) -> Result<(), Error> {
996 self.fixed(msg, 0)
997 }
998
999 fn fixed<M: Message>(&mut self, msg: &M, index: u16) -> Result<(), Error> {
1000 self.fixed_with(msg, index, Extras::Values(&[]))
1001 }
1002
1003 fn fixed_with<M: Message>(
1004 &mut self,
1005 msg: &M,
1006 index: u16,
1007 extras: Extras<'_>,
1008 ) -> Result<(), Error> {
1009 let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
1010 self.message(layout, defs, Header::Normal, msg.timestamp(), extras, |out| {
1011 msg.encode(out, index);
1012 })
1013 }
1014
1015 pub(crate) fn cost<M: Message>(&self, msg: &M) -> Result<Planned, Error> {
1017 self.cost_with(msg, Extras::Values(&[]))
1018 }
1019
1020 fn cost_with<M: Message>(&self, msg: &M, extras: Extras<'_>) -> Result<Planned, Error> {
1022 let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
1023 self.plan(layout, defs, extras, &|out: &mut dyn FieldOut| msg.encode(out, 0))
1024 }
1025
1026 fn plan<I>(
1029 &self,
1030 mut layout: Layout,
1031 table: I,
1032 extras: Extras<'_>,
1033 encode: &dyn Fn(&mut dyn FieldOut),
1034 ) -> Result<Planned, Error>
1035 where
1036 I: Iterator<Item = FieldDef> + Clone,
1037 {
1038 let mut check = Fields::new(table.clone(), None);
1039 encode(&mut check);
1040 refusal(check.refused())?;
1041 let keep = check.present();
1043 if let Shape::Message { keep: k, .. } = &mut layout.shape {
1044 *k = keep;
1045 }
1046 let defs = kept(table, keep);
1047 layout.raw = extra::raw_defs(extras)?;
1048 layout.dev = self.dev_fields(extras)?;
1049 let (local, define) = self.st.locals.find(layout);
1050 let count = defs.clone().count().saturating_add(layout.raw.defs().count());
1051 let count = u8::try_from(count).map_err(|_| Error::TooLarge)?;
1052 let planned = Planned { layout, keep, local, count, definition: 0, body: 0 };
1053 let definition = if define { planned.definition_len() } else { 0 };
1054 let body = data_len(defs)
1055 .saturating_add(data_len(layout.raw.defs()))
1056 .saturating_add(self.st.dev.size(layout.dev))
1057 .saturating_add(1);
1058 Ok(Planned { definition, body, ..planned })
1059 }
1060
1061 fn message<I>(
1063 &mut self,
1064 layout: Layout,
1065 table: I,
1066 header: Header,
1067 timestamp: Option<Timestamp>,
1068 extras: Extras<'_>,
1069 encode: impl Fn(&mut dyn FieldOut),
1070 ) -> Result<(), Error>
1071 where
1072 I: Iterator<Item = FieldDef> + Clone,
1073 {
1074 if self.st.failed {
1075 return Err(Error::Sink);
1076 }
1077 let planned = self.plan(layout, table.clone(), extras, &encode)?;
1078 self.reserve(planned.size())?;
1079 let Planned { layout, keep, local, count, definition, .. } = planned;
1080 self.st.locals.hold(local, layout);
1081
1082 if definition > 0 {
1083 let [g0, g1] = layout.global.to_le_bytes();
1084 let flag = if layout.dev == 0 { 0 } else { 0x20 };
1085 self.put(&[0x40 | flag | local, 0, 0, g0, g1, count]);
1086 for f in kept(table.clone(), keep).chain(layout.raw.defs()) {
1087 self.put(&[f.num, f.size, f.base]);
1088 }
1089 if layout.dev != 0 {
1090 self.put_dev_definitions(layout.dev);
1091 }
1092 }
1093 match header {
1094 Header::Normal => self.put(&[local]),
1095 Header::Compressed(low) => self.put(&[0x80 | local << 5 | low]),
1096 }
1097 let mut fields = Fields::new(table, Some(self)).keep(keep);
1098 encode(&mut fields);
1099 fields.finish();
1100 self.put_raw_fields(extras);
1101 self.put_dev_fields(extras, layout.dev);
1102 self.flush();
1103 if self.st.failed {
1104 return Err(Error::Sink);
1105 }
1106 if let Some(t) = timestamp {
1107 self.st.last_timestamp = Some(t);
1108 }
1109 Ok(())
1110 }
1111
1112 fn reserve(&mut self, size: u32) -> Result<(), Error> {
1113 let end = self.room(size)?;
1114 if self.st.plan.is_some_and(|plan| end > plan.data_size) {
1115 return Err(Error::SourceChanged);
1116 }
1117 self.st.written = end;
1118 Ok(())
1119 }
1120
1121 fn room(&mut self, size: u32) -> Result<u32, Error> {
1124 let end = self.st.written.checked_add(size).ok_or(Error::TooLarge)?;
1125 match end.checked_add(self.st.act.kept_for_end()) {
1126 Some(n) if n <= LIMIT => {
1127 self.ahead(size)?;
1128 Ok(end)
1129 }
1130 _ => Err(Error::TooLarge),
1131 }
1132 }
1133
1134 fn ahead(&mut self, size: u32) -> Result<(), Error> {
1136 if self.out.fits(size) {
1137 Ok(())
1138 } else {
1139 Err(Error::Sink)
1140 }
1141 }
1142
1143 fn flush(&mut self) {
1144 if let Some(bytes) = self.st.stage.get(..self.st.staged) {
1145 if !self.st.failed && !bytes.is_empty() && !self.out.write(bytes) {
1146 self.st.failed = true;
1147 }
1148 }
1149 self.st.staged = 0;
1150 }
1151
1152 fn close(&mut self) -> Result<(), Error> {
1155 self.flush();
1156 if self.st.failed {
1157 return Err(Error::Sink);
1158 }
1159 if self.st.require_end && !self.st.act.ended() {
1160 return Err(Error::Unfinished);
1161 }
1162 match self.st.plan {
1163 Some(plan)
1164 if plan.data_size != self.st.written
1165 || plan.data_crc != self.st.data_crc.value() =>
1166 {
1167 Err(Error::SourceChanged)
1168 }
1169 _ => Ok(()),
1170 }
1171 }
1172}
1173
1174impl Put for Writer<'_> {
1175 fn put(&mut self, bytes: &[u8]) {
1176 self.st.data_crc.update(bytes);
1177 for &byte in bytes {
1178 if let Some(slot) = self.st.stage.get_mut(self.st.staged) {
1179 *slot = byte;
1180 self.st.staged = self.st.staged.saturating_add(1);
1181 }
1182 if self.st.staged == STAGE {
1183 self.flush();
1184 }
1185 }
1186 }
1187}
1188
1189fn check<M: Message>(msg: &M) -> Result<(), Error> {
1191 let mut fields = Fields::new(M::FIELDS.iter().copied(), None);
1192 msg.encode(&mut fields, 0);
1193 refusal(fields.refused())
1194}
1195
1196fn refusal(refused: Option<FieldError>) -> Result<(), Error> {
1197 match refused {
1198 Some(FieldError::StringTooLong) => Err(Error::StringTooLong),
1199 Some(FieldError::OutOfRange) => Err(Error::OutOfRange),
1200 None => Ok(()),
1201 }
1202}
1203
1204fn next_index(count: u16) -> Result<u16, Error> {
1206 if count >= 0x0FFF {
1207 Err(Error::IndexFull)
1208 } else {
1209 Ok(count)
1210 }
1211}
1212
1213mod activity;
1214#[cfg(feature = "async")]
1215mod asynch;
1216#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
1217mod embedded_io;
1218mod extra;
1219#[cfg(test)]
1220mod tests;
1221
1222#[cfg(feature = "async")]
1223pub use asynch::{
1224 write_async, AsyncOnePass, AsyncPatchSink, AsyncSink, AsyncWriter, ASYNC_WRITE_LEN,
1225};
1226#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
1227pub use embedded_io::{EmbeddedIo, EmbeddedIoError};