// Copyright (C) 2026 Jannik Schürg // // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use std::str::FromStr; use thiserror::Error; mod fields; mod legacy; mod sep; mod utils; pub(crate) use fields::Fields; use crate::{ActivPalTime, Event}; #[derive(Debug)] pub struct EventsParseError { pub line: usize, pub error: EventParseError, } #[derive(Error, Debug)] pub enum EventParseError { #[error("events do not start with correct header line")] InvalidHeader, #[error("too few columns")] TooFewColumns, #[error("error parsing time column {0:?}, expected .<10 fractional digits>")] InvalidTime(String), #[error("error parsing data count column")] InvalidDataCount, #[error("could not parse interval {0:?}")] InvalidInterval(String), #[error("unknown activity code: {0:?}")] InvalidActivityCode(String), #[error("error parsing steps column")] InvalidSteps, #[error("error parsing met hours column")] InvalidMetHours, } impl crate::Events { fn from_events>>( events_iterator: I, ) -> Result { let mut events = Vec::new(); let mut steps_total = 0; for event in events_iterator { let mut event = event?; event.steps -= steps_total; steps_total += event.steps; events.push(event); } Ok(Self { events }) } } impl FromStr for crate::Events { type Err = EventsParseError; fn from_str(s: &str) -> Result { let s = s.as_bytes(); if s.starts_with(b"sep=;") { return Self::from_events(sep::parse_events(s)?); } let header_match = [ b"time,datacount(samples),interval(s),activitycode(0=sedentary,1=standing,2=stepping),cumulativestepcount,activityscore(met.h)".as_ref(), b"time,datacount(samples),interval(s),activitycode(0=sedentary1=standing2=stepping),cumulativestepcount,activityscore(met.h)".as_ref(), ].into_iter().any(|header| { let filtered = s .iter() .cloned() .filter_map(|c| { if c == b' ' || c == b'"' { None } else { Some(c.to_ascii_lowercase()) } }); // zip() stops at the shorter side, so without this length check // any input shorter than the header would vacuously "match". filtered.clone().count() >= header.len() && filtered.zip(header.iter().cloned()).all(|(a, b)| a == b) }); if !header_match { return Err(EventsParseError { line: 1, error: EventParseError::InvalidHeader, }); } Self::from_events(legacy::parse_events(s)) } }