cadmpeg-ir 0.6.2

CAD data model, validation, diffing, and codec API for cadmpeg.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
// SPDX-License-Identifier: Apache-2.0
//! Checked finite scalar domains.
//!
//! Subset conversions preserve values. Restricting a domain requires `TryFrom`:
//!
//! ```
//! use cadmpeg_ir::scalar::{Length, NonNegativeLength, NonZeroLength, PositiveLength};
//! let positive = PositiveLength::new(2.0).unwrap();
//! let nonzero = NonZeroLength::from(positive);
//! let length = Length::from(nonzero);
//! assert_eq!(PositiveLength::try_from(length).unwrap(), positive);
//! assert_eq!(Length::from(length), length);
//! let identity: Result<Length, std::convert::Infallible> = Length::try_from(length);
//! let widening: Result<Length, std::convert::Infallible> = Length::try_from(positive);
//! assert_eq!(identity.unwrap(), widening.unwrap());
//! assert_eq!(NonNegativeLength::from(positive).get(), 2.0);
//! ```
//!
//! A signed nonzero length cannot become positive without a check:
//!
//! ```compile_fail
//! use cadmpeg_ir::scalar::{NonZeroLength, PositiveLength};
//! let _: PositiveLength = NonZeroLength::new(-2.0).unwrap().into();
//! ```
//!
//! A finite angle or real cannot become positive without a check either:
//!
//! ```compile_fail
//! use cadmpeg_ir::scalar::{Angle, PositiveAngle};
//! let _: PositiveAngle = Angle::ZERO.into();
//! ```
//!
//! ```compile_fail
//! use cadmpeg_ir::scalar::{FiniteReal, PositiveReal};
//! let _: PositiveReal = FiniteReal::new(-1.0).unwrap().into();
//! ```
//!
//! Overlapping domains have no infallible conversion in either direction:
//!
//! ```compile_fail
//! use cadmpeg_ir::scalar::{NonNegativeLength, NonZeroLength};
//! let _: NonNegativeLength = NonZeroLength::new(-2.0).unwrap().into();
//! ```
//!
//! ```compile_fail
//! use cadmpeg_ir::scalar::{NonNegativeLength, NonZeroLength};
//! let _: NonZeroLength = NonNegativeLength::new(0.0).unwrap().into();
//! ```
//!
//! Equal numerical restrictions do not permit conversions between quantity families:
//!
//! ```compile_fail
//! use cadmpeg_ir::scalar::{PositiveAngle, PositiveLength};
//! let _: PositiveAngle = PositiveLength::new(2.0).unwrap().into();
//! ```
//!
//! ```compile_fail
//! use cadmpeg_ir::scalar::{PositiveLength, PositiveReal};
//! let _: PositiveReal = PositiveLength::new(2.0).unwrap().into();
//! ```
//!
//! A dimensionless value takes a quantity family only through a named assignment
//! that its caller's context justifies:
//!
//! ```compile_fail
//! use cadmpeg_ir::scalar::{FiniteReal, Length};
//! let _: Length = FiniteReal::ZERO.into();
//! ```
//!
//! ```
//! use cadmpeg_ir::scalar::{Angle, FiniteReal, Length};
//! let value = FiniteReal::new(-2.5).unwrap();
//! assert_eq!(Length::from_assigned_real(value).get(), -2.5);
//! assert_eq!(Angle::from_assigned_real(value).get(), -2.5);
//! ```

#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// A finite IEEE-754 binary32 value in its source precision.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(transparent)]
pub struct FiniteBinary32(f32);

impl FiniteBinary32 {
    /// Zero in source precision.
    pub const ZERO: Self = Self(0.0);
    /// One in source precision.
    pub const ONE: Self = Self(1.0);

    /// Admit a finite binary32 value.
    #[must_use]
    pub fn new(value: f32) -> Option<Self> {
        value.is_finite().then_some(Self(value))
    }

    /// Return the admitted value in its source precision.
    #[must_use]
    pub const fn get(self) -> f32 {
        self.0
    }
}

impl<'de> Deserialize<'de> for FiniteBinary32 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::new(f32::deserialize(deserializer)?)
            .ok_or_else(|| serde::de::Error::custom("FiniteBinary32 must be finite"))
    }
}

impl TryFrom<f32> for FiniteBinary32 {
    type Error = &'static str;

    fn try_from(value: f32) -> Result<Self, Self::Error> {
        Self::new(value).ok_or("FiniteBinary32 must be finite")
    }
}

impl From<FiniteBinary32> for f32 {
    fn from(value: FiniteBinary32) -> Self {
        value.get()
    }
}

impl From<FiniteBinary32> for FiniteReal {
    /// Widen an admitted finite binary32 value without another admission.
    fn from(value: FiniteBinary32) -> Self {
        Self(f64::from(value.get()))
    }
}

/// A finite binary32 fraction in the closed unit interval.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(transparent)]
pub struct UnitBinary32(f32);

impl UnitBinary32 {
    /// Admit a binary32 fraction in the closed unit interval.
    #[must_use]
    pub fn new(value: f32) -> Option<Self> {
        (0.0..=1.0).contains(&value).then_some(Self(value))
    }

    /// Return the admitted value in its source precision.
    #[must_use]
    pub const fn get(self) -> f32 {
        self.0
    }
}

impl<'de> Deserialize<'de> for UnitBinary32 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::new(f32::deserialize(deserializer)?)
            .ok_or_else(|| serde::de::Error::custom("UnitBinary32 must be in [0, 1]"))
    }
}

impl TryFrom<f32> for UnitBinary32 {
    type Error = &'static str;

    fn try_from(value: f32) -> Result<Self, Self::Error> {
        Self::new(value).ok_or("UnitBinary32 must be in [0, 1]")
    }
}

impl From<UnitBinary32> for f32 {
    fn from(value: UnitBinary32) -> Self {
        value.get()
    }
}

/// A positive value in a native signed 64-bit integer lane.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "i64", into = "i64")]
pub struct PositiveI64(i64);

impl PositiveI64 {
    /// Admit a positive signed 64-bit integer.
    pub const fn new(value: i64) -> Option<Self> {
        if value > 0 {
            Some(Self(value))
        } else {
            None
        }
    }

    /// Return the signed 64-bit integer.
    pub const fn get(&self) -> i64 {
        self.0
    }
}

impl TryFrom<i64> for PositiveI64 {
    type Error = String;

    fn try_from(value: i64) -> Result<Self, Self::Error> {
        Self::new(value).ok_or_else(|| format!("PositiveI64 must be positive, got {value}"))
    }
}

impl From<PositiveI64> for i64 {
    fn from(value: PositiveI64) -> Self {
        value.get()
    }
}

macro_rules! checked_scalar {
    ($(#[$attribute:meta])* $name:ident, $value:ident, $condition:expr, $error:literal) => {
        $(#[$attribute])*
        #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize)]
        #[cfg_attr(feature = "schema", derive(JsonSchema))]
        #[serde(transparent)]
        pub struct $name(f64);
        rewrite_scalar!($name);

        impl $name {
            /// Admits a value within the scalar's domain.
            pub const fn new($value: f64) -> Option<Self> {
                if $value.is_finite() && $condition { Some(Self($value)) } else { None }
            }

            /// Returns the scalar value.
            pub const fn get(self) -> f64 {
                self.0
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where D: serde::Deserializer<'de>,
            {
                Self::new(f64::deserialize(deserializer)?)
                    .ok_or_else(|| serde::de::Error::custom($error))
            }
        }

        impl TryFrom<f64> for $name {
            type Error = &'static str;

            fn try_from(value: f64) -> Result<Self, Self::Error> {
                Self::new(value).ok_or($error)
            }
        }

        impl From<$name> for f64 {
            fn from(value: $name) -> Self { value.get() }
        }
    };
}

checked_scalar!(
    /// A finite length in canonical millimeters.
    Length, value, true, "Length must be finite"
);
checked_scalar!(
    /// A finite signed angle in canonical radians.
    #[derive(Default)]
    Angle, value, true, "Angle must be finite"
);
checked_scalar!(
    /// A positive finite length in canonical millimeters.
    PositiveLength, value, value > 0.0, "PositiveLength must be positive and finite"
);
checked_scalar!(
    /// A finite nonzero signed length in canonical millimeters.
    NonZeroLength, value, value != 0.0, "NonZeroLength must be finite and nonzero"
);
checked_scalar!(
    /// A nonnegative finite length in canonical millimeters.
    NonNegativeLength, value, value >= 0.0, "NonNegativeLength must be nonnegative and finite"
);
checked_scalar!(
    /// A finite angle strictly between negative and positive half-pi radians.
    SlopeAngle, value, value.abs() < std::f64::consts::FRAC_PI_2,
    "SlopeAngle must be finite and strictly between -pi/2 and pi/2"
);
checked_scalar!(
    /// A finite angle strictly between zero and pi radians.
    InteriorAngle, value, value > 0.0 && value < std::f64::consts::PI,
    "InteriorAngle must be finite and strictly between zero and pi"
);
checked_scalar!(
    /// A positive finite angle in canonical radians.
    PositiveAngle, value, value > 0.0, "PositiveAngle must be positive and finite"
);
checked_scalar!(
    /// A finite nonzero signed angle in canonical radians.
    NonZeroAngle, value, value != 0.0, "NonZeroAngle must be finite and nonzero"
);
checked_scalar!(
    /// A finite dimensionless scalar.
    FiniteReal, value, true, "FiniteReal must be finite"
);

impl FiniteReal {
    /// Negative one in a finite scalar lane.
    pub const NEG_ONE: Self = Self(-1.0);
}
checked_scalar!(
    /// A positive finite dimensionless scalar.
    PositiveReal, value, value > 0.0, "PositiveReal must be positive and finite"
);
checked_scalar!(
    /// A nonnegative finite dimensionless scalar.
    NonNegativeReal, value, value >= 0.0, "NonNegativeReal must be nonnegative and finite"
);

checked_scalar!(
    /// A finite nonzero signed dimensionless scalar.
    NonZeroReal, value, value != 0.0, "NonZeroReal must be finite and nonzero"
);
checked_scalar!(
    /// A finite fraction in the closed interval from zero to one.
    Fraction, value, value >= 0.0 && value <= 1.0, "Fraction must be between zero and one"
);
checked_scalar!(
    /// A finite dimensionless scale of at least one. The product of a nonzero
    /// value and this scale has a magnitude not below the value's, so it is
    /// not zero.
    Magnification, value, value >= 1.0, "Magnification must be finite and at least one"
);

impl Length {
    /// Zero in canonical units.
    pub const ZERO: Self = Self(0.0);
}

impl Angle {
    /// One full turn in radians.
    pub const FULL_TURN: Self = Self(std::f64::consts::TAU);
    /// One quarter turn in radians.
    pub const QUARTER_TURN: Self = Self(std::f64::consts::FRAC_PI_2);
    /// One half turn in radians.
    pub const HALF_TURN: Self = Self(std::f64::consts::PI);
    /// Three quarter turns in radians.
    pub const THREE_QUARTER_TURN: Self = Self(3.0 * std::f64::consts::FRAC_PI_2);
    /// Zero in canonical units.
    pub const ZERO: Self = Self(0.0);
}

impl NonNegativeLength {
    /// Zero in canonical units.
    pub const ZERO: Self = Self(0.0);

    /// Assign a finite scalar to the length family if it is nonnegative.
    #[must_use]
    pub const fn from_finite_assigned_real(value: FiniteReal) -> Option<Self> {
        if value.get() >= 0.0 {
            Some(Self(value.get()))
        } else {
            None
        }
    }

    /// The length times the magnitude of the sine of `angle`.
    ///
    /// The sine of a finite angle is finite, and a sine computed within one
    /// unit in the last place has magnitude at most one. The product is
    /// therefore finite, nonnegative and not above the length, so it is
    /// admitted without a check.
    #[must_use]
    pub fn scaled_by_sine(self, angle: Angle) -> Self {
        Self(self.0 * angle.0.sin().abs())
    }

    /// Assign the length family to a dimensionless nonnegative value in
    /// canonical millimeters.
    ///
    /// The caller calls this route only where its own context states that
    /// the value is a length, for example a tolerance that bounds model-space
    /// distances. Both domains admit every finite nonnegative value, so the
    /// assignment keeps the value and cannot refuse.
    #[must_use]
    pub const fn from_assigned_real(value: NonNegativeReal) -> Self {
        Self(value.0)
    }

    /// The length times `scale`.
    ///
    /// A positive scale keeps the sign of a nonnegative value: zero stays
    /// zero, and rounding does not change a sign. The product is refused only
    /// when it overflows.
    #[must_use]
    pub fn scaled(self, scale: PositiveReal) -> Option<Self> {
        let value = self.0 * scale.0;
        value.is_finite().then_some(Self(value))
    }
}

impl PositiveReal {
    /// Unit scalar value.
    pub const ONE: Self = Self(1.0);

    /// Assign a positive length to a dimensionless positive value.
    /// The caller supplies the quantity meaning; both domains admit the same bits.
    #[must_use]
    pub const fn from_assigned_length(value: PositiveLength) -> Self {
        Self(value.0)
    }

    /// Admit a finite scalar as positive. Only its sign remains to check.
    #[must_use]
    pub const fn from_finite(value: FiniteReal) -> Option<Self> {
        if value.get() > 0.0 {
            Some(Self(value.get()))
        } else {
            None
        }
    }
}

impl NonNegativeReal {
    /// Zero dimensionless scalar.
    pub const ZERO: Self = Self(0.0);

    /// Narrow an admitted nonnegative value to a positive value.
    ///
    /// Finiteness is already admitted; only zero can refuse.
    #[must_use]
    pub const fn positive(self) -> Option<PositiveReal> {
        if self.0 > 0.0 {
            Some(PositiveReal(self.0))
        } else {
            None
        }
    }

    /// Admit a finite scalar as nonnegative. Only its sign remains to check.
    #[must_use]
    pub const fn from_finite(value: FiniteReal) -> Option<Self> {
        if value.get() >= 0.0 {
            Some(Self(value.get()))
        } else {
            None
        }
    }

    /// The value times `scale`.
    ///
    /// A positive scale keeps the sign of a nonnegative value: zero stays
    /// zero, and rounding does not change a sign. The product is refused only
    /// when it overflows.
    #[must_use]
    pub fn scaled(self, scale: PositiveReal) -> Option<Self> {
        let value = self.0 * scale.0;
        value.is_finite().then_some(Self(value))
    }
}

impl Magnification {
    /// Millimeters per meter.
    pub const MILLIMETERS_PER_METER: Self = Self(1000.0);
}

impl SlopeAngle {
    /// Zero in canonical radians.
    pub const ZERO: Self = Self(0.0);
}

impl PositiveAngle {
    /// One full turn in radians.
    pub const FULL_TURN: Self = Self(std::f64::consts::TAU);
    /// One quarter turn in radians.
    pub const QUARTER_TURN: Self = Self(std::f64::consts::FRAC_PI_2);
    /// One half turn in radians.
    pub const HALF_TURN: Self = Self(std::f64::consts::PI);
    /// Three quarter turns in radians.
    pub const THREE_QUARTER_TURN: Self = Self(3.0 * std::f64::consts::FRAC_PI_2);

    /// Assign a finite scalar as an angle and require it to be positive.
    /// Only the sign remains to check.
    #[must_use]
    pub const fn from_assigned_real(value: FiniteReal) -> Option<Self> {
        if value.get() > 0.0 {
            Some(Self(value.get()))
        } else {
            None
        }
    }
}

impl NonZeroAngle {
    /// The positive magnitude of a finite nonzero angle.
    #[must_use]
    pub const fn abs(self) -> PositiveAngle {
        PositiveAngle(self.0.abs())
    }
}

/// State one subset edge inside a quantity family.
///
/// `$from` accepts a subset of what `$to` accepts, so the widening carries the
/// stored value without checking it again. The restriction back to `$from`
/// runs `$from`'s own admission, so it is `TryFrom` and `$error` states the
/// condition a refused value failed.
///
/// A pair whose domains only overlap has no subset direction and therefore no
/// declaration here; such a conversion is a check its caller spells out.
macro_rules! scalar_subset {
    ($from:ident => $to:ident, $error:literal) => {
        impl From<$from> for $to {
            fn from(value: $from) -> Self {
                Self(value.get())
            }
        }

        impl TryFrom<$to> for $from {
            type Error = &'static str;

            fn try_from(value: $to) -> Result<Self, Self::Error> {
                Self::new(value.get()).ok_or($error)
            }
        }
    };
}

scalar_subset!(PositiveLength => NonZeroLength, "length must be positive");
scalar_subset!(PositiveLength => NonNegativeLength, "length must be positive");
scalar_subset!(PositiveLength => Length, "length must be positive");
scalar_subset!(NonZeroLength => Length, "length must be nonzero");
scalar_subset!(NonNegativeLength => Length, "length must be nonnegative");

scalar_subset!(InteriorAngle => PositiveAngle, "angle must be strictly less than pi");
scalar_subset!(InteriorAngle => NonZeroAngle, "angle must be strictly between zero and pi");
scalar_subset!(InteriorAngle => Angle, "angle must be strictly between zero and pi");
scalar_subset!(PositiveAngle => NonZeroAngle, "angle must be positive");
scalar_subset!(PositiveAngle => Angle, "angle must be positive");
scalar_subset!(NonZeroAngle => Angle, "angle must be nonzero");
scalar_subset!(SlopeAngle => Angle, "angle must be strictly between -pi/2 and pi/2");

scalar_subset!(PositiveReal => NonZeroReal, "value must be positive");
scalar_subset!(PositiveReal => NonNegativeReal, "value must be positive");
scalar_subset!(PositiveReal => FiniteReal, "value must be positive");
scalar_subset!(NonZeroReal => FiniteReal, "value must be nonzero");
scalar_subset!(NonNegativeReal => FiniteReal, "value must be nonnegative");
scalar_subset!(Fraction => NonNegativeReal, "value must be between zero and one");
scalar_subset!(Fraction => FiniteReal, "value must be between zero and one");
scalar_subset!(Magnification => PositiveReal, "value must be at least one");

impl Length {
    /// Reverse the sign.
    #[must_use]
    pub const fn negated(self) -> Self {
        Self(-self.0)
    }

    /// The length in canonical millimeters as a dimensionless real, for a
    /// product with a dimensionless factor. A length is finite, so nothing is
    /// checked.
    #[must_use]
    pub const fn magnitude(self) -> FiniteReal {
        FiniteReal(self.0)
    }

    /// The magnitude. The magnitude of a finite value is finite.
    #[must_use]
    pub const fn abs(self) -> Self {
        Self(self.0.abs())
    }

    /// Assign the length family to a dimensionless value in canonical
    /// millimeters.
    ///
    /// A `FiniteReal` carries no quantity family, so no conversion gives it
    /// one. The caller calls this route only where its own context states that
    /// the value is a length, for example a parameter definition that declares
    /// a length kind. Both domains admit every finite value, so the assignment
    /// keeps the value and cannot refuse.
    #[must_use]
    pub const fn from_assigned_real(value: FiniteReal) -> Self {
        Self(value.0)
    }
}

impl PositiveLength {
    /// Assign a positive dimensionless value to the length family.
    #[must_use]
    pub const fn from_assigned_positive_real(value: PositiveReal) -> Self {
        Self(value.get())
    }

    /// Assign a finite scalar to the length family if it is positive.
    #[must_use]
    pub const fn from_assigned_real(value: FiniteReal) -> Option<Self> {
        if value.get() > 0.0 {
            Some(Self(value.get()))
        } else {
            None
        }
    }

    /// The length in canonical millimeters as a dimensionless real, for a
    /// quotient of lengths. A positive length is finite, so nothing is
    /// checked.
    #[must_use]
    pub const fn magnitude(self) -> FiniteReal {
        FiniteReal(self.0)
    }

    /// Two values, the first not below the second, each times `scale`, as
    /// positive lengths. The caller establishes that order.
    ///
    /// Rounding is monotone, so the products keep the order; they can round
    /// to one value, which the order admits. The first product is admitted
    /// positive and finite. The second is not above the first, so it is
    /// finite when the first is, and only its sign is tested. A refusal gives
    /// the index of the refused value.
    pub(crate) fn scale_ordered_pair(
        values: [f64; 2],
        scale: PositiveReal,
    ) -> Result<[Self; 2], usize> {
        let [first, second] = values.map(|value| value * scale.0);
        if !first.is_finite() || first <= 0.0 {
            return Err(0);
        }
        if second <= 0.0 {
            return Err(1);
        }
        Ok([Self(first), Self(second)])
    }
}

impl NonZeroLength {
    /// Assign a finite scalar to the length family if it is nonzero.
    #[must_use]
    pub const fn from_assigned_real(value: FiniteReal) -> Option<Self> {
        if value.get() == 0.0 {
            None
        } else {
            Some(Self(value.get()))
        }
    }

    /// The magnitude. The magnitude of a finite nonzero value is finite and
    /// positive.
    #[must_use]
    pub const fn abs(self) -> PositiveLength {
        PositiveLength(self.0.abs())
    }

    /// The length times `factor`.
    ///
    /// The exact product has a magnitude not below the length's, and rounding
    /// is monotone, so the rounded product is not zero. The product is refused
    /// only when it overflows.
    #[must_use]
    pub fn magnified(self, factor: Magnification) -> Option<Self> {
        let value = self.0 * factor.0;
        value.is_finite().then_some(Self(value))
    }
}

impl Angle {
    /// Reverse the sign.
    #[must_use]
    pub const fn negated(self) -> Self {
        Self(-self.0)
    }

    /// The magnitude. The magnitude of a finite value is finite.
    #[must_use]
    pub const fn abs(self) -> Self {
        Self(self.0.abs())
    }

    /// Assign the angle family to a dimensionless value in canonical radians.
    ///
    /// A `FiniteReal` carries no quantity family, so no conversion gives it
    /// one. The caller calls this route only where its own context states that
    /// the value is an angle, for example a parameter definition or a relation
    /// that declares an angle kind. Both domains admit every finite value, so
    /// the assignment keeps the value and cannot refuse.
    #[must_use]
    pub const fn from_assigned_real(value: FiniteReal) -> Self {
        Self(value.0)
    }
}

impl FiniteReal {
    /// Unit scalar value.
    pub const ONE: Self = Self(1.0);
    /// Zero.
    pub const ZERO: Self = Self(0.0);
    /// One half.
    pub const HALF: Self = Self(0.5);
    /// Two.
    pub(crate) const TWO: Self = Self(2.0);

    /// Reverse the sign.
    #[must_use]
    pub const fn negated(self) -> Self {
        Self(-self.0)
    }

    /// The magnitude. The magnitude of a finite value is finite.
    #[must_use]
    pub const fn abs(self) -> Self {
        Self(self.0.abs())
    }

    /// The value `units` times the least positive subnormal magnitude,
    /// negated when `negative` is set.
    ///
    /// A `u64` converts to at most `2^64`, and `2^64` times `2^-1074` is
    /// `2^-1010`, so the product is finite for every argument and nothing is
    /// checked. Up to `2^53` units the conversion and the product are exact,
    /// so the value is the one whose bit pattern is the sign bit and `units`.
    #[must_use]
    pub(crate) fn subnormal_units(negative: bool, units: u64) -> Option<Self> {
        let magnitude = cadmpeg_core::convert::f64_from_u64(units)? * f64::from_bits(1);
        Some(Self(if negative { -magnitude } else { magnitude }))
    }

    /// The four-quadrant arctangent of `self / x`, an angle in `[-π, π]`.
    /// The arctangent of two finite values is finite, so nothing is checked.
    #[must_use]
    pub fn atan2(self, x: Self) -> Self {
        Self(self.0.atan2(x.0))
    }

    /// An index as a real, absent when its integer value is not exact in `f64`.
    #[must_use]
    pub(crate) fn from_index(index: usize) -> Option<Self> {
        cadmpeg_core::convert::f64_from_index(index).map(Self)
    }

    /// An integer as a real, absent when its integer value is not exact in `f64`.
    #[must_use]
    pub(crate) fn from_integer(value: i64) -> Option<Self> {
        cadmpeg_core::convert::f64_from_i64(value).map(Self)
    }

    /// The turns from `start` to `self`: `(self - start) / τ`, rounded once
    /// from the exact difference.
    ///
    /// The exact difference of two finite values is at most `2 * f64::MAX`
    /// in magnitude and `τ` exceeds two, so the quotient is finite and nothing
    /// is checked. The route lives beside [`FiniteReal`] because only this
    /// module constructs one.
    #[must_use]
    pub(crate) fn turns_from(self, start: Self) -> Self {
        use crate::math::sum::{ExactSignedSum, ScaledValue};
        let mut difference = ExactSignedSum::default();
        difference.add_product(self.0, 1.0);
        difference.add_product(start.0, -1.0);
        let turn = ScaledValue::of_nonzero(NonZeroReal(std::f64::consts::TAU));
        Self(difference.finish().map_or(0.0, |difference| {
            difference.quotient_shifted_product(turn, 0)
        }))
    }

    /// Where `self` lies against the segment from `start` to `end`: outside
    /// it, on a segment of zero width, or at the fraction `(self - start) /
    /// (end - start)`, rounded once from the exact differences.
    ///
    /// A value within the segment lies no farther from `start` than `end`
    /// does, and on the same side, so the fraction lies in `[0, 1]` and
    /// nothing is checked. The route lives beside [`FiniteReal`] because only
    /// this module constructs one.
    pub(crate) fn segment_position(self, start: Self, end: Self) -> SegmentPosition {
        use crate::math::sum::ExactSignedSum;
        if !((self >= start && self <= end) || (self <= start && self >= end)) {
            return SegmentPosition::Outside;
        }
        let mut width = ExactSignedSum::default();
        width.add_product(end.0, 1.0);
        width.add_product(start.0, -1.0);
        let Some(width) = width.finish() else {
            return SegmentPosition::Degenerate;
        };
        let mut distance = ExactSignedSum::default();
        distance.add_product(self.0, 1.0);
        distance.add_product(start.0, -1.0);
        SegmentPosition::Within(Self(
            distance
                .finish()
                .map_or(0.0, |distance| distance.quotient_shifted_product(width, 0)),
        ))
    }

    /// `exp(-|self|)` and `(1 + exp(-|self|)²)²`, the tail and the squared
    /// denominator of the hyperbolic tangent's derivative. The tail lies in
    /// `[0, 1]`, so the denominator lies in `[1, 4]` and nothing is checked.
    /// The route lives beside [`FiniteReal`] because only this module
    /// constructs a nonzero value.
    pub(crate) fn hyperbolic_tail(self) -> (f64, NonZeroReal) {
        let tail = (-self.0.abs()).exp();
        (tail, NonZeroReal((1.0 + tail * tail).powi(2)))
    }

    /// The hypotenuse of this finite value and one is finite and at least one.
    pub(crate) fn hypot_one_nonzero(self) -> NonZeroReal {
        NonZeroReal(self.0.hypot(1.0))
    }

    /// `exp(-|self|)` and `1 + exp(-|self|)^2`; the sum is in `[1, 2]`.
    pub(crate) fn hyperbolic_tail_unit_sum(self) -> (f64, NonZeroReal) {
        let tail = (-self.0.abs()).exp();
        (tail, NonZeroReal(1.0 + tail * tail))
    }

    /// The value as a magnitude above one, or none where its magnitude is at
    /// most one.
    pub(crate) fn beyond_unit(self) -> Option<BeyondUnit> {
        (self.0.abs() > 1.0).then_some(BeyondUnit(self.0))
    }

    /// Half the value. Half a finite value is finite.
    #[must_use]
    pub(crate) fn halved(self) -> Self {
        Self(self.0 * 0.5)
    }

    /// The midpoint of `self` and `other`. The midpoint of two finite values
    /// is finite.
    #[must_use]
    pub(crate) fn midpoint(self, other: Self) -> Self {
        Self(self.0.midpoint(other.0))
    }

    /// Admit a normal value or a zero. Every normal value and every zero is
    /// finite, so the one predicate states the whole admission.
    pub(crate) fn normal_or_zero(value: f64) -> Option<Self> {
        (value.is_normal() || value == 0.0).then_some(Self(value))
    }

    /// Admit every value of each lane, or none of them.
    pub(crate) fn lanes<const N: usize>(lanes: [Vec<f64>; N]) -> Option<[Vec<Self>; N]> {
        lanes
            .iter()
            .flatten()
            .all(|value| value.is_finite())
            .then(|| lanes.map(|lane| lane.into_iter().map(Self).collect()))
    }

    /// Admit every present value, or none of them.
    pub(crate) fn optional<const N: usize>(values: [Option<f64>; N]) -> Option<[Option<Self>; N]> {
        values
            .iter()
            .flatten()
            .all(|value| value.is_finite())
            .then(|| values.map(|value| value.map(Self)))
    }

    /// Admit every value, or none of them.
    pub(crate) fn array<const N: usize>(values: [f64; N]) -> Option<[Self; N]> {
        values
            .iter()
            .all(|value| value.is_finite())
            .then(|| values.map(Self))
    }

    /// Admit every value of the lane, or none of them.
    pub(crate) fn lane(values: Vec<f64>) -> Option<Vec<Self>> {
        values
            .iter()
            .all(|value| value.is_finite())
            .then(|| values.into_iter().map(Self).collect())
    }

    /// Admit every value of each row, or none of them.
    pub(crate) fn rows<const N: usize>(rows: Vec<[f64; N]>) -> Option<Vec<[Self; N]>> {
        rows.iter()
            .flatten()
            .all(|value| value.is_finite())
            .then(|| rows.into_iter().map(|row| row.map(Self)).collect())
    }

    /// Admit every value of the grid, or none of them.
    pub(crate) fn grid<const N: usize, const M: usize>(
        grid: [[f64; M]; N],
    ) -> Option<[[Self; M]; N]> {
        grid.iter()
            .flatten()
            .all(|value| value.is_finite())
            .then(|| grid.map(|row| row.map(Self)))
    }

    /// Admit every present value of the grid, or none of them.
    pub(crate) fn optional_grid<const N: usize, const M: usize>(
        grid: [[Option<f64>; M]; N],
    ) -> Option<[[Option<Self>; M]; N]> {
        grid.iter()
            .flatten()
            .flatten()
            .all(|value| value.is_finite())
            .then(|| grid.map(|row| row.map(|value| value.map(Self))))
    }

    /// The raw values of the array, for a reader that writes or edits them.
    #[must_use]
    pub fn raw_array<const N: usize>(values: [Self; N]) -> [f64; N] {
        values.map(Self::get)
    }

    /// The raw present values, for a reader that writes or edits them.
    #[must_use]
    pub fn raw_optional<const N: usize>(values: [Option<Self>; N]) -> [Option<f64>; N] {
        values.map(|value| value.map(Self::get))
    }

    /// The raw values of the lane, for a reader that writes or edits them.
    #[must_use]
    pub fn raw_lane(values: &[Self]) -> Vec<f64> {
        values.iter().map(|value| value.0).collect()
    }

    /// The raw values of each row, for a reader that writes or edits them.
    #[must_use]
    pub fn raw_rows<const N: usize>(rows: &[[Self; N]]) -> Vec<[f64; N]> {
        rows.iter().map(|row| row.map(Self::get)).collect()
    }

    /// The raw values of the grid, for a reader that writes or edits them.
    #[must_use]
    pub fn raw_grid<const N: usize, const M: usize>(grid: [[Self; M]; N]) -> [[f64; M]; N] {
        grid.map(|row| row.map(Self::get))
    }

    /// The raw present values of the grid, for a reader that writes or edits
    /// them.
    #[must_use]
    pub fn raw_optional_grid<const N: usize, const M: usize>(
        grid: [[Option<Self>; M]; N],
    ) -> [[Option<f64>; M]; N] {
        grid.map(Self::raw_optional)
    }

    /// The raw values of each lane, for a reader that writes or edits them.
    #[must_use]
    pub fn raw_lanes<const N: usize>(lanes: &[Vec<Self>; N]) -> [Vec<f64>; N] {
        std::array::from_fn(|index| lanes[index].iter().map(|value| value.0).collect())
    }
}

impl crate::topology::IncreasingParameterInterval {
    /// The affine scale and offset that map this interval to `target`, when
    /// both coefficients have finite nonzero scale and finite offset. Scaled
    /// spans retain a ratio even when either width exceeds binary64.
    pub fn affine_coefficients_to(self, target: Self) -> Option<(FiniteReal, FiniteReal)> {
        use crate::math::sum::ExactSignedSum;
        let scale = target.scaled_span().quotient(self.scaled_span()).ok()?;
        if scale == FiniteReal::ZERO {
            return None;
        }
        let mut offset = ExactSignedSum::default();
        offset.add_product(target.lower(), 1.0);
        offset.add_product(self.lower(), -scale.get());
        Some((scale, offset.finite_sum()?))
    }

    /// The positive width as a finite factor, doubled when the full width
    /// exceeds binary64. Halving both large operands is exact before their
    /// finite subtraction.
    pub(crate) fn span_factors(self) -> (f64, bool) {
        let [lower, upper] = self.endpoints();
        let span = upper - lower;
        if span.is_finite() {
            (span, false)
        } else {
            (upper * 0.5 - lower * 0.5, true)
        }
    }

    /// The positive interval width in a scaled form. A finite subtraction is
    /// nonzero because the endpoints are ordered.
    pub(crate) fn scaled_span(self) -> crate::math::sum::ScaledValue {
        use crate::math::sum::ScaledValue;
        let (factor, doubled) = self.span_factors();
        let span = ScaledValue::of_nonzero(NonZeroReal(factor));
        if doubled {
            span.doubled()
        } else {
            span
        }
    }

    /// Map a finite parameter from `source` into this interval. The exact
    /// product sum forms the affine numerator before division by the scaled
    /// source width, so neither width needs to fit in binary64. `reversed`
    /// maps the source start to this interval's upper endpoint.
    pub fn map_from(
        self,
        source: Self,
        parameter: FiniteReal,
        reversed: bool,
    ) -> Result<FiniteReal, f64> {
        use crate::math::sum::ExactSignedSum;
        let [source_start, source_end] = source.endpoints();
        let [lower, upper] = self.endpoints();
        let (target_start, target_end) = if reversed {
            (upper, lower)
        } else {
            (lower, upper)
        };
        let parameter = parameter.get();
        let mut numerator = ExactSignedSum::default();
        numerator.add_product(parameter, target_end);
        numerator.add_product(source_start, -target_end);
        numerator.add_product(source_end, target_start);
        numerator.add_product(parameter, -target_start);
        match numerator.finish() {
            Some(numerator) => numerator.quotient(source.scaled_span()),
            None => Ok(FiniteReal::ZERO),
        }
    }

    /// Return the endpoints as finite reals. The interval admits only finite
    /// endpoints, so nothing is checked. The route lives beside
    /// [`FiniteReal`] because only this module constructs one.
    #[must_use]
    pub const fn finite_endpoints(self) -> [FiniteReal; 2] {
        let [lower, upper] = self.endpoints();
        [FiniteReal(lower), FiniteReal(upper)]
    }
}

impl crate::topology::ParameterInterval {
    /// Return the endpoints as finite reals. The interval admits only finite
    /// endpoints, so nothing is checked. The route lives beside
    /// [`FiniteReal`] because only this module constructs one.
    #[must_use]
    pub const fn finite_endpoints(self) -> [FiniteReal; 2] {
        let [start, end] = self.endpoints();
        [FiniteReal(start), FiniteReal(end)]
    }

    /// The point of the interval nearest `value`: `value` itself inside the
    /// interval, its nearer endpoint outside. The endpoints are finite and
    /// ordered, so the nearest point is finite and nothing is checked. The
    /// route lives beside [`FiniteReal`] because only this module constructs
    /// one.
    #[must_use]
    pub(crate) fn project(self, value: ExtendedReal) -> FiniteReal {
        let [start, end] = self.endpoints();
        FiniteReal(value.0.clamp(start, end))
    }
}

impl<const N: usize> crate::units::FiniteVector<N> {
    /// The components as finite reals. The vector admits only finite
    /// components, so nothing is checked. The route lives beside
    /// [`FiniteReal`] because only this module constructs one.
    #[must_use]
    pub fn finite_components(self) -> [FiniteReal; N] {
        self.get().map(FiniteReal)
    }
}

impl crate::geometry::nurbs::KnotVector {
    /// The knot at `index` as a finite real, absent past the last knot. The
    /// vector admits only finite knots, so nothing is checked. The route
    /// lives beside [`FiniteReal`] because only this module constructs one.
    #[must_use]
    pub fn finite_knot(&self, index: usize) -> Option<FiniteReal> {
        self.as_slice().get(index).map(|knot| FiniteReal(*knot))
    }

    /// The knots as finite reals, in order. The vector admits only finite
    /// knots, so nothing is checked. The route lives beside [`FiniteReal`]
    /// because only this module constructs one.
    pub fn finite_knots(
        &self,
    ) -> impl DoubleEndedIterator<Item = FiniteReal> + ExactSizeIterator + '_ {
        self.as_slice().iter().map(|knot| FiniteReal(*knot))
    }
}

impl crate::geometry::DirectedParameterRange {
    /// Return the directed endpoints as finite reals. The range admits only
    /// finite endpoints, so nothing is checked. The route lives beside
    /// [`FiniteReal`] because only this module constructs one.
    #[must_use]
    pub const fn finite_endpoints(self) -> [FiniteReal; 2] {
        let [start, end] = self.endpoints();
        [FiniteReal(start), FiniteReal(end)]
    }
}

impl crate::geometry::RecordBounds {
    /// The present values as finite reals. The quartet admits only finite
    /// values, so nothing is checked. The route lives beside [`FiniteReal`]
    /// because only this module constructs one.
    #[must_use]
    pub(crate) fn finite_values(self) -> [Option<FiniteReal>; 4] {
        self.get().map(|value| value.map(FiniteReal))
    }
}

impl crate::features::FinitePoint3 {
    /// Return the coordinates as finite reals. The point admits only finite
    /// coordinates, so nothing is checked. The route lives beside
    /// [`FiniteReal`] because only this module constructs one.
    #[must_use]
    pub const fn coordinates(self) -> [FiniteReal; 3] {
        let point = self.get();
        [
            FiniteReal(point.x),
            FiniteReal(point.y),
            FiniteReal(point.z),
        ]
    }
}

impl crate::features::FiniteVector3 {
    /// Return the components as finite reals. The vector admits only finite
    /// components, so nothing is checked. The route lives beside
    /// [`FiniteReal`] because only this module constructs one.
    #[must_use]
    pub const fn components(self) -> [FiniteReal; 3] {
        let vector = self.get();
        [
            FiniteReal(vector.x),
            FiniteReal(vector.y),
            FiniteReal(vector.z),
        ]
    }

    /// The components charted by the binade of the largest magnitude, and the
    /// chart's exponent: each component times `2^-exponent`, where
    /// `2^exponent` is the least power of two above the largest magnitude. A
    /// zero vector has no chart.
    ///
    /// Every magnitude is at most the largest, which lies below `2^exponent`,
    /// and a power-of-two scaling does not raise a magnitude past the
    /// product's own bound, so each charted component lies in `(-1, 1)` and
    /// nothing is checked. The route lives beside [`FiniteReal`] because only
    /// this module constructs one.
    #[must_use]
    pub(crate) fn binade_chart(self) -> Option<([FiniteReal; 3], i32)> {
        let vector = self.get();
        let largest = vector.x.abs().max(vector.y.abs()).max(vector.z.abs());
        let exponent = crate::math::power_of_two_bound(largest)?;
        let chart = |value: f64| FiniteReal(crate::math::power_of_two_product(value, -exponent));
        Some((
            [chart(vector.x), chart(vector.y), chart(vector.z)],
            exponent,
        ))
    }

    /// Unit direction for every nonzero vector, including subnormals, and
    /// none for the zero vector. Callers that impose a geometric length
    /// threshold must check it separately.
    ///
    /// The vector is charted by the binade of its largest component
    /// ([`Self::binade_chart`]), so the norm stays in range: the largest
    /// charted magnitude is at least one half and none reaches one, so the
    /// chart's norm lies in `[1/2, √3)`. Each unit component is a charted
    /// component over that norm, at most one in magnitude. A charted component
    /// below the normal range may already be rounded or zero; its quotient is
    /// formed from the original component instead, rounded once. Nothing is
    /// checked. The route lives beside [`FiniteReal`] because only this module
    /// constructs the nonzero norm.
    #[must_use]
    pub fn unit_nonzero(self) -> Option<crate::math::Vector3> {
        use crate::math::sum::ScaledValue;
        let ([x, y, z], exponent) = self.binade_chart()?;
        let length = crate::math::Vector3::new(x.0, y.0, z.0).norm();
        let scaled_length = ScaledValue::of_nonzero(NonZeroReal(length));
        let component = |value: f64, chart: FiniteReal| match NonZeroReal::new(value) {
            Some(value) if chart.0.abs() < f64::MIN_POSITIVE => {
                ScaledValue::of_nonzero(value).quotient_shifted_product(scaled_length, -exponent)
            }
            _ => chart.0 / length,
        };
        let vector = self.get();
        Some(crate::math::Vector3::new(
            component(vector.x, x),
            component(vector.y, y),
            component(vector.z, z),
        ))
    }

    /// The unit direction, and the factors `[scale, scale, scale, length³]`
    /// of the cubed length, where `scale` is the largest component magnitude
    /// and `length` the norm of the components over it; none for the zero
    /// vector.
    ///
    /// The scale of a nonzero vector is nonzero and finite. Each component
    /// over it lies in `[-1, 1]` and the largest is `±1` exactly, so `length`
    /// lies in `[1, √3]` and its cube in `[1, 3√3]`: nothing is checked.
    #[must_use]
    pub(crate) fn unit_with_cubed_length(self) -> Option<(crate::math::Vector3, [NonZeroReal; 4])> {
        let unit = self.unit_nonzero()?;
        let vector = self.get();
        let scale = vector.x.abs().max(vector.y.abs()).max(vector.z.abs());
        let length = (vector.x / scale)
            .hypot(vector.y / scale)
            .hypot(vector.z / scale);
        let scale = NonZeroReal(scale);
        Some((
            unit,
            [scale, scale, scale, NonZeroReal(length * length * length)],
        ))
    }
}

impl crate::units::FinitePoint2 {
    /// Return the coordinates as finite reals. The point admits only finite
    /// coordinates, so nothing is checked. The route lives beside
    /// [`FiniteReal`] because only this module constructs one.
    #[must_use]
    pub const fn coordinates(self) -> [FiniteReal; 2] {
        let point = self.get();
        [FiniteReal(point.u), FiniteReal(point.v)]
    }
}

/// A real value or an infinity, never NaN.
///
/// The hypotenuse of two finite values, a finite value or an infinity over a
/// nonzero finite length, and a finite length subtracted from one of these
/// are all finite or infinite. The four-quadrant arctangent of two such values is
/// finite, so it needs no check.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ExtendedReal(f64);

impl ExtendedReal {
    /// A finite value.
    pub(crate) const fn from_finite(value: FiniteReal) -> Self {
        Self(value.0)
    }

    /// Admit a value that is not NaN.
    pub(crate) fn new(value: f64) -> Option<Self> {
        (!value.is_nan()).then_some(Self(value))
    }

    /// `origin - scale * step`. The product of two finite values is finite
    /// or infinite, and a finite value less it is finite or infinite.
    pub(crate) fn stepped(origin: FiniteReal, scale: FiniteReal, step: FiniteReal) -> Self {
        Self(origin.0 - scale.0 * step.0)
    }

    /// The hypotenuse `hypot(x, y)` of two finite values: finite or `+inf`.
    pub(crate) fn hypot(x: FiniteReal, y: FiniteReal) -> Self {
        Self(x.0.hypot(y.0))
    }

    /// `self - value`: an infinity less a finite length keeps its infinity.
    #[must_use]
    pub(crate) fn minus(self, value: Length) -> Self {
        Self(self.0 - value.0)
    }

    /// `self / divisor`: over a nonzero finite divisor, a finite value is
    /// finite or infinite and an infinity keeps its infinity.
    #[must_use]
    pub(crate) fn over(self, divisor: NonZeroLength) -> Self {
        Self(self.0 / divisor.0)
    }

    /// The four-quadrant arctangent of `self / x`, an angle in `[-π, π]`.
    pub(crate) fn atan2(self, x: Self) -> FiniteReal {
        FiniteReal(self.0.atan2(x.0))
    }
}

/// Where a value lies against a segment of two finite bounds.
pub(crate) enum SegmentPosition {
    /// The value lies outside the segment.
    Outside,
    /// The bounds are equal: the segment has zero width.
    Degenerate,
    /// The value lies at this fraction of the segment, in `[0, 1]`.
    Within(FiniteReal),
}

/// The cosine of two admitted unit directions, rounded into its closed
/// mathematical range.
#[derive(Clone, Copy)]
pub(crate) struct UnitCosine(f64);

impl UnitCosine {
    /// The dot product of unit directions. Each product and their sum are
    /// finite; rounding at the boundary can put the result just outside
    /// `[-1, 1]`, so the boundary itself is the admitted value.
    pub(crate) fn between(
        first: crate::units::UnitVector3,
        second: crate::units::UnitVector3,
    ) -> Self {
        let dot = first.as_raw().dot(*second.as_raw());
        Self(if dot.abs() > 1.0 { dot.signum() } else { dot })
    }

    pub(crate) const fn get(self) -> f64 {
        self.0
    }
}

/// A finite value whose magnitude exceeds one.
#[derive(Clone, Copy)]
pub(crate) struct BeyondUnit(f64);

impl BeyondUnit {
    /// The nonzero magnitude of a value whose magnitude exceeds one.
    pub(crate) fn magnitude(self) -> NonZeroReal {
        NonZeroReal(self.0.abs())
    }

    /// The positive square-root factor in the arcsecant derivative.
    pub(crate) fn arcsec_factor(self) -> NonZeroReal {
        let magnitude = self.0.abs();
        NonZeroReal((((magnitude - 1.0) / magnitude) * (1.0 + 1.0 / magnitude)).sqrt())
    }

    /// `dividend / self`. The quotient's magnitude is below the dividend's,
    /// so it is finite and nothing is checked.
    pub(crate) fn quotient(self, dividend: FiniteReal) -> FiniteReal {
        FiniteReal(dividend.0 / self.0)
    }

    /// `((self - 1) / self) * ((self + 1) / self)`, which is `1 - 1/self²`.
    ///
    /// For `self` in `(1, 2]` the difference `self - 1` is exact and at least
    /// `2^-52`, and beyond two it is at least one; the sum `self + 1` is at
    /// least two. Each quotient lies in `(0, 2)`, and their product is
    /// positive, finite and at least `2^-53`; the negative side is the mirror
    /// image. Nothing is checked.
    pub(crate) fn square_complement(self) -> NonZeroReal {
        let x = self.0;
        NonZeroReal(((x - 1.0) / x) * ((x + 1.0) / x))
    }

    /// The inverse hyperbolic cotangent, `atanh(1 / self)`. The reciprocal's
    /// magnitude is below one, so the value is finite and nothing is checked.
    pub(crate) fn arcoth(self) -> FiniteReal {
        FiniteReal((1.0 / self.0).atanh())
    }
}

impl PositiveReal {
    /// `sqrt((1 - self) * (1 + self))` for a value below one, and none
    /// otherwise.
    ///
    /// Below one each factor is at least `2^-53`: `1 - self` is exact from
    /// one half on and at least one half before it. The product is normal and
    /// at most one, so the root is positive and finite and nothing is
    /// checked. The route lives beside [`FiniteReal`] because only this
    /// module constructs one.
    pub(crate) fn unit_complement_root(self) -> Option<Self> {
        (self.0 < 1.0).then(|| Self(((1.0 - self.0) * (1.0 + self.0)).sqrt()))
    }
}

impl NonZeroReal {
    /// Admit a finite scalar as nonzero. Only zero remains to check.
    #[must_use]
    pub const fn from_finite(value: FiniteReal) -> Option<Self> {
        if value.get() == 0.0 {
            None
        } else {
            Some(Self(value.get()))
        }
    }

    /// Unit scalar value.
    pub const ONE: Self = Self(1.0);
    /// One over the square root of two.
    pub const FRAC_1_SQRT_2: Self = Self(std::f64::consts::FRAC_1_SQRT_2);

    /// The positive magnitude of a nonzero finite value.
    pub(crate) fn magnitude(self) -> Self {
        Self(self.0.abs())
    }

    /// `-expm1(-2|self|)` is positive for every nonzero binary64 input.
    pub(crate) fn hyperbolic_sinh_denominator(self) -> Self {
        Self(-(-2.0 * self.0.abs()).exp_m1())
    }
}
#[cfg(test)]
mod tests;

mod identity_rewrite;