1use chrono::{Datelike, Timelike};
5use rust_decimal::Decimal;
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7use std::collections::BTreeMap;
8use std::fmt;
9use std::str::FromStr;
10
11use crate::computation::rational::{self, RationalInteger};
12
13pub type BaseMeasureVector = BTreeMap<crate::planning::semantics::Dimension, i32>;
22
23pub fn rational_from_parsed_decimal(decimal: Decimal) -> Result<RationalInteger, String> {
28 rational::decimal_to_rational(decimal).map_err(|failure| failure.to_string())
29}
30
31#[derive(Clone, Debug, PartialEq, Eq, Hash)]
43pub enum UnitScale {
44 Literal(RationalInteger),
46 Compound { prefix: RationalInteger },
51 Unresolved {
55 written: String,
56 segments: Vec<String>,
57 name: String,
58 },
59 Reference {
64 factors: Vec<(crate::planning::semantics::ScaleTarget, i32)>,
65 coefficient: RationalInteger,
66 },
67}
68
69impl UnitScale {
70 #[must_use]
71 pub fn dynamic_coefficient(&self) -> Option<&RationalInteger> {
72 match self {
73 UnitScale::Literal(_) | UnitScale::Compound { .. } | UnitScale::Unresolved { .. } => {
74 None
75 }
76 UnitScale::Reference { coefficient, .. } => Some(coefficient),
77 }
78 }
79
80 #[must_use]
83 pub fn canonicalize_scale_factors(
84 factors: &[(crate::planning::semantics::ScaleTarget, i32)],
85 ) -> Vec<(crate::planning::semantics::ScaleTarget, i32)> {
86 let mut accumulator: BTreeMap<crate::planning::semantics::ScaleTarget, i32> =
87 BTreeMap::new();
88 for (target, exponent) in factors {
89 let entry = accumulator.entry(target.clone()).or_insert(0);
90 *entry = entry.checked_add(*exponent).expect(
91 "BUG: planning bounds dynamic scale factor exponents when merging the same target",
92 );
93 }
94 accumulator
95 .into_iter()
96 .filter(|(_, exponent)| *exponent != 0)
97 .collect()
98 }
99}
100
101#[derive(Clone, Debug, PartialEq, Eq, Hash)]
110pub struct MeasureUnit {
111 pub name: String,
112 pub scale: UnitScale,
113 pub derived_measure_factors: Vec<(String, i32)>,
114 pub decomposition: BaseMeasureVector,
115 pub minimum: Option<RationalInteger>,
117 pub maximum: Option<RationalInteger>,
119 pub suggestion_magnitude: Option<RationalInteger>,
121}
122
123impl MeasureUnit {
124 pub fn from_decimal_factor(
125 name: String,
126 decimal_factor: Decimal,
127 derived_measure_factors: Vec<(String, i32)>,
128 ) -> Result<Self, String> {
129 let factor =
130 rational::decimal_to_rational(decimal_factor).map_err(|failure| failure.to_string())?;
131 let scale = if derived_measure_factors.is_empty() {
132 UnitScale::Literal(factor)
133 } else {
134 UnitScale::Compound { prefix: factor }
135 };
136 Ok(MeasureUnit {
137 name,
138 scale,
139 derived_measure_factors,
140 decomposition: BaseMeasureVector::new(),
141 minimum: None,
142 maximum: None,
143 suggestion_magnitude: None,
144 })
145 }
146
147 pub fn from_reference(
148 name: String,
149 written: String,
150 segments: Vec<String>,
151 reference_name: String,
152 ) -> Self {
153 MeasureUnit {
154 name,
155 scale: UnitScale::Unresolved {
156 written,
157 segments,
158 name: reference_name,
159 },
160 derived_measure_factors: Vec::new(),
161 decomposition: BaseMeasureVector::new(),
162 minimum: None,
163 maximum: None,
164 suggestion_magnitude: None,
165 }
166 }
167
168 pub fn clear_constraint_magnitudes(&mut self) {
169 self.minimum = None;
170 self.maximum = None;
171 self.suggestion_magnitude = None;
172 }
173
174 #[must_use]
175 pub fn is_dynamic(&self) -> bool {
176 matches!(
177 self.scale,
178 UnitScale::Unresolved { .. } | UnitScale::Reference { .. }
179 )
180 }
181
182 #[must_use]
184 pub fn scale_written(&self) -> Option<String> {
185 match &self.scale {
186 UnitScale::Unresolved { written, .. } => Some(written.clone()),
187 UnitScale::Reference { factors, .. } => {
188 if factors.is_empty() {
189 panic!("BUG: Reference scale factors must be non-empty after planning");
190 }
191 Some(format_scale_factors(factors))
192 }
193 UnitScale::Literal(_) | UnitScale::Compound { .. } => None,
194 }
195 }
196
197 #[must_use]
199 pub fn resolved_scale_factors(&self) -> &[(crate::planning::semantics::ScaleTarget, i32)] {
200 match &self.scale {
201 UnitScale::Reference { factors, .. } => factors.as_slice(),
202 UnitScale::Literal(_) | UnitScale::Compound { .. } | UnitScale::Unresolved { .. } => {
203 &[]
204 }
205 }
206 }
207
208 #[must_use]
210 pub fn scale_reference_parts(&self) -> Option<(&[String], &str)> {
211 match &self.scale {
212 UnitScale::Unresolved { segments, name, .. } => {
213 Some((segments.as_slice(), name.as_str()))
214 }
215 UnitScale::Literal(_) | UnitScale::Compound { .. } | UnitScale::Reference { .. } => {
216 None
217 }
218 }
219 }
220
221 #[must_use]
223 pub fn literal_factor(&self) -> Option<&RationalInteger> {
224 match &self.scale {
225 UnitScale::Literal(factor) => Some(factor),
226 UnitScale::Compound { .. }
227 | UnitScale::Unresolved { .. }
228 | UnitScale::Reference { .. } => None,
229 }
230 }
231
232 #[must_use]
235 pub(crate) fn declared_factor(&self) -> Option<&RationalInteger> {
236 match &self.scale {
237 UnitScale::Literal(factor) | UnitScale::Compound { prefix: factor } => Some(factor),
238 UnitScale::Unresolved { .. } | UnitScale::Reference { .. } => None,
239 }
240 }
241
242 #[must_use]
244 pub fn scale_coefficient(&self) -> RationalInteger {
245 match &self.scale {
246 UnitScale::Literal(_) | UnitScale::Compound { .. } | UnitScale::Unresolved { .. } => {
247 rational::rational_one()
248 }
249 UnitScale::Reference { coefficient, .. } => coefficient.clone(),
250 }
251 }
252
253 pub fn require_literal_factor(&self) -> &RationalInteger {
256 self.literal_factor().unwrap_or_else(|| {
257 panic!(
258 "BUG: literal factor required for unit '{}'; planning must keep static paths away from reference-scaled units",
259 self.name
260 )
261 })
262 }
263
264 #[must_use]
269 pub fn same_scale(&self, other: &Self) -> bool {
270 self.scale == other.scale
271 }
272
273 pub fn is_canonical_factor(&self) -> bool {
274 self.literal_factor()
275 .is_some_and(|factor| *factor == rational::rational_one())
276 }
277
278 pub fn is_positive_factor(&self) -> bool {
279 match &self.scale {
280 UnitScale::Literal(factor) | UnitScale::Compound { prefix: factor } => {
281 factor.numer_is_positive()
282 }
283 UnitScale::Unresolved { .. } => true,
284 UnitScale::Reference { coefficient, .. } => coefficient.numer_is_positive(),
285 }
286 }
287
288 pub fn factor_decimal(&self) -> Decimal {
290 rational::RationalInteger::try_to_decimal(self.require_literal_factor())
291 .expect("BUG: measure unit factor must convert to decimal")
292 }
293
294 #[must_use]
295 pub fn minimum_decimal(&self) -> Option<Decimal> {
296 self.minimum.as_ref().map(|bound| {
297 bound
298 .try_to_decimal()
299 .expect("BUG: planned measure unit minimum must convert to decimal")
300 })
301 }
302
303 #[must_use]
304 pub fn maximum_decimal(&self) -> Option<Decimal> {
305 self.maximum.as_ref().map(|bound| {
306 bound
307 .try_to_decimal()
308 .expect("BUG: planned measure unit maximum must convert to decimal")
309 })
310 }
311
312 #[must_use]
313 pub fn suggestion_magnitude_decimal(&self) -> Option<Decimal> {
314 self.suggestion_magnitude.as_ref().map(|bound| {
315 bound
316 .try_to_decimal()
317 .expect("BUG: planned measure unit default must convert to decimal")
318 })
319 }
320
321 #[must_use]
323 pub fn maximum_canonical_decimal(&self) -> Option<Decimal> {
324 self.maximum.as_ref().map(|maximum| {
325 let canonical = rational::checked_mul(maximum, self.require_literal_factor())
326 .expect("BUG: planned measure unit maximum canonical multiply must succeed");
327 canonical
328 .try_to_decimal()
329 .expect("BUG: planned measure unit maximum canonical must convert to decimal")
330 })
331 }
332}
333
334#[derive(Clone, Debug, PartialEq, Eq, Hash)]
335pub struct MeasureUnits(pub Vec<MeasureUnit>);
336
337impl MeasureUnits {
338 pub fn new() -> Self {
339 MeasureUnits(Vec::new())
340 }
341 pub fn get(&self, name: &str) -> Result<&MeasureUnit, String> {
342 self.0.iter().find(|u| u.name == name).ok_or_else(|| {
343 let valid: Vec<&str> = self.0.iter().map(|u| u.name.as_str()).collect();
344 format!(
345 "Unknown unit '{}' for this measure type. Valid units: {}",
346 name,
347 valid.join(", ")
348 )
349 })
350 }
351
352 pub fn iter(&self) -> std::slice::Iter<'_, MeasureUnit> {
353 self.0.iter()
354 }
355 pub fn push(&mut self, u: MeasureUnit) {
356 self.0.push(u);
357 }
358 pub fn is_empty(&self) -> bool {
359 self.0.is_empty()
360 }
361 pub fn len(&self) -> usize {
362 self.0.len()
363 }
364 pub fn map<F: FnMut(MeasureUnit) -> MeasureUnit>(self, f: F) -> Self {
365 MeasureUnits(self.0.into_iter().map(f).collect())
366 }
367}
368
369impl MeasureUnit {
370 pub fn with_decomposition(self, decomposition: BaseMeasureVector) -> Self {
371 Self {
372 decomposition,
373 ..self
374 }
375 }
376 pub fn with_factor(self, factor: RationalInteger) -> Self {
377 match self.scale {
378 UnitScale::Literal(_) | UnitScale::Compound { .. } => Self {
379 scale: UnitScale::Literal(factor),
380 ..self
381 },
382 UnitScale::Unresolved { .. } | UnitScale::Reference { .. } => {
383 panic!(
384 "BUG: with_factor on reference-scaled unit '{}'; use with_reference_scale for compounds that inherit dynamic bases",
385 self.name
386 )
387 }
388 }
389 }
390
391 pub fn with_reference_scale(
394 self,
395 factors: Vec<(crate::planning::semantics::ScaleTarget, i32)>,
396 coefficient: RationalInteger,
397 ) -> Self {
398 let factors = UnitScale::canonicalize_scale_factors(&factors);
399 if factors.is_empty() {
400 panic!(
401 "BUG: with_reference_scale on unit '{}' got an empty factor product; compound resolution must leave a literal scale when all dynamics cancel",
402 self.name
403 );
404 }
405 Self {
406 scale: UnitScale::Reference {
407 factors,
408 coefficient,
409 },
410 ..self
411 }
412 }
413
414 pub fn with_resolved_scale(self, resolved: crate::planning::semantics::ScaleTarget) -> Self {
415 match self.scale {
416 UnitScale::Unresolved { .. } => Self {
417 scale: UnitScale::Reference {
418 factors: vec![(resolved, 1)],
419 coefficient: rational::rational_one(),
420 },
421 ..self
422 },
423 UnitScale::Literal(_) | UnitScale::Compound { .. } | UnitScale::Reference { .. } => {
424 panic!(
425 "BUG: with_resolved_scale on non-unresolved unit '{}'",
426 self.name
427 )
428 }
429 }
430 }
431 pub fn with_derived_measure_factors(self, derived_measure_factors: Vec<(String, i32)>) -> Self {
432 Self {
433 derived_measure_factors,
434 ..self
435 }
436 }
437}
438
439fn format_scale_factors(factors: &[(crate::planning::semantics::ScaleTarget, i32)]) -> String {
440 factors
441 .iter()
442 .map(|(target, exponent)| {
443 if *exponent == 1 {
444 target.to_string()
445 } else {
446 format!("{target}^{exponent}")
447 }
448 })
449 .collect::<Vec<_>>()
450 .join(" * ")
451}
452
453impl Default for MeasureUnits {
454 fn default() -> Self {
455 MeasureUnits::new()
456 }
457}
458
459impl From<Vec<MeasureUnit>> for MeasureUnits {
460 fn from(v: Vec<MeasureUnit>) -> Self {
461 MeasureUnits(v)
462 }
463}
464
465impl<'a> IntoIterator for &'a MeasureUnits {
466 type Item = &'a MeasureUnit;
467 type IntoIter = std::slice::Iter<'a, MeasureUnit>;
468 fn into_iter(self) -> Self::IntoIter {
469 self.0.iter()
470 }
471}
472
473#[derive(Clone, Debug, PartialEq, Eq, Hash)]
474pub struct RatioUnit {
475 pub name: String,
476 pub value: RationalInteger,
477 pub minimum: Option<RationalInteger>,
478 pub maximum: Option<RationalInteger>,
479 pub suggestion_magnitude: Option<RationalInteger>,
480}
481
482impl RatioUnit {
483 pub fn clear_constraint_magnitudes(&mut self) {
484 self.minimum = None;
485 self.maximum = None;
486 self.suggestion_magnitude = None;
487 }
488
489 pub fn value_decimal(&self) -> Decimal {
491 self.value
492 .try_to_decimal()
493 .expect("BUG: ratio unit value must convert to decimal")
494 }
495
496 #[must_use]
497 pub fn minimum_decimal(&self) -> Option<Decimal> {
498 self.minimum.as_ref().map(|bound| {
499 bound
500 .try_to_decimal()
501 .expect("BUG: planned ratio unit minimum must convert to decimal")
502 })
503 }
504
505 #[must_use]
506 pub fn maximum_decimal(&self) -> Option<Decimal> {
507 self.maximum.as_ref().map(|bound| {
508 bound
509 .try_to_decimal()
510 .expect("BUG: planned ratio unit maximum must convert to decimal")
511 })
512 }
513
514 #[must_use]
515 pub fn suggestion_magnitude_decimal(&self) -> Option<Decimal> {
516 self.suggestion_magnitude.as_ref().map(|bound| {
517 bound
518 .try_to_decimal()
519 .expect("BUG: planned ratio unit default must convert to decimal")
520 })
521 }
522
523 #[must_use]
525 pub fn maximum_canonical_decimal(&self) -> Option<Decimal> {
526 self.maximum.as_ref().map(|maximum| {
527 let canonical = rational::checked_mul(maximum, &self.value)
528 .expect("BUG: planned ratio unit maximum canonical multiply must succeed");
529 canonical
530 .try_to_decimal()
531 .expect("BUG: planned ratio unit maximum canonical must convert to decimal")
532 })
533 }
534}
535
536#[derive(Clone, Debug, PartialEq, Eq, Hash)]
537pub struct RatioUnits(pub Vec<RatioUnit>);
538
539impl RatioUnits {
540 pub fn new() -> Self {
541 RatioUnits(Vec::new())
542 }
543 pub fn get(&self, name: &str) -> Result<&RatioUnit, String> {
544 self.0.iter().find(|u| u.name == name).ok_or_else(|| {
545 let valid: Vec<&str> = self.0.iter().map(|u| u.name.as_str()).collect();
546 format!(
547 "Unknown unit '{}' for this ratio type. Valid units: {}",
548 name,
549 valid.join(", ")
550 )
551 })
552 }
553
554 pub fn iter(&self) -> std::slice::Iter<'_, RatioUnit> {
555 self.0.iter()
556 }
557 pub fn push(&mut self, u: RatioUnit) {
558 self.0.push(u);
559 }
560 pub fn is_empty(&self) -> bool {
561 self.0.is_empty()
562 }
563 pub fn len(&self) -> usize {
564 self.0.len()
565 }
566}
567
568impl Default for RatioUnits {
569 fn default() -> Self {
570 RatioUnits::new()
571 }
572}
573
574impl From<Vec<RatioUnit>> for RatioUnits {
575 fn from(v: Vec<RatioUnit>) -> Self {
576 RatioUnits(v)
577 }
578}
579
580impl<'a> IntoIterator for &'a RatioUnits {
581 type Item = &'a RatioUnit;
582 type IntoIter = std::slice::Iter<'a, RatioUnit>;
583 fn into_iter(self) -> Self::IntoIter {
584 self.0.iter()
585 }
586}
587
588#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
593#[serde(rename_all = "lowercase")]
594pub enum BooleanValue {
595 True,
596 False,
597 Yes,
598 No,
599}
600
601impl From<BooleanValue> for bool {
602 fn from(value: BooleanValue) -> bool {
603 matches!(value, BooleanValue::True | BooleanValue::Yes)
604 }
605}
606
607impl From<&BooleanValue> for bool {
608 fn from(value: &BooleanValue) -> bool {
609 (*value).into() }
611}
612
613impl From<bool> for BooleanValue {
614 fn from(value: bool) -> BooleanValue {
615 if value {
616 BooleanValue::True
617 } else {
618 BooleanValue::False
619 }
620 }
621}
622
623impl std::ops::Not for BooleanValue {
624 type Output = BooleanValue;
625
626 fn not(self) -> Self::Output {
627 if self.into() {
628 BooleanValue::False
629 } else {
630 BooleanValue::True
631 }
632 }
633}
634
635impl std::ops::Not for &BooleanValue {
636 type Output = BooleanValue;
637
638 fn not(self) -> Self::Output {
639 if (*self).into() {
640 BooleanValue::False
641 } else {
642 BooleanValue::True
643 }
644 }
645}
646
647impl std::str::FromStr for BooleanValue {
648 type Err = String;
649
650 fn from_str(s: &str) -> Result<Self, Self::Err> {
651 match s.trim().to_lowercase().as_str() {
652 "true" => Ok(BooleanValue::True),
653 "false" => Ok(BooleanValue::False),
654 "yes" => Ok(BooleanValue::Yes),
655 "no" => Ok(BooleanValue::No),
656 _ => Err(format!("Invalid boolean: '{}'", s)),
657 }
658 }
659}
660
661impl BooleanValue {
662 #[must_use]
663 pub fn as_str(&self) -> &'static str {
664 match self {
665 BooleanValue::True => "true",
666 BooleanValue::False => "false",
667 BooleanValue::Yes => "yes",
668 BooleanValue::No => "no",
669 }
670 }
671}
672
673impl fmt::Display for BooleanValue {
674 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
675 write!(f, "{}", self.as_str())
676 }
677}
678
679#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
681pub struct TimezoneValue {
682 pub offset_minutes: i16,
683}
684
685const MAX_TIMEZONE_OFFSET_MINUTES: i16 = 23 * 60 + 59;
686
687impl TimezoneValue {
688 pub fn from_offset_seconds(seconds: i32) -> Option<Self> {
690 if seconds % 60 != 0 {
691 return None;
692 }
693 let offset_minutes = i16::try_from(seconds / 60).ok()?;
694 (offset_minutes.unsigned_abs() <= MAX_TIMEZONE_OFFSET_MINUTES.unsigned_abs())
695 .then_some(Self { offset_minutes })
696 }
697
698 pub fn offset_seconds(&self) -> i32 {
699 i32::from(self.offset_minutes) * 60
700 }
701}
702
703impl fmt::Display for TimezoneValue {
704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
705 if self.offset_minutes == 0 {
706 return write!(f, "Z");
707 }
708 let sign = if self.offset_minutes > 0 { "+" } else { "-" };
709 let magnitude = self.offset_minutes.unsigned_abs();
710 write!(f, "{}{:02}:{:02}", sign, magnitude / 60, magnitude % 60)
711 }
712}
713
714impl Serialize for TimezoneValue {
715 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
716 serializer.serialize_str(&self.to_string())
717 }
718}
719
720impl<'de> Deserialize<'de> for TimezoneValue {
721 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
722 let s = String::deserialize(deserializer)?;
723 Self::from_str(&s).map_err(serde::de::Error::custom)
724 }
725}
726
727impl FromStr for TimezoneValue {
728 type Err = String;
729
730 fn from_str(s: &str) -> Result<Self, Self::Err> {
731 let trimmed = s.trim();
732 if trimmed == "Z" || trimmed == "z" {
733 return Ok(Self { offset_minutes: 0 });
734 }
735 if trimmed.len() == 6
736 && (trimmed.starts_with('+') || trimmed.starts_with('-'))
737 && trimmed.as_bytes()[3] == b':'
738 {
739 let hours: i16 = trimmed[1..3]
740 .parse()
741 .map_err(|_| format!("Invalid timezone format: '{s}'"))?;
742 let minutes: i16 = trimmed[4..6]
743 .parse()
744 .map_err(|_| format!("Invalid timezone format: '{s}'"))?;
745 if !(0..=23).contains(&hours) || !(0..60).contains(&minutes) {
746 return Err(format!("Invalid timezone format: '{s}'"));
747 }
748 let magnitude = hours * 60 + minutes;
749 let offset_minutes = if trimmed.starts_with('-') {
750 -magnitude
751 } else {
752 magnitude
753 };
754 return Ok(Self { offset_minutes });
755 }
756 Err(format!("Invalid timezone format: '{s}'"))
757 }
758}
759
760#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
761pub struct TimeValue {
762 pub hour: u8,
763 pub minute: u8,
764 pub second: u8,
765 pub microsecond: u32,
766 pub timezone: Option<TimezoneValue>,
767}
768
769impl Serialize for TimeValue {
770 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
771 serializer.serialize_str(&self.to_string())
772 }
773}
774
775impl<'de> Deserialize<'de> for TimeValue {
776 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
777 let s = String::deserialize(deserializer)?;
778 Self::from_str(&s).map_err(serde::de::Error::custom)
779 }
780}
781
782impl fmt::Display for TimeValue {
783 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
784 write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)?;
785 if self.microsecond != 0 {
786 write!(f, ".{:06}", self.microsecond)?;
787 }
788 if let Some(timezone) = &self.timezone {
789 write!(f, "{}", timezone)?;
790 }
791 Ok(())
792 }
793}
794
795#[derive(
796 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
797)]
798#[serde(rename_all = "snake_case")]
799pub enum DateGranularity {
800 Year,
801 YearMonth,
802 IsoWeek {
806 iso_year: i32,
807 week: u32,
808 },
809 #[default]
810 Full,
811 DateTime,
812}
813
814#[derive(Debug, Clone)]
815pub struct DateTimeValue {
816 pub year: i32,
817 pub month: u32,
818 pub day: u32,
819 pub hour: u32,
820 pub minute: u32,
821 pub second: u32,
822 pub microsecond: u32,
823 pub timezone: Option<TimezoneValue>,
824 pub granularity: DateGranularity,
825}
826
827impl Serialize for DateTimeValue {
828 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
829 serializer.serialize_str(&self.to_string())
830 }
831}
832
833impl<'de> Deserialize<'de> for DateTimeValue {
834 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
835 let s = String::deserialize(deserializer)?;
836 Self::from_str(&s).map_err(serde::de::Error::custom)
837 }
838}
839
840impl PartialEq for DateTimeValue {
841 fn eq(&self, other: &Self) -> bool {
842 self.year == other.year
843 && self.month == other.month
844 && self.day == other.day
845 && self.hour == other.hour
846 && self.minute == other.minute
847 && self.second == other.second
848 && self.microsecond == other.microsecond
849 && self.timezone == other.timezone
850 }
851}
852
853impl Eq for DateTimeValue {}
854
855impl PartialOrd for DateTimeValue {
856 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
857 Some(self.cmp(other))
858 }
859}
860
861impl Ord for DateTimeValue {
862 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
863 self.year
864 .cmp(&other.year)
865 .then_with(|| self.month.cmp(&other.month))
866 .then_with(|| self.day.cmp(&other.day))
867 .then_with(|| self.hour.cmp(&other.hour))
868 .then_with(|| self.minute.cmp(&other.minute))
869 .then_with(|| self.second.cmp(&other.second))
870 .then_with(|| self.microsecond.cmp(&other.microsecond))
871 .then_with(|| self.timezone.cmp(&other.timezone))
872 }
873}
874
875impl std::hash::Hash for DateTimeValue {
876 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
877 self.year.hash(state);
878 self.month.hash(state);
879 self.day.hash(state);
880 self.hour.hash(state);
881 self.minute.hash(state);
882 self.second.hash(state);
883 self.microsecond.hash(state);
884 self.timezone.hash(state);
885 }
886}
887
888impl DateTimeValue {
889 pub fn now() -> Self {
890 let now = chrono::Local::now();
891 let offset_secs = now.offset().local_minus_utc();
892 Self {
893 year: now.year(),
894 month: now.month(),
895 day: now.day(),
896 hour: now.time().hour(),
897 minute: now.time().minute(),
898 second: now.time().second(),
899 microsecond: now.time().nanosecond() / 1000 % 1_000_000,
900 timezone: Some(TimezoneValue::from_offset_seconds(offset_secs).expect(
901 "BUG: current local UTC offsets are whole minutes within ±23:59 since 1972",
902 )),
903 granularity: DateGranularity::DateTime,
904 }
905 }
906
907 fn parse_iso_week(s: &str) -> Option<Self> {
908 let parts: Vec<&str> = s.split("-W").collect();
909 if parts.len() != 2 {
910 return None;
911 }
912 let iso_year: i32 = parts[0].parse().ok()?;
913 let week: u32 = parts[1].parse().ok()?;
914 if week == 0 || week > 53 {
915 return None;
916 }
917 let date = chrono::NaiveDate::from_isoywd_opt(iso_year, week, chrono::Weekday::Mon)?;
918 Some(Self {
919 year: date.year(),
920 month: date.month(),
921 day: date.day(),
922 hour: 0,
923 minute: 0,
924 second: 0,
925 microsecond: 0,
926 timezone: None,
927 granularity: DateGranularity::IsoWeek { iso_year, week },
928 })
929 }
930}
931
932impl fmt::Display for DateTimeValue {
933 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
934 match self.granularity {
935 DateGranularity::Year => write!(f, "{:04}", self.year),
936 DateGranularity::YearMonth => write!(f, "{:04}-{:02}", self.year, self.month),
937 DateGranularity::IsoWeek { iso_year, week } => {
938 write!(f, "{:04}-W{:02}", iso_year, week)
939 }
940 DateGranularity::Full => {
941 write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
942 }
943 DateGranularity::DateTime => {
944 write!(
945 f,
946 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
947 self.year, self.month, self.day, self.hour, self.minute, self.second
948 )?;
949 if self.microsecond != 0 {
950 write!(f, ".{:06}", self.microsecond)?;
951 }
952 if let Some(tz) = &self.timezone {
953 write!(f, "{}", tz)?;
954 }
955 Ok(())
956 }
957 }
958 }
959}
960
961#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
966#[serde(rename_all = "snake_case")]
967pub enum Value {
968 Number(Decimal),
969 NumberWithUnit(Decimal, String),
970 Text(String),
971 Date(DateTimeValue),
972 Time(TimeValue),
973 Boolean(BooleanValue),
974 Range(Box<Value>, Box<Value>),
975}
976
977impl fmt::Display for Value {
978 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
979 match self {
980 Value::Number(n) => write!(f, "{}", n),
981 Value::Text(s) => write!(f, "{}", s),
982 Value::Date(dt) => write!(f, "{}", dt),
983 Value::Boolean(b) => write!(f, "{}", b),
984 Value::Time(time) => write!(f, "{}", time),
985 Value::NumberWithUnit(n, u) => match u.as_str() {
986 "percent" => {
987 let norm = n.normalize();
988 let s = if norm.fract().is_zero() {
989 norm.trunc().to_string()
990 } else {
991 norm.to_string()
992 };
993 write!(f, "{}%", s)
994 }
995 "permille" => {
996 let norm = n.normalize();
997 let s = if norm.fract().is_zero() {
998 norm.trunc().to_string()
999 } else {
1000 norm.to_string()
1001 };
1002 write!(f, "{}%%", s)
1003 }
1004 unit => {
1005 let norm = n.normalize();
1006 let s = if norm.fract().is_zero() {
1007 norm.trunc().to_string()
1008 } else {
1009 norm.to_string()
1010 };
1011 write!(f, "{} {}", s, unit)
1012 }
1013 },
1014 Value::Range(left, right) => write!(f, "{}...{}", left, right),
1015 }
1016 }
1017}
1018
1019impl std::str::FromStr for DateTimeValue {
1024 type Err = String;
1025
1026 fn from_str(s: &str) -> Result<Self, Self::Err> {
1027 if let Ok(dt) = s.parse::<chrono::DateTime<chrono::FixedOffset>>() {
1028 let timezone = TimezoneValue::from_offset_seconds(dt.offset().local_minus_utc())
1029 .ok_or_else(|| format!("Invalid timezone offset in date: '{}'", s))?;
1030 let microsecond = dt.nanosecond() / 1000 % 1_000_000;
1031 return Ok(DateTimeValue {
1032 year: dt.year(),
1033 month: dt.month(),
1034 day: dt.day(),
1035 hour: dt.hour(),
1036 minute: dt.minute(),
1037 second: dt.second(),
1038 microsecond,
1039 timezone: Some(timezone),
1040 granularity: DateGranularity::DateTime,
1041 });
1042 }
1043 if let Ok(dt) = s.parse::<chrono::NaiveDateTime>() {
1044 let microsecond = dt.nanosecond() / 1000 % 1_000_000;
1045 return Ok(DateTimeValue {
1046 year: dt.year(),
1047 month: dt.month(),
1048 day: dt.day(),
1049 hour: dt.hour(),
1050 minute: dt.minute(),
1051 second: dt.second(),
1052 microsecond,
1053 timezone: None,
1054 granularity: DateGranularity::DateTime,
1055 });
1056 }
1057 if let Ok(d) = s.parse::<chrono::NaiveDate>() {
1058 return Ok(DateTimeValue {
1059 year: d.year(),
1060 month: d.month(),
1061 day: d.day(),
1062 hour: 0,
1063 minute: 0,
1064 second: 0,
1065 microsecond: 0,
1066 timezone: None,
1067 granularity: DateGranularity::Full,
1068 });
1069 }
1070 if let Some(week_val) = Self::parse_iso_week(s) {
1071 return Ok(week_val);
1072 }
1073 if let Ok(ym) = chrono::NaiveDate::parse_from_str(&format!("{}-01", s), "%Y-%m-%d") {
1074 return Ok(Self {
1075 year: ym.year(),
1076 month: ym.month(),
1077 day: 1,
1078 hour: 0,
1079 minute: 0,
1080 second: 0,
1081 microsecond: 0,
1082 timezone: None,
1083 granularity: DateGranularity::YearMonth,
1084 });
1085 }
1086 if let Ok(year) = s.parse::<i32>() {
1087 if (1..=9999).contains(&year) {
1088 return Ok(Self {
1089 year,
1090 month: 1,
1091 day: 1,
1092 hour: 0,
1093 minute: 0,
1094 second: 0,
1095 microsecond: 0,
1096 timezone: None,
1097 granularity: DateGranularity::Year,
1098 });
1099 }
1100 }
1101 Err(format!("Invalid date format: '{}'", s))
1102 }
1103}
1104
1105impl std::str::FromStr for TimeValue {
1106 type Err = String;
1107
1108 fn from_str(s: &str) -> Result<Self, Self::Err> {
1109 let trimmed = s.trim();
1110
1111 let (time_text, timezone) = if trimmed.ends_with('Z') || trimmed.ends_with('z') {
1112 (
1113 &trimmed[..trimmed.len() - 1],
1114 Some(TimezoneValue { offset_minutes: 0 }),
1115 )
1116 } else if let Some(first) = trimmed.chars().next() {
1117 let after_first = first.len_utf8();
1118 if let Some(sign_index) = trimmed[after_first..]
1119 .rfind(['+', '-'])
1120 .map(|index| index + after_first)
1121 {
1122 let timezone_text = &trimmed[sign_index..];
1123 if timezone_text.len() == 6
1124 && (timezone_text.starts_with('+') || timezone_text.starts_with('-'))
1125 && timezone_text.as_bytes()[3] == b':'
1126 {
1127 let timezone = TimezoneValue::from_str(timezone_text)
1128 .map_err(|_| format!("Invalid time format: '{s}'"))?;
1129 (&trimmed[..sign_index], Some(timezone))
1130 } else {
1131 (trimmed, None)
1132 }
1133 } else {
1134 (trimmed, None)
1135 }
1136 } else {
1137 (trimmed, None)
1138 };
1139
1140 if let Ok(t) = chrono::NaiveTime::parse_from_str(time_text, "%H:%M:%S%.f") {
1141 return Ok(TimeValue {
1142 hour: t.hour() as u8,
1143 minute: t.minute() as u8,
1144 second: t.second() as u8,
1145 microsecond: t.nanosecond() / 1000 % 1_000_000,
1146 timezone,
1147 });
1148 }
1149 if let Ok(t) = chrono::NaiveTime::parse_from_str(time_text, "%H:%M:%S") {
1150 return Ok(TimeValue {
1151 hour: t.hour() as u8,
1152 minute: t.minute() as u8,
1153 second: t.second() as u8,
1154 microsecond: 0,
1155 timezone,
1156 });
1157 }
1158 if let Ok(t) = chrono::NaiveTime::parse_from_str(time_text, "%H:%M") {
1159 return Ok(TimeValue {
1160 hour: t.hour() as u8,
1161 minute: t.minute() as u8,
1162 second: 0,
1163 microsecond: 0,
1164 timezone,
1165 });
1166 }
1167 Err(format!("Invalid time format: '{}'", s))
1168 }
1169}
1170
1171pub(crate) struct NumberLiteral(pub Decimal);
1176
1177impl std::str::FromStr for NumberLiteral {
1178 type Err = String;
1179
1180 fn from_str(s: &str) -> Result<Self, Self::Err> {
1181 let clean = s.trim().replace('_', "");
1182 if let Some(dot) = clean.find('.') {
1183 let frac = &clean[dot + 1..];
1184 let frac_digits = frac.chars().take_while(|c| c.is_ascii_digit()).count();
1185 if frac_digits > Decimal::MAX_SCALE as usize {
1186 return Err(format!(
1187 "Invalid number '{}': too many fractional digits (max {})",
1188 s,
1189 Decimal::MAX_SCALE
1190 ));
1191 }
1192 }
1193 Decimal::from_str(&clean)
1194 .map_err(|_| format!("Invalid number: '{}'", s))
1195 .map(NumberLiteral)
1196 }
1197}
1198
1199pub(crate) struct TextLiteral(pub String);
1201
1202impl std::str::FromStr for TextLiteral {
1203 type Err = String;
1204
1205 fn from_str(s: &str) -> Result<Self, Self::Err> {
1206 if s.len() > crate::limits::MAX_TEXT_VALUE_LENGTH {
1207 return Err(format!(
1208 "Text value exceeds maximum length (max {} characters)",
1209 crate::limits::MAX_TEXT_VALUE_LENGTH
1210 ));
1211 }
1212 Ok(TextLiteral(s.to_string()))
1213 }
1214}
1215
1216pub(crate) struct NumberWithUnit(pub Decimal, pub String);
1218
1219impl std::str::FromStr for NumberWithUnit {
1220 type Err = String;
1221
1222 fn from_str(s: &str) -> Result<Self, Self::Err> {
1223 let trimmed = s.trim();
1224 if trimmed.is_empty() {
1225 return Err(
1226 "Measure value cannot be empty. Use a number followed by a unit (e.g. '10 eur')."
1227 .to_string(),
1228 );
1229 }
1230
1231 let mut parts = trimmed.split_whitespace();
1232 let number_part = parts
1233 .next()
1234 .expect("split_whitespace yields >=1 token after non-empty guard");
1235 let unit_part = parts.next().ok_or_else(|| {
1236 format!(
1237 "Measure value must include a unit (e.g. '{} eur').",
1238 number_part
1239 )
1240 })?;
1241 if parts.next().is_some() {
1242 return Err(format!(
1243 "Invalid measure value: '{}'. Expected exactly '<number> <unit>', got extra tokens.",
1244 s
1245 ));
1246 }
1247 let n = number_part
1248 .parse::<NumberLiteral>()
1249 .map_err(|_| format!("Invalid measure: '{}'", s))?
1250 .0;
1251 Ok(NumberWithUnit(n, unit_part.to_string()))
1252 }
1253}
1254
1255#[derive(Debug, Clone, PartialEq, Eq)]
1280pub(crate) enum RatioLiteral {
1281 Bare(Decimal),
1282 Percent(Decimal),
1283 Permille(Decimal),
1284 Named { value: Decimal, unit: String },
1285}
1286
1287impl std::str::FromStr for RatioLiteral {
1288 type Err = String;
1289
1290 fn from_str(s: &str) -> Result<Self, Self::Err> {
1291 let trimmed = s.trim();
1292 if trimmed.is_empty() {
1293 return Err(
1294 "Ratio value cannot be empty. Use a number, optionally followed by '%', '%%', or a unit name (e.g. '0.5', '50%', '25%%', '50 percent')."
1295 .to_string(),
1296 );
1297 }
1298
1299 let mut parts = trimmed.split_whitespace();
1300 let first = parts
1301 .next()
1302 .expect("split_whitespace yields >=1 token after non-empty guard");
1303 let second = parts.next();
1304 if parts.next().is_some() {
1305 return Err(format!(
1306 "Invalid ratio value: '{}'. Expected '<number>', '<number>%', '<number>%%', or '<number> <unit>'.",
1307 s
1308 ));
1309 }
1310
1311 match second {
1312 None => {
1314 if let Some(rest) = first.strip_suffix("%%") {
1315 if rest.is_empty() {
1316 return Err(format!(
1317 "Invalid ratio value: '{}'. '%%' must follow a number (e.g. '25%%').",
1318 s
1319 ));
1320 }
1321 let n = rest
1322 .parse::<NumberLiteral>()
1323 .map_err(|_| {
1324 format!(
1325 "Invalid ratio value: '{}'. '{}' is not a valid number before '%%'.",
1326 s, rest
1327 )
1328 })?
1329 .0;
1330 return Ok(RatioLiteral::Permille(n));
1331 }
1332 if let Some(rest) = first.strip_suffix('%') {
1333 if rest.is_empty() {
1334 return Err(format!(
1335 "Invalid ratio value: '{}'. '%' must follow a number (e.g. '50%').",
1336 s
1337 ));
1338 }
1339 let n = rest
1340 .parse::<NumberLiteral>()
1341 .map_err(|_| {
1342 format!(
1343 "Invalid ratio value: '{}'. '{}' is not a valid number before '%'.",
1344 s, rest
1345 )
1346 })?
1347 .0;
1348 return Ok(RatioLiteral::Percent(n));
1349 }
1350 let n = first.parse::<NumberLiteral>().map_err(|_| {
1351 format!(
1352 "Invalid ratio value: '{}'. Must be a number, '<n>%', '<n>%%', '<n> percent', '<n> permille', or '<n> <unit>'.",
1353 s
1354 )
1355 })?.0;
1356 Ok(RatioLiteral::Bare(n))
1357 }
1358 Some(unit) => {
1360 if unit == "%" || unit == "%%" {
1361 return Err(format!(
1362 "Invalid ratio value: '{}'. '{}' must be glued to the number (e.g. '{}{}'), not separated by whitespace.",
1363 s, unit, first, unit
1364 ));
1365 }
1366 let n = first
1367 .parse::<NumberLiteral>()
1368 .map_err(|_| {
1369 format!(
1370 "Invalid ratio value: '{}'. '{}' is not a valid number.",
1371 s, first
1372 )
1373 })?
1374 .0;
1375 Ok(RatioLiteral::Named {
1376 value: n,
1377 unit: unit.to_string(),
1378 })
1379 }
1380 }
1381 }
1382}
1383
1384#[cfg(test)]
1385mod tests {
1386 use super::{BooleanValue, TimeValue, TimezoneValue};
1387 use std::str::FromStr;
1388
1389 #[test]
1390 fn timezone_value_round_trips_every_signed_offset() {
1391 for text in [
1392 "-00:30", "-03:30", "-09:30", "+05:45", "+00:30", "-12:00", "+14:00",
1393 ] {
1394 let timezone = TimezoneValue::from_str(text).expect("valid offset");
1395 assert_eq!(timezone.to_string(), text);
1396 }
1397 assert_eq!(TimezoneValue::from_str("+00:00").unwrap().to_string(), "Z");
1398 assert_eq!(TimezoneValue::from_str("-00:00").unwrap().to_string(), "Z");
1399 }
1400
1401 #[test]
1402 fn timezone_value_orders_by_signed_offset() {
1403 let ordered = [
1404 "-09:30", "-03:30", "-03:00", "-00:30", "Z", "+00:30", "+05:45",
1405 ]
1406 .map(|text| TimezoneValue::from_str(text).expect("valid offset"));
1407 for pair in ordered.windows(2) {
1408 assert!(
1409 pair[0] < pair[1],
1410 "{} must order before {}",
1411 pair[0],
1412 pair[1]
1413 );
1414 }
1415 }
1416
1417 #[test]
1418 fn time_value_rejects_multibyte_first_char() {
1419 for invalid in ["é", "é10:00", "日12:00", "é10:00+01:00", "€+01:00"] {
1420 assert!(
1421 TimeValue::from_str(invalid).is_err(),
1422 "'{invalid}' must not parse as time"
1423 );
1424 }
1425 }
1426
1427 #[test]
1428 fn time_value_parses_timezone_after_ascii_time() {
1429 let time = TimeValue::from_str("10:30:00+01:00").expect("valid time with offset");
1430 assert_eq!(time.hour, 10);
1431 assert_eq!(time.minute, 30);
1432 let timezone = time.timezone.expect("offset parsed");
1433 assert_eq!(timezone.offset_minutes, 60);
1434 }
1435
1436 #[test]
1437 fn boolean_value_rejects_accept_and_reject_strings() {
1438 for invalid in ["accept", "reject"] {
1439 assert!(
1440 BooleanValue::from_str(invalid).is_err(),
1441 "'{invalid}' must not parse as boolean"
1442 );
1443 }
1444 }
1445
1446 #[test]
1447 #[should_panic(expected = "BUG: literal factor required")]
1448 fn require_literal_factor_panics_on_reference_scale() {
1449 let unit = super::MeasureUnit::from_reference(
1450 "gbp".to_string(),
1451 "rate".to_string(),
1452 Vec::new(),
1453 "rate".to_string(),
1454 );
1455 let _ = unit.require_literal_factor();
1456 }
1457}