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,
261 IndexFull,
264 OutOfOrder,
271 TimeWentBack,
273 Paused,
275 DistanceWentBack,
277 Unfinished,
279 GivenByLengths,
282 Undeclared,
285 Duplicate,
287 Reserved,
290 TooMany,
293}
294
295impl fmt::Display for Error {
296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297 f.write_str(match self {
298 Self::Sink => "the sink failed",
299 Self::SourceChanged => "the source wrote different messages on the second pass",
300 Self::TooLarge => "the file would be 4 GiB or more",
301 Self::StringTooLong => "string longer than its field",
302 Self::OutOfRange => "value out of its field's range",
303 Self::IndexFull => "no message_index left for another lap or session",
304 Self::OutOfOrder => "the activity is not ready for that call",
305 Self::TimeWentBack => "a time before one already written",
306 Self::Paused => "a record, length or set while the timer is paused",
307 Self::DistanceWentBack => "a total distance less than one already written",
308 Self::Unfinished => "the activity was not ended",
309 Self::GivenByLengths => "a distance, speed or cadence that a pool swim's lengths give",
310 Self::Undeclared => "a developer or field this file did not declare",
311 Self::Duplicate => "given twice",
312 Self::Reserved => "a message or field the encoder writes itself",
313 Self::TooMany => "more developers or fields than the encoder holds",
314 })
315 }
316}
317
318impl core::error::Error for Error {}
319
320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
326pub enum WriteError<S, E> {
327 Sink(S),
329 Source(E),
331}
332
333impl<S, E: fmt::Display> fmt::Display for WriteError<S, E> {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 match self {
336 Self::Sink(_) => f.write_str("the sink failed"),
337 Self::Source(e) => e.fmt(f),
338 }
339 }
340}
341
342impl<S, E> core::error::Error for WriteError<S, E>
343where
344 S: core::error::Error + 'static,
345 E: core::error::Error + 'static,
346{
347 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
348 match self {
349 Self::Sink(e) => Some(e),
350 Self::Source(e) => e.source(),
351 }
352 }
353}
354
355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357pub struct Options {
358 compressed_timestamps: bool,
359 profile_version: u16,
360 utc_offset: Option<i32>,
361 auto_multisport: bool,
362}
363
364impl Options {
365 #[must_use]
367 pub const fn new() -> Self {
368 Self {
369 compressed_timestamps: false,
370 profile_version: 2100,
371 utc_offset: None,
372 auto_multisport: false,
373 }
374 }
375
376 #[must_use]
380 pub const fn auto_multisport(mut self, on: bool) -> Self {
381 self.auto_multisport = on;
382 self
383 }
384
385 #[must_use]
389 pub const fn compressed_timestamps(mut self, on: bool) -> Self {
390 self.compressed_timestamps = on;
391 self
392 }
393
394 #[must_use]
397 pub const fn utc_offset(mut self, seconds: i32) -> Self {
398 self.utc_offset = Some(seconds);
399 self
400 }
401
402 #[must_use]
404 pub const fn profile_version(mut self, version: u16) -> Self {
405 self.profile_version = version;
406 self
407 }
408}
409
410impl Default for Options {
411 fn default() -> Self {
412 Self::new()
413 }
414}
415
416pub fn size<E, F>(options: Options, mut source: F) -> Result<u32, E>
422where
423 E: From<Error>,
424 F: FnMut(&mut Writer<'_>) -> Result<(), E>,
425{
426 Ok(plan(options, &mut source, true)?.file_size)
427}
428
429pub fn write<S, E, F>(sink: S, options: Options, source: F) -> Result<S, WriteError<S::Error, E>>
458where
459 S: Sink,
460 E: From<Error>,
461 F: FnMut(&mut Writer<'_>) -> Result<(), E>,
462{
463 write_with(sink, options, source, true)
464}
465
466fn write_with<S, E, F>(
468 sink: S,
469 options: Options,
470 mut source: F,
471 require_end: bool,
472) -> Result<S, WriteError<S::Error, E>>
473where
474 S: Sink,
475 E: From<Error>,
476 F: FnMut(&mut Writer<'_>) -> Result<(), E>,
477{
478 let plan = plan(options, &mut source, require_end).map_err(WriteError::Source)?;
479 let mut out = SinkOut { sink, error: None };
480 out.sink.begin(plan.file_size).map_err(WriteError::Sink)?;
481 let header = header(options, plan.data_size);
482 out.sink.write(&header).map_err(WriteError::Sink)?;
483
484 let mut st = State::new(options, Some(plan));
485 st.require_end = require_end;
486 let result = source(&mut Writer { out: &mut out, st: &mut st });
487 let end = Writer { out: &mut out, st: &mut st }.close();
488 if let Some(e) = out.error.take() {
489 return Err(WriteError::Sink(e));
490 }
491 result.map_err(WriteError::Source)?;
492 end.map_err(|e| WriteError::Source(E::from(e)))?;
493 out.sink.write(&file_crc(&header, &st)).map_err(WriteError::Sink)?;
494 Ok(out.sink)
495}
496
497pub struct OnePass<S: PatchSink> {
518 out: SinkOut<S>,
519 st: State,
520}
521
522impl<S: PatchSink> fmt::Debug for OnePass<S> {
523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524 f.debug_struct("OnePass").field("written", &self.st.written).finish_non_exhaustive()
525 }
526}
527
528impl<S: PatchSink> OnePass<S> {
529 pub fn new(mut sink: S, options: Options) -> Result<Self, S::Error> {
535 sink.write(&header(options, 0))?;
536 Ok(Self { out: SinkOut { sink, error: None }, st: State::new(options, None) })
537 }
538
539 pub fn writer(&mut self) -> Writer<'_> {
541 Writer { out: &mut self.out, st: &mut self.st }
542 }
543
544 #[allow(clippy::result_large_err, reason = "the error holds the file, to finish again")]
553 pub fn finish(mut self) -> Result<S, FinishError<Self, S::Error>> {
554 match self.try_finish() {
555 Ok(()) => Ok(self.out.sink),
556 Err(error) => Err(FinishError { error, file: self }),
557 }
558 }
559
560 pub fn into_sink(self) -> S {
563 self.out.sink
564 }
565
566 fn try_finish(&mut self) -> Result<(), WriteError<S::Error, Error>> {
567 let ended = Writer { out: &mut self.out, st: &mut self.st }.close();
568 if let Some(e) = self.out.error.take() {
569 return Err(WriteError::Sink(e));
570 }
571 ended.map_err(WriteError::Source)?;
572 let (header, back, crc) = self.st.trailer().map_err(WriteError::Source)?;
573 let written = self.out.sink.write(&crc).and_then(|()| self.out.sink.patch(back, &header));
575 written.map_err(|e| {
576 self.st.failed = true;
577 WriteError::Sink(e)
578 })
579 }
580}
581
582pub struct FinishError<F, E> {
585 error: WriteError<E, Error>,
586 file: F,
587}
588
589impl<F, E> FinishError<F, E> {
590 pub const fn error(&self) -> &WriteError<E, Error> {
592 &self.error
593 }
594
595 pub fn into_inner(self) -> F {
597 self.file
598 }
599
600 pub fn into_parts(self) -> (WriteError<E, Error>, F) {
602 (self.error, self.file)
603 }
604}
605
606impl<F, E: fmt::Debug> fmt::Debug for FinishError<F, E> {
607 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608 f.debug_struct("FinishError").field("error", &self.error).finish_non_exhaustive()
609 }
610}
611
612impl<F, E> fmt::Display for FinishError<F, E> {
613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 self.error.fmt(f)
615 }
616}
617
618impl<F, E: core::error::Error + 'static> core::error::Error for FinishError<F, E> {
619 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
620 self.error.source()
621 }
622}
623
624#[cfg(feature = "alloc")]
630pub fn to_vec<E, F>(options: Options, source: F) -> Result<alloc::vec::Vec<u8>, E>
631where
632 E: From<Error>,
633 F: FnOnce(&mut Writer<'_>) -> Result<(), E>,
634{
635 let Ok(mut file) = OnePass::new(VecSink::default(), options);
636 source(&mut file.writer())?;
637 match file.finish().map_err(FinishError::into_parts) {
638 Ok(VecSink(bytes)) => Ok(bytes),
639 Err((WriteError::Source(e), _)) => Err(E::from(e)),
640 Err((WriteError::Sink(never), _)) => match never {},
641 }
642}
643
644#[derive(Clone, Copy, Debug, PartialEq, Eq)]
646struct Plan {
647 data_size: u32,
648 file_size: u32,
649 data_crc: u16,
650}
651
652fn plan<E, F>(options: Options, source: &mut F, require_end: bool) -> Result<Plan, E>
653where
654 E: From<Error>,
655 F: FnMut(&mut Writer<'_>) -> Result<(), E>,
656{
657 let mut st = State::new(options, None);
658 st.require_end = require_end;
659 source(&mut Writer { out: &mut Counter, st: &mut st })?;
660 Ok(st.plan()?)
661}
662
663fn file_crc(header: &[u8], st: &State) -> [u8; 2] {
664 let mut crc = Crc::new();
665 crc.update(header);
666 crc.then(st.data_crc, st.written).value().to_le_bytes()
667}
668
669fn header(options: Options, data_size: u32) -> [u8; HEADER_LEN as usize] {
670 let mut h = [0u8; HEADER_LEN as usize];
671 let [h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13] = &mut h;
672 *h0 = HEADER_LEN;
673 *h1 = PROTOCOL_VERSION;
674 [*h2, *h3] = options.profile_version.to_le_bytes();
675 [*h4, *h5, *h6, *h7] = data_size.to_le_bytes();
676 [*h8, *h9, *h10, *h11] = *b".FIT";
677 let mut crc = Crc::new();
678 crc.update(&[*h0, *h1, *h2, *h3, *h4, *h5, *h6, *h7, *h8, *h9, *h10, *h11]);
679 [*h12, *h13] = crc.value().to_le_bytes();
680 h
681}
682
683trait Out {
684 fn write(&mut self, bytes: &[u8]) -> bool;
686
687 fn fits(&mut self, _size: u32) -> bool {
690 true
691 }
692}
693
694struct Counter;
695
696impl Out for Counter {
697 fn write(&mut self, _: &[u8]) -> bool {
698 true
699 }
700}
701
702struct SinkOut<S: Sink> {
703 sink: S,
704 error: Option<S::Error>,
705}
706
707impl<S: Sink> Out for SinkOut<S> {
708 fn write(&mut self, bytes: &[u8]) -> bool {
709 match self.sink.write(bytes) {
710 Ok(()) => true,
711 Err(e) => {
712 self.error = Some(e);
713 false
714 }
715 }
716 }
717}
718
719#[derive(Clone, Copy, Debug, PartialEq, Eq)]
721struct Layout {
722 global: u16,
723 shape: Shape,
724 raw: extra::RawDefs,
726 dev: u32,
728}
729
730#[derive(Clone, Copy, Debug, PartialEq, Eq)]
732enum Shape {
733 Message { fields: &'static [FieldDef], keep: Mask },
734 Record { fields: RecordFields, compressed: bool },
735}
736
737#[derive(Clone, Debug)]
740struct Locals {
741 held: [Option<(Layout, u32)>; 16],
742 clock: u32,
743}
744
745impl Locals {
746 const fn new() -> Self {
747 Self { held: [None; 16], clock: 0 }
748 }
749
750 fn find(&self, layout: Layout) -> (u8, bool) {
752 let (first, group) = match layout.shape {
753 Shape::Record { .. } => (0u8, self.held.get(..4)),
754 Shape::Message { .. } => (4u8, self.held.get(4..)),
755 };
756 let group = group.unwrap_or(&[]);
757 let local = |i: usize| first.saturating_add(u8::try_from(i).unwrap_or(u8::MAX));
758 if let Some(i) = group.iter().position(|h| h.is_some_and(|(l, _)| l == layout)) {
759 return (local(i), false);
760 }
761 if let Some(i) = group.iter().position(Option::is_none) {
762 return (local(i), true);
763 }
764 let oldest = group
765 .iter()
766 .enumerate()
767 .min_by_key(|(_, h)| h.map_or(0, |(_, used)| used))
768 .map_or(0, |(i, _)| i);
769 (local(oldest), true)
770 }
771
772 fn hold(&mut self, local: u8, layout: Layout) {
773 self.clock = self.clock.wrapping_add(1);
774 if let Some(h) = self.held.get_mut(usize::from(local)) {
775 *h = Some((layout, self.clock));
776 }
777 }
778}
779
780const fn fixed_layout<M: Message>() -> Layout {
782 let shape = Shape::Message { fields: M::FIELDS, keep: Mask::ALL };
783 Layout { global: M::GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 }
784}
785
786#[derive(Clone, Copy)]
788enum Header {
789 Normal,
790 Compressed(u8),
792}
793
794#[derive(Clone, Copy)]
796pub(crate) struct Planned {
797 layout: Layout,
798 keep: Mask,
799 local: u8,
800 count: u8,
801 definition: u32,
803 body: u32,
805}
806
807impl Planned {
808 pub(crate) const fn size(&self) -> u32 {
810 self.definition.saturating_add(self.body)
811 }
812
813 pub(crate) fn after(&self, before: &Self) -> u32 {
816 if before.definition > 0 && before.local == self.local && self.definition == 0 {
817 self.definition_len().saturating_add(self.body)
818 } else {
819 self.size()
820 }
821 }
822
823 fn definition_len(&self) -> u32 {
824 definition_len(u32::from(self.count), self.layout.dev.count_ones())
825 }
826}
827
828const fn definition_len(fields: u32, dev_fields: u32) -> u32 {
831 let dev = match dev_fields {
832 0 => 0,
833 n => n.saturating_mul(3).saturating_add(1),
834 };
835 fields.saturating_mul(3).saturating_add(6).saturating_add(dev)
836}
837
838const STAGE: usize = 32;
839
840#[derive(Clone)]
842struct State {
843 options: Options,
844 plan: Option<Plan>,
845 stage: [u8; STAGE],
846 staged: usize,
847 data_crc: Crc,
848 written: u32,
849 locals: Locals,
850 last_timestamp: Option<Timestamp>,
851 laps: u16,
852 sessions: u16,
853 failed: bool,
854 act: activity::Act,
855 require_end: bool,
856 dev: extra::DevTable,
857}
858
859impl State {
860 fn new(options: Options, plan: Option<Plan>) -> Self {
861 Self {
862 options,
863 plan,
864 stage: [0; STAGE],
865 staged: 0,
866 data_crc: Crc::new(),
867 written: 0,
868 locals: Locals::new(),
869 last_timestamp: None,
870 laps: 0,
871 sessions: 0,
872 failed: false,
873 act: activity::Act::new(),
874 require_end: true,
875 dev: extra::DevTable::new(),
876 }
877 }
878
879 fn plan(mut self) -> Result<Plan, Error> {
881 Writer { out: &mut Counter, st: &mut self }.close()?;
882 let file_size = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
883 Ok(Plan { data_size: self.written, file_size, data_crc: self.data_crc.value() })
884 }
885
886 fn trailer(&self) -> Result<([u8; HEADER_LEN as usize], u32, [u8; 2]), Error> {
889 let header = header(self.options, self.written);
890 let back = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
891 let crc = file_crc(&header, self);
892 Ok((header, back, crc))
893 }
894}
895
896pub struct Writer<'a> {
899 out: &'a mut dyn Out,
900 st: &'a mut State,
901}
902
903impl fmt::Debug for Writer<'_> {
904 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
905 f.debug_struct("Writer").field("written", &self.st.written).finish_non_exhaustive()
906 }
907}
908
909impl Writer<'_> {
910 pub(crate) fn raw_file_id(&mut self, msg: &FileId) -> Result<(), Error> {
912 self.fixed(msg, 0)
913 }
914
915 pub(crate) fn raw_device_info(&mut self, msg: &DeviceInfo<'_>) -> Result<(), Error> {
916 self.fixed(msg, 0)
917 }
918
919 pub(crate) fn raw_event(&mut self, msg: Event) -> Result<(), Error> {
920 self.fixed(&msg, 0)
921 }
922
923 #[cfg(test)]
924 pub(crate) fn raw_record(&mut self, msg: Record) -> Result<(), Error> {
925 self.raw_record_with(msg, &[])
926 }
927
928 fn raw_record_with(&mut self, msg: Record, extras: &[Extra<'_>]) -> Result<(), Error> {
929 let (layout, defs, header, compressed) = self.record_parts(&msg);
930 let t = msg.timestamp;
931 self.message(layout, defs, header, Some(t), Extras::Values(extras), |out| {
932 if !compressed {
933 out.u32(t.fit());
934 }
935 msg.encode(out);
936 })
937 }
938
939 pub(crate) fn record_cost(&self, msg: &Record, extras: &[Extra<'_>]) -> Result<u32, Error> {
941 let (layout, defs, _, compressed) = self.record_parts(msg);
942 let t = msg.timestamp;
943 let planned =
944 self.plan(layout, defs, Extras::Values(extras), &|out: &mut dyn FieldOut| {
945 if !compressed {
946 out.u32(t.fit());
947 }
948 msg.encode(out);
949 })?;
950 Ok(planned.size())
951 }
952
953 fn record_parts(
955 &self,
956 msg: &Record,
957 ) -> (Layout, impl Iterator<Item = FieldDef> + Clone, Header, bool) {
958 let t = msg.timestamp;
959 let compressed = self.st.options.compressed_timestamps
960 && self
961 .st
962 .last_timestamp
963 .and_then(|last| t.fit().checked_sub(last.fit()))
964 .is_some_and(|gap| gap < 32);
965 let shape = Shape::Record { fields: msg.fields(), compressed };
966 let layout = Layout { global: RECORD_GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 };
967 let defs = core::iter::once(RECORD_TIMESTAMP)
968 .filter(move |_| !compressed)
969 .chain(record_fields(msg.fields()));
970 let header = if compressed {
971 #[allow(clippy::cast_possible_truncation)]
972 Header::Compressed((t.fit() & 0x1F) as u8)
973 } else {
974 Header::Normal
975 };
976 (layout, defs, header, compressed)
977 }
978
979 pub(crate) fn raw_lap(&mut self, msg: &Lap) -> Result<(), Error> {
981 self.fixed_with(msg, next_index(self.st.laps, LAPS_MAX)?, Extras::Staged(KindId::Lap))?;
982 self.st.laps = self.st.laps.wrapping_add(1);
983 self.st.dev.unstage(KindId::Lap);
984 Ok(())
985 }
986
987 pub(crate) fn raw_session(&mut self, msg: &Session) -> Result<(), Error> {
989 let index = next_index(self.st.sessions, SESSIONS_MAX)?;
990 self.fixed_with(msg, index, Extras::Staged(KindId::Session))?;
991 self.st.sessions = self.st.sessions.wrapping_add(1);
992 self.st.dev.unstage(KindId::Session);
993 Ok(())
994 }
995
996 pub(crate) fn raw_activity(&mut self, msg: &Activity) -> Result<(), Error> {
998 self.fixed(msg, 0)
999 }
1000
1001 fn fixed<M: Message>(&mut self, msg: &M, index: u16) -> Result<(), Error> {
1002 self.fixed_with(msg, index, Extras::Values(&[]))
1003 }
1004
1005 fn fixed_with<M: Message>(
1006 &mut self,
1007 msg: &M,
1008 index: u16,
1009 extras: Extras<'_>,
1010 ) -> Result<(), Error> {
1011 let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
1012 self.message(layout, defs, Header::Normal, msg.timestamp(), extras, |out| {
1013 msg.encode(out, index);
1014 })
1015 }
1016
1017 pub(crate) fn cost<M: Message>(&self, msg: &M) -> Result<Planned, Error> {
1019 self.cost_with(msg, Extras::Values(&[]))
1020 }
1021
1022 fn cost_with<M: Message>(&self, msg: &M, extras: Extras<'_>) -> Result<Planned, Error> {
1024 let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
1025 self.plan(layout, defs, extras, &|out: &mut dyn FieldOut| msg.encode(out, 0))
1026 }
1027
1028 fn plan<I>(
1031 &self,
1032 mut layout: Layout,
1033 table: I,
1034 extras: Extras<'_>,
1035 encode: &dyn Fn(&mut dyn FieldOut),
1036 ) -> Result<Planned, Error>
1037 where
1038 I: Iterator<Item = FieldDef> + Clone,
1039 {
1040 let mut check = Fields::new(table.clone(), None);
1041 encode(&mut check);
1042 refusal(check.refused())?;
1043 let keep = check.present();
1045 if let Shape::Message { keep: k, .. } = &mut layout.shape {
1046 *k = keep;
1047 }
1048 let defs = kept(table, keep);
1049 layout.raw = extra::raw_defs(extras)?;
1050 layout.dev = self.dev_fields(extras)?;
1051 let (local, define) = self.st.locals.find(layout);
1052 let count = defs.clone().count().saturating_add(layout.raw.defs().count());
1053 let count = u8::try_from(count).map_err(|_| Error::TooLarge)?;
1054 let planned = Planned { layout, keep, local, count, definition: 0, body: 0 };
1055 let definition = if define { planned.definition_len() } else { 0 };
1056 let body = data_len(defs)
1057 .saturating_add(data_len(layout.raw.defs()))
1058 .saturating_add(self.st.dev.size(layout.dev))
1059 .saturating_add(1);
1060 Ok(Planned { definition, body, ..planned })
1061 }
1062
1063 fn message<I>(
1065 &mut self,
1066 layout: Layout,
1067 table: I,
1068 header: Header,
1069 timestamp: Option<Timestamp>,
1070 extras: Extras<'_>,
1071 encode: impl Fn(&mut dyn FieldOut),
1072 ) -> Result<(), Error>
1073 where
1074 I: Iterator<Item = FieldDef> + Clone,
1075 {
1076 if self.st.failed {
1077 return Err(Error::Sink);
1078 }
1079 let planned = self.plan(layout, table.clone(), extras, &encode)?;
1080 self.reserve(planned.size())?;
1081 let Planned { layout, keep, local, count, definition, .. } = planned;
1082 self.st.locals.hold(local, layout);
1083
1084 if definition > 0 {
1085 let [g0, g1] = layout.global.to_le_bytes();
1086 let flag = if layout.dev == 0 { 0 } else { 0x20 };
1087 self.put(&[0x40 | flag | local, 0, 0, g0, g1, count]);
1088 for f in kept(table.clone(), keep).chain(layout.raw.defs()) {
1089 self.put(&[f.num, f.size, f.base]);
1090 }
1091 if layout.dev != 0 {
1092 self.put_dev_definitions(layout.dev);
1093 }
1094 }
1095 match header {
1096 Header::Normal => self.put(&[local]),
1097 Header::Compressed(low) => self.put(&[0x80 | local << 5 | low]),
1098 }
1099 let mut fields = Fields::new(table, Some(self)).keep(keep);
1100 encode(&mut fields);
1101 fields.finish();
1102 self.put_raw_fields(extras);
1103 self.put_dev_fields(extras, layout.dev);
1104 self.flush();
1105 if self.st.failed {
1106 return Err(Error::Sink);
1107 }
1108 if let Some(t) = timestamp {
1109 self.st.last_timestamp = Some(t);
1110 }
1111 Ok(())
1112 }
1113
1114 fn reserve(&mut self, size: u32) -> Result<(), Error> {
1115 let end = self.room(size)?;
1116 if self.st.plan.is_some_and(|plan| end > plan.data_size) {
1117 return Err(Error::SourceChanged);
1118 }
1119 self.st.written = end;
1120 Ok(())
1121 }
1122
1123 fn room(&mut self, size: u32) -> Result<u32, Error> {
1126 let end = self.st.written.checked_add(size).ok_or(Error::TooLarge)?;
1127 match end.checked_add(self.st.act.kept_for_end()) {
1128 Some(n) if n <= LIMIT => {
1129 self.ahead(size)?;
1130 Ok(end)
1131 }
1132 _ => Err(Error::TooLarge),
1133 }
1134 }
1135
1136 fn ahead(&mut self, size: u32) -> Result<(), Error> {
1138 if self.out.fits(size) {
1139 Ok(())
1140 } else {
1141 Err(Error::Sink)
1142 }
1143 }
1144
1145 fn flush(&mut self) {
1146 if let Some(bytes) = self.st.stage.get(..self.st.staged) {
1147 if !self.st.failed && !bytes.is_empty() && !self.out.write(bytes) {
1148 self.st.failed = true;
1149 }
1150 }
1151 self.st.staged = 0;
1152 }
1153
1154 fn close(&mut self) -> Result<(), Error> {
1157 self.flush();
1158 if self.st.failed {
1159 return Err(Error::Sink);
1160 }
1161 if self.st.require_end && !self.st.act.ended() {
1162 return Err(Error::Unfinished);
1163 }
1164 match self.st.plan {
1165 Some(plan)
1166 if plan.data_size != self.st.written
1167 || plan.data_crc != self.st.data_crc.value() =>
1168 {
1169 Err(Error::SourceChanged)
1170 }
1171 _ => Ok(()),
1172 }
1173 }
1174}
1175
1176impl Put for Writer<'_> {
1177 fn put(&mut self, bytes: &[u8]) {
1178 self.st.data_crc.update(bytes);
1179 for &byte in bytes {
1180 if let Some(slot) = self.st.stage.get_mut(self.st.staged) {
1181 *slot = byte;
1182 self.st.staged = self.st.staged.saturating_add(1);
1183 }
1184 if self.st.staged == STAGE {
1185 self.flush();
1186 }
1187 }
1188 }
1189}
1190
1191fn check<M: Message>(msg: &M) -> Result<(), Error> {
1193 let mut fields = Fields::new(M::FIELDS.iter().copied(), None);
1194 msg.encode(&mut fields, 0);
1195 refusal(fields.refused())
1196}
1197
1198fn refusal(refused: Option<FieldError>) -> Result<(), Error> {
1199 match refused {
1200 Some(FieldError::StringTooLong) => Err(Error::StringTooLong),
1201 Some(FieldError::OutOfRange) => Err(Error::OutOfRange),
1202 None => Ok(()),
1203 }
1204}
1205
1206const INDEXES: u16 = 0x0FFF;
1208
1209pub const LAPS_MAX: u16 = INDEXES;
1213pub const SESSIONS_MAX: u16 = INDEXES;
1215pub const LENGTHS_MAX: u16 = INDEXES;
1218pub const SETS_MAX: u16 = INDEXES;
1221pub const SENSORS_MAX: u8 = 254;
1224pub const DURATION_SECONDS_MAX: u32 = u32::MAX / 1000;
1227#[allow(clippy::cast_lossless, reason = "f64::from is not const")]
1230pub const DISTANCE_METERS_MAX: f64 = DISTANCE_CM_MAX as f64 / 100.0;
1231const DISTANCE_CM_MAX: u32 = u32::MAX - 1;
1232
1233fn next_index(count: u16, max: u16) -> Result<u16, Error> {
1235 if count >= max {
1236 Err(Error::IndexFull)
1237 } else {
1238 Ok(count)
1239 }
1240}
1241
1242mod activity;
1243#[cfg(feature = "async")]
1244mod asynch;
1245#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
1246mod embedded_io;
1247mod extra;
1248#[cfg(test)]
1249mod tests;
1250
1251#[cfg(feature = "async")]
1252pub use asynch::{
1253 write_async, AsyncOnePass, AsyncPatchSink, AsyncSink, AsyncWriter, ASYNC_WRITE_LEN,
1254};
1255#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
1256pub use embedded_io::{EmbeddedIo, EmbeddedIoError};