Skip to main content

wellfare_core/anatomy/
measurements.rs

1//! Comprehensive **body measurements** — one integer record for anatomy fit, clothing,
2//! footwear, helmets, gloves, rings, and eyewear.
3//!
4//! Vocabulary follows ISO 8559-1 / ISO 7250-1 (garment anthropometry) plus Brannock-style
5//! foot measures and standard headform arcs. This is **not** a certification claim; the
6//! names are so a clothing or helmet module can consume the same numbers the person typed.
7//!
8//! Every field is optional. Absence is not an assumption. Anatomy [`super::constitution::BodyFit`]
9//! currently uses only stature, sitting height, inseam, arm span, shoulder, chest, waist,
10//! and hip. The rest are stored and listed by use — they do not invent a morph.
11
12use serde::{Deserialize, Serialize};
13
14/// Soft clamps so a typo cannot explode a consumer. Values outside are rejected on save.
15pub const STATURE_MM_RANGE: (u16, u16) = (300, 2500);
16pub const WEIGHT_G_RANGE: (u32, u32) = (500, 400_000);
17/// Legacy torso-girth window (kept for callers). Per-field ranges live on the catalog.
18pub const CIRC_MM_RANGE: (u16, u16) = (80, 2500);
19
20const FIT: u16 = 1;
21const CLOTH: u16 = 2;
22const FOOTW: u16 = 4;
23const HEADW: u16 = 8;
24const GLOVE: u16 = 16;
25const EYE: u16 = 32;
26const RING: u16 = 64;
27
28/// Who consumes this measure. A field can serve several.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31pub enum MeasurementUse {
32    AnatomyFit,
33    Clothing,
34    Footwear,
35    Headwear,
36    Gloves,
37    Eyewear,
38    Rings,
39}
40
41/// Form / catalog grouping.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
43#[serde(rename_all = "snake_case")]
44pub enum MeasurementGroup {
45    WholeBody,
46    Torso,
47    Arms,
48    Legs,
49    Head,
50    Hands,
51    Feet,
52}
53
54impl MeasurementGroup {
55    /// Label.
56    pub fn label(self) -> &'static str {
57        match self {
58            Self::WholeBody => "Whole body",
59            Self::Torso => "Torso and clothing",
60            Self::Arms => "Arms and sleeves",
61            Self::Legs => "Legs and trousers",
62            Self::Head => "Head, helmets, and hats",
63            Self::Hands => "Hands, gloves, and rings",
64            Self::Feet => "Feet and footwear",
65        }
66    }
67
68    /// Hint.
69    pub fn hint(self) -> &'static str {
70        match self {
71            Self::WholeBody => {
72                "Height and mass for the body, plus the long measures used to proportion it."
73            }
74            Self::Torso => {
75                "Shirt, jacket, dress, and bra measures (ISO 8559-1 names). Underbust is stored; cup size is a garment convention, not a body measure."
76            }
77            Self::Arms => {
78                "Sleeve length and arm girths for shirts, coats, and compression sleeves."
79            }
80            Self::Legs => "Inseam, outseam, and limb girths for trousers, shorts, and hosiery.",
81            Self::Head => {
82                "Helmets, hats, and some eyewear. Circumference plus length/breadth/arcs — not a hat-size letter."
83            }
84            Self::Hands => "Gloves and rings. Left/right ring girth when the two hands differ.",
85            Self::Feet => {
86                "Footwear lasts (Brannock-style). Prefer left and right; a single foot length is the fallback."
87            }
88        }
89    }
90}
91
92/// How the person types the number. Stored unit is always mm or g.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "snake_case")]
95pub enum MeasurementInputUnit {
96    Cm,
97    Kg,
98    Mm,
99}
100
101/// One curated measurement the person may declare.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct MeasurementSpec {
104    pub id: &'static str,
105    pub label: &'static str,
106    pub group: MeasurementGroup,
107    pub lo: u32,
108    pub hi: u32,
109    pub input: MeasurementInputUnit,
110    pub uses: u16,
111    pub hint: &'static str,
112}
113
114impl MeasurementSpec {
115    ///  uses.
116    pub fn uses_list(self) -> Vec<MeasurementUse> {
117        decode_uses(self.uses)
118    }
119
120    ///  when it serves the use.
121    pub fn serves(self, use_: MeasurementUse) -> bool {
122        self.uses & bit(use_) != 0
123    }
124
125    /// Stores unit.
126    pub fn store_unit(self) -> &'static str {
127        match self.input {
128            MeasurementInputUnit::Kg => "g",
129            _ => "mm",
130        }
131    }
132}
133
134/// Lengths and girths the person may declare. Units are millimetres / grams so the
135/// stored numbers are integers (no float health arithmetic in the record).
136#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
137pub struct BodyMeasurements {
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub stature_mm: Option<u16>,
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub weight_g: Option<u32>,
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub sitting_height_mm: Option<u16>,
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub cervical_height_mm: Option<u16>,
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub crotch_height_mm: Option<u16>,
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub knee_height_mm: Option<u16>,
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub ankle_height_mm: Option<u16>,
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub waist_height_mm: Option<u16>,
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub arm_span_mm: Option<u16>,
156
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub neck_mm: Option<u16>,
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub neck_base_mm: Option<u16>,
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub shoulder_width_mm: Option<u16>,
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub across_back_mm: Option<u16>,
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub across_chest_mm: Option<u16>,
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub chest_mm: Option<u16>,
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub underbust_mm: Option<u16>,
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub waist_mm: Option<u16>,
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub abdomen_mm: Option<u16>,
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub hip_mm: Option<u16>,
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub nape_to_waist_mm: Option<u16>,
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub front_waist_length_mm: Option<u16>,
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub rise_mm: Option<u16>,
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub outseam_mm: Option<u16>,
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub shoulder_girth_mm: Option<u16>,
187
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub sleeve_mm: Option<u16>,
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub upper_arm_length_mm: Option<u16>,
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub underarm_length_mm: Option<u16>,
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub elbow_to_wrist_mm: Option<u16>,
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub biceps_mm: Option<u16>,
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub elbow_girth_mm: Option<u16>,
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub forearm_mm: Option<u16>,
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub wrist_mm: Option<u16>,
204
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub inseam_mm: Option<u16>,
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub thigh_mm: Option<u16>,
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub mid_thigh_mm: Option<u16>,
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub knee_girth_mm: Option<u16>,
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub calf_mm: Option<u16>,
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub ankle_mm: Option<u16>,
217
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub head_mm: Option<u16>,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub head_length_mm: Option<u16>,
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub head_breadth_mm: Option<u16>,
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub head_height_mm: Option<u16>,
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub face_length_mm: Option<u16>,
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub bizygomatic_mm: Option<u16>,
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub sagittal_arc_mm: Option<u16>,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub bitragion_arc_mm: Option<u16>,
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub interpupillary_mm: Option<u16>,
236
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub hand_length_mm: Option<u16>,
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub palm_length_mm: Option<u16>,
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub hand_breadth_mm: Option<u16>,
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub hand_circ_mm: Option<u16>,
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub middle_finger_mm: Option<u16>,
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub thumb_circ_mm: Option<u16>,
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub ring_finger_circ_mm: Option<u16>,
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub ring_finger_left_circ_mm: Option<u16>,
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub ring_finger_right_circ_mm: Option<u16>,
255
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub foot_mm: Option<u16>,
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub foot_left_mm: Option<u16>,
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub foot_right_mm: Option<u16>,
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub foot_width_mm: Option<u16>,
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub foot_width_left_mm: Option<u16>,
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub foot_width_right_mm: Option<u16>,
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub heel_width_mm: Option<u16>,
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub ball_girth_mm: Option<u16>,
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub instep_girth_mm: Option<u16>,
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub arch_length_mm: Option<u16>,
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub toe_height_mm: Option<u16>,
278}
279
280impl BodyMeasurements {
281    ///  when empty.
282    pub fn is_empty(&self) -> bool {
283        *self == Self::default()
284    }
285
286    /// Gets.
287    pub fn get(&self, id: &str) -> Option<u32> {
288        let v = serde_json::to_value(self).ok()?;
289        v.get(id)?.as_u64().map(|n| n as u32)
290    }
291
292    /// Declared entries.
293    pub fn declared(&self) -> Vec<(&'static MeasurementSpec, u32)> {
294        MEASUREMENT_CATALOG
295            .iter()
296            .filter_map(|spec| self.get(spec.id).map(|n| (spec, n)))
297            .collect()
298    }
299
300    /// Values for a measurement.
301    pub fn values_for(&self, use_: MeasurementUse) -> Vec<(&'static MeasurementSpec, u32)> {
302        self.declared()
303            .into_iter()
304            .filter(|(spec, _)| spec.serves(use_))
305            .collect()
306    }
307
308    ///  when it has beyond-anatomy-fit.
309    pub fn has_beyond_anatomy_fit(&self) -> bool {
310        self.declared()
311            .into_iter()
312            .any(|(spec, _)| !spec.serves(MeasurementUse::AnatomyFit))
313    }
314
315    /// Single foot length for a consumer that does not handle laterality.
316    pub fn foot_length_mm(&self) -> Option<u16> {
317        self.foot_mm
318            .or_else(|| max_opt(self.foot_left_mm, self.foot_right_mm))
319    }
320
321    /// Foot width for a last size.
322    pub fn foot_width_for_last(&self) -> Option<u16> {
323        self.foot_width_mm
324            .or_else(|| max_opt(self.foot_width_left_mm, self.foot_width_right_mm))
325    }
326
327    /// Validates.
328    pub fn validate(&self) -> Result<(), String> {
329        for spec in MEASUREMENT_CATALOG {
330            if let Some(n) = self.get(spec.id) {
331                if n < spec.lo || n > spec.hi {
332                    return Err(format!(
333                        "{} {n} is outside {}–{} {}",
334                        spec.id,
335                        spec.lo,
336                        spec.hi,
337                        spec.store_unit()
338                    ));
339                }
340            }
341        }
342        if let (Some(stature), Some(sit)) = (self.stature_mm, self.sitting_height_mm) {
343            if sit >= stature {
344                return Err("sitting height must be shorter than standing height".into());
345            }
346        }
347        Ok(())
348    }
349}
350
351/// Authoritative field list. New garment/helmet measures get a row here — not a vendor struct.
352pub const MEASUREMENT_CATALOG: &[MeasurementSpec] = &[
353    // Whole body
354    spec(
355        "stature_mm",
356        "Standing height",
357        MeasurementGroup::WholeBody,
358        300,
359        2500,
360        MeasurementInputUnit::Cm,
361        FIT | CLOTH,
362        "Crown to floor.",
363    ),
364    spec(
365        "weight_g",
366        "Body mass",
367        MeasurementGroup::WholeBody,
368        500,
369        400_000,
370        MeasurementInputUnit::Kg,
371        FIT | CLOTH,
372        "Stored in grams.",
373    ),
374    spec(
375        "sitting_height_mm",
376        "Sitting height",
377        MeasurementGroup::WholeBody,
378        200,
379        1600,
380        MeasurementInputUnit::Cm,
381        FIT | CLOTH,
382        "Crown to seat.",
383    ),
384    spec(
385        "cervical_height_mm",
386        "Cervical height",
387        MeasurementGroup::WholeBody,
388        200,
389        1800,
390        MeasurementInputUnit::Cm,
391        CLOTH,
392        "Nape to floor, standing.",
393    ),
394    spec(
395        "crotch_height_mm",
396        "Crotch height",
397        MeasurementGroup::WholeBody,
398        200,
399        1200,
400        MeasurementInputUnit::Cm,
401        CLOTH,
402        "Crotch to floor.",
403    ),
404    spec(
405        "knee_height_mm",
406        "Knee height",
407        MeasurementGroup::WholeBody,
408        150,
409        800,
410        MeasurementInputUnit::Cm,
411        CLOTH,
412        "Knee crease to floor.",
413    ),
414    spec(
415        "ankle_height_mm",
416        "Ankle height",
417        MeasurementGroup::WholeBody,
418        40,
419        200,
420        MeasurementInputUnit::Cm,
421        CLOTH | FOOTW,
422        "Lateral malleolus to floor.",
423    ),
424    spec(
425        "waist_height_mm",
426        "Waist height",
427        MeasurementGroup::WholeBody,
428        300,
429        1500,
430        MeasurementInputUnit::Cm,
431        CLOTH,
432        "Natural waist to floor.",
433    ),
434    spec(
435        "arm_span_mm",
436        "Arm span",
437        MeasurementGroup::WholeBody,
438        300,
439        2800,
440        MeasurementInputUnit::Cm,
441        FIT | CLOTH,
442        "Fingertip to fingertip.",
443    ),
444    // Torso / clothing
445    spec(
446        "neck_mm",
447        "Neck circumference",
448        MeasurementGroup::Torso,
449        150,
450        700,
451        MeasurementInputUnit::Cm,
452        CLOTH,
453        "Shirt collar.",
454    ),
455    spec(
456        "neck_base_mm",
457        "Neck-base circumference",
458        MeasurementGroup::Torso,
459        200,
460        800,
461        MeasurementInputUnit::Cm,
462        CLOTH,
463        "Around the neck-shoulder join.",
464    ),
465    spec(
466        "shoulder_width_mm",
467        "Shoulder breadth",
468        MeasurementGroup::Torso,
469        200,
470        700,
471        MeasurementInputUnit::Cm,
472        FIT | CLOTH,
473        "Biacromial, bone to bone.",
474    ),
475    spec(
476        "across_back_mm",
477        "Across back",
478        MeasurementGroup::Torso,
479        200,
480        700,
481        MeasurementInputUnit::Cm,
482        CLOTH,
483        "Armscye to armscye, back.",
484    ),
485    spec(
486        "across_chest_mm",
487        "Across chest",
488        MeasurementGroup::Torso,
489        200,
490        700,
491        MeasurementInputUnit::Cm,
492        CLOTH,
493        "Armscye to armscye, front.",
494    ),
495    spec(
496        "chest_mm",
497        "Chest / bust circumference",
498        MeasurementGroup::Torso,
499        300,
500        2000,
501        MeasurementInputUnit::Cm,
502        FIT | CLOTH,
503        "Fullest bust / chest.",
504    ),
505    spec(
506        "underbust_mm",
507        "Underbust circumference",
508        MeasurementGroup::Torso,
509        300,
510        1800,
511        MeasurementInputUnit::Cm,
512        CLOTH,
513        "Band measurement. Not a cup size.",
514    ),
515    spec(
516        "waist_mm",
517        "Waist circumference",
518        MeasurementGroup::Torso,
519        300,
520        2000,
521        MeasurementInputUnit::Cm,
522        FIT | CLOTH,
523        "Natural waist.",
524    ),
525    spec(
526        "abdomen_mm",
527        "Abdomen / high-hip circumference",
528        MeasurementGroup::Torso,
529        300,
530        2200,
531        MeasurementInputUnit::Cm,
532        CLOTH,
533        "About 8 cm below the waist.",
534    ),
535    spec(
536        "hip_mm",
537        "Hip / seat circumference",
538        MeasurementGroup::Torso,
539        300,
540        2200,
541        MeasurementInputUnit::Cm,
542        FIT | CLOTH,
543        "Fullest seat.",
544    ),
545    spec(
546        "nape_to_waist_mm",
547        "Nape to waist",
548        MeasurementGroup::Torso,
549        200,
550        700,
551        MeasurementInputUnit::Cm,
552        CLOTH,
553        "Cervicale to back waist.",
554    ),
555    spec(
556        "front_waist_length_mm",
557        "Front waist length",
558        MeasurementGroup::Torso,
559        200,
560        700,
561        MeasurementInputUnit::Cm,
562        CLOTH,
563        "Side-neck to front waist.",
564    ),
565    spec(
566        "rise_mm",
567        "Rise / crotch depth",
568        MeasurementGroup::Torso,
569        150,
570        500,
571        MeasurementInputUnit::Cm,
572        CLOTH,
573        "Seated waist to chair, or crotch depth.",
574    ),
575    spec(
576        "outseam_mm",
577        "Outseam",
578        MeasurementGroup::Torso,
579        400,
580        1400,
581        MeasurementInputUnit::Cm,
582        CLOTH,
583        "Waist to ankle, outside leg.",
584    ),
585    spec(
586        "shoulder_girth_mm",
587        "Shoulder / overarm girth",
588        MeasurementGroup::Torso,
589        600,
590        2200,
591        MeasurementInputUnit::Cm,
592        CLOTH,
593        "Around both shoulders and chest.",
594    ),
595    // Arms
596    spec(
597        "sleeve_mm",
598        "Sleeve length",
599        MeasurementGroup::Arms,
600        300,
601        900,
602        MeasurementInputUnit::Cm,
603        CLOTH,
604        "Shoulder point to wrist.",
605    ),
606    spec(
607        "upper_arm_length_mm",
608        "Upper-arm length",
609        MeasurementGroup::Arms,
610        150,
611        500,
612        MeasurementInputUnit::Cm,
613        CLOTH,
614        "Shoulder to elbow.",
615    ),
616    spec(
617        "underarm_length_mm",
618        "Underarm length",
619        MeasurementGroup::Arms,
620        250,
621        800,
622        MeasurementInputUnit::Cm,
623        CLOTH,
624        "Armpit to wrist.",
625    ),
626    spec(
627        "elbow_to_wrist_mm",
628        "Elbow to wrist",
629        MeasurementGroup::Arms,
630        120,
631        400,
632        MeasurementInputUnit::Cm,
633        CLOTH,
634        "Forearm length.",
635    ),
636    spec(
637        "biceps_mm",
638        "Upper-arm / biceps circumference",
639        MeasurementGroup::Arms,
640        120,
641        700,
642        MeasurementInputUnit::Cm,
643        CLOTH,
644        "Fullest upper arm.",
645    ),
646    spec(
647        "elbow_girth_mm",
648        "Elbow circumference",
649        MeasurementGroup::Arms,
650        120,
651        500,
652        MeasurementInputUnit::Cm,
653        CLOTH,
654        "Around the bent elbow.",
655    ),
656    spec(
657        "forearm_mm",
658        "Forearm circumference",
659        MeasurementGroup::Arms,
660        100,
661        500,
662        MeasurementInputUnit::Cm,
663        CLOTH | GLOVE,
664        "Fullest forearm.",
665    ),
666    spec(
667        "wrist_mm",
668        "Wrist circumference",
669        MeasurementGroup::Arms,
670        80,
671        300,
672        MeasurementInputUnit::Cm,
673        CLOTH | GLOVE,
674        "Just distal to the styloid.",
675    ),
676    // Legs
677    spec(
678        "inseam_mm",
679        "Inside leg / inseam",
680        MeasurementGroup::Legs,
681        300,
682        1200,
683        MeasurementInputUnit::Cm,
684        FIT | CLOTH,
685        "Crotch to floor, or trouser inseam.",
686    ),
687    spec(
688        "thigh_mm",
689        "Thigh circumference",
690        MeasurementGroup::Legs,
691        250,
692        1200,
693        MeasurementInputUnit::Cm,
694        CLOTH,
695        "Fullest thigh.",
696    ),
697    spec(
698        "mid_thigh_mm",
699        "Mid-thigh circumference",
700        MeasurementGroup::Legs,
701        200,
702        1100,
703        MeasurementInputUnit::Cm,
704        CLOTH,
705        "Halfway hip to knee.",
706    ),
707    spec(
708        "knee_girth_mm",
709        "Knee circumference",
710        MeasurementGroup::Legs,
711        200,
712        800,
713        MeasurementInputUnit::Cm,
714        CLOTH,
715        "Around the knee.",
716    ),
717    spec(
718        "calf_mm",
719        "Calf circumference",
720        MeasurementGroup::Legs,
721        180,
722        700,
723        MeasurementInputUnit::Cm,
724        CLOTH,
725        "Fullest calf.",
726    ),
727    spec(
728        "ankle_mm",
729        "Ankle circumference",
730        MeasurementGroup::Legs,
731        120,
732        400,
733        MeasurementInputUnit::Cm,
734        CLOTH | FOOTW,
735        "Minimum ankle girth.",
736    ),
737    // Head / helmet / eyewear
738    spec(
739        "head_mm",
740        "Head circumference",
741        MeasurementGroup::Head,
742        280,
743        750,
744        MeasurementInputUnit::Cm,
745        HEADW,
746        "Above the brow, helmet tape.",
747    ),
748    spec(
749        "head_length_mm",
750        "Head length",
751        MeasurementGroup::Head,
752        120,
753        280,
754        MeasurementInputUnit::Cm,
755        HEADW,
756        "Glabella to occiput.",
757    ),
758    spec(
759        "head_breadth_mm",
760        "Head breadth",
761        MeasurementGroup::Head,
762        100,
763        220,
764        MeasurementInputUnit::Cm,
765        HEADW,
766        "Maximum cranial breadth.",
767    ),
768    spec(
769        "head_height_mm",
770        "Head height",
771        MeasurementGroup::Head,
772        150,
773        300,
774        MeasurementInputUnit::Cm,
775        HEADW,
776        "Vertex to menton, or tragion to vertex.",
777    ),
778    spec(
779        "face_length_mm",
780        "Face length",
781        MeasurementGroup::Head,
782        80,
783        180,
784        MeasurementInputUnit::Cm,
785        HEADW | EYE,
786        "Nasion to menton.",
787    ),
788    spec(
789        "bizygomatic_mm",
790        "Face width",
791        MeasurementGroup::Head,
792        90,
793        180,
794        MeasurementInputUnit::Cm,
795        HEADW | EYE,
796        "Bizygomatic breadth.",
797    ),
798    spec(
799        "sagittal_arc_mm",
800        "Sagittal arc",
801        MeasurementGroup::Head,
802        250,
803        450,
804        MeasurementInputUnit::Cm,
805        HEADW,
806        "Glabella over vertex to inion.",
807    ),
808    spec(
809        "bitragion_arc_mm",
810        "Bitragion coronal arc",
811        MeasurementGroup::Head,
812        250,
813        450,
814        MeasurementInputUnit::Cm,
815        HEADW,
816        "Ear to ear over the crown.",
817    ),
818    spec(
819        "interpupillary_mm",
820        "Interpupillary distance",
821        MeasurementGroup::Head,
822        40,
823        90,
824        MeasurementInputUnit::Mm,
825        EYE,
826        "IPD in millimetres.",
827    ),
828    // Hands
829    spec(
830        "hand_length_mm",
831        "Hand length",
832        MeasurementGroup::Hands,
833        100,
834        280,
835        MeasurementInputUnit::Cm,
836        GLOVE,
837        "Wrist crease to middle fingertip.",
838    ),
839    spec(
840        "palm_length_mm",
841        "Palm length",
842        MeasurementGroup::Hands,
843        60,
844        160,
845        MeasurementInputUnit::Cm,
846        GLOVE,
847        "Wrist crease to palmar digital crease.",
848    ),
849    spec(
850        "hand_breadth_mm",
851        "Hand breadth",
852        MeasurementGroup::Hands,
853        50,
854        140,
855        MeasurementInputUnit::Cm,
856        GLOVE,
857        "Across the metacarpals.",
858    ),
859    spec(
860        "hand_circ_mm",
861        "Hand circumference",
862        MeasurementGroup::Hands,
863        120,
864        320,
865        MeasurementInputUnit::Cm,
866        GLOVE,
867        "Around the knuckles, excluding thumb.",
868    ),
869    spec(
870        "middle_finger_mm",
871        "Middle-finger length",
872        MeasurementGroup::Hands,
873        40,
874        120,
875        MeasurementInputUnit::Cm,
876        GLOVE,
877        "Proximal crease to tip.",
878    ),
879    spec(
880        "thumb_circ_mm",
881        "Thumb circumference",
882        MeasurementGroup::Hands,
883        40,
884        120,
885        MeasurementInputUnit::Cm,
886        GLOVE,
887        "Mid-thumb.",
888    ),
889    spec(
890        "ring_finger_circ_mm",
891        "Ring-finger circumference",
892        MeasurementGroup::Hands,
893        35,
894        100,
895        MeasurementInputUnit::Mm,
896        RING,
897        "Preferred ring finger, millimetres.",
898    ),
899    spec(
900        "ring_finger_left_circ_mm",
901        "Left ring-finger circumference",
902        MeasurementGroup::Hands,
903        35,
904        100,
905        MeasurementInputUnit::Mm,
906        RING,
907        "When the hands differ.",
908    ),
909    spec(
910        "ring_finger_right_circ_mm",
911        "Right ring-finger circumference",
912        MeasurementGroup::Hands,
913        35,
914        100,
915        MeasurementInputUnit::Mm,
916        RING,
917        "When the hands differ.",
918    ),
919    // Feet
920    spec(
921        "foot_mm",
922        "Foot length",
923        MeasurementGroup::Feet,
924        80,
925        400,
926        MeasurementInputUnit::Cm,
927        FOOTW,
928        "Heel to longest toe. Fallback if left/right omitted.",
929    ),
930    spec(
931        "foot_left_mm",
932        "Left foot length",
933        MeasurementGroup::Feet,
934        80,
935        400,
936        MeasurementInputUnit::Cm,
937        FOOTW,
938        "Prefer this plus right.",
939    ),
940    spec(
941        "foot_right_mm",
942        "Right foot length",
943        MeasurementGroup::Feet,
944        80,
945        400,
946        MeasurementInputUnit::Cm,
947        FOOTW,
948        "Prefer this plus left.",
949    ),
950    spec(
951        "foot_width_mm",
952        "Foot width (ball)",
953        MeasurementGroup::Feet,
954        50,
955        160,
956        MeasurementInputUnit::Cm,
957        FOOTW,
958        "Ball width. Fallback if left/right omitted.",
959    ),
960    spec(
961        "foot_width_left_mm",
962        "Left foot width",
963        MeasurementGroup::Feet,
964        50,
965        160,
966        MeasurementInputUnit::Cm,
967        FOOTW,
968        "",
969    ),
970    spec(
971        "foot_width_right_mm",
972        "Right foot width",
973        MeasurementGroup::Feet,
974        50,
975        160,
976        MeasurementInputUnit::Cm,
977        FOOTW,
978        "",
979    ),
980    spec(
981        "heel_width_mm",
982        "Heel width",
983        MeasurementGroup::Feet,
984        40,
985        120,
986        MeasurementInputUnit::Cm,
987        FOOTW,
988        "",
989    ),
990    spec(
991        "ball_girth_mm",
992        "Ball girth",
993        MeasurementGroup::Feet,
994        120,
995        320,
996        MeasurementInputUnit::Cm,
997        FOOTW,
998        "Around the metatarsal heads.",
999    ),
1000    spec(
1001        "instep_girth_mm",
1002        "Instep girth",
1003        MeasurementGroup::Feet,
1004        120,
1005        320,
1006        MeasurementInputUnit::Cm,
1007        FOOTW,
1008        "Around the arch / instep.",
1009    ),
1010    spec(
1011        "arch_length_mm",
1012        "Arch length",
1013        MeasurementGroup::Feet,
1014        80,
1015        280,
1016        MeasurementInputUnit::Cm,
1017        FOOTW,
1018        "Heel to ball (Brannock arch).",
1019    ),
1020    spec(
1021        "toe_height_mm",
1022        "Toe-box height",
1023        MeasurementGroup::Feet,
1024        15,
1025        60,
1026        MeasurementInputUnit::Mm,
1027        FOOTW,
1028        "Vertical clearance at the toes, millimetres.",
1029    ),
1030];
1031
1032const fn spec(
1033    id: &'static str,
1034    label: &'static str,
1035    group: MeasurementGroup,
1036    lo: u32,
1037    hi: u32,
1038    input: MeasurementInputUnit,
1039    uses: u16,
1040    hint: &'static str,
1041) -> MeasurementSpec {
1042    MeasurementSpec {
1043        id,
1044        label,
1045        group,
1046        lo,
1047        hi,
1048        input,
1049        uses,
1050        hint,
1051    }
1052}
1053
1054const fn bit(use_: MeasurementUse) -> u16 {
1055    match use_ {
1056        MeasurementUse::AnatomyFit => FIT,
1057        MeasurementUse::Clothing => CLOTH,
1058        MeasurementUse::Footwear => FOOTW,
1059        MeasurementUse::Headwear => HEADW,
1060        MeasurementUse::Gloves => GLOVE,
1061        MeasurementUse::Eyewear => EYE,
1062        MeasurementUse::Rings => RING,
1063    }
1064}
1065
1066fn decode_uses(bits: u16) -> Vec<MeasurementUse> {
1067    [
1068        MeasurementUse::AnatomyFit,
1069        MeasurementUse::Clothing,
1070        MeasurementUse::Footwear,
1071        MeasurementUse::Headwear,
1072        MeasurementUse::Gloves,
1073        MeasurementUse::Eyewear,
1074        MeasurementUse::Rings,
1075    ]
1076    .into_iter()
1077    .filter(|u| bits & bit(*u) != 0)
1078    .collect()
1079}
1080
1081fn max_opt(a: Option<u16>, b: Option<u16>) -> Option<u16> {
1082    match (a, b) {
1083        (Some(x), Some(y)) => Some(x.max(y)),
1084        (Some(x), None) => Some(x),
1085        (None, Some(y)) => Some(y),
1086        (None, None) => None,
1087    }
1088}
1089
1090/// Grouped catalog for the Care form and for clothing/helmet consumers.
1091pub fn measurement_catalog_json() -> serde_json::Value {
1092    let mut groups = Vec::new();
1093    for group in [
1094        MeasurementGroup::WholeBody,
1095        MeasurementGroup::Torso,
1096        MeasurementGroup::Arms,
1097        MeasurementGroup::Legs,
1098        MeasurementGroup::Head,
1099        MeasurementGroup::Hands,
1100        MeasurementGroup::Feet,
1101    ] {
1102        let fields: Vec<serde_json::Value> = MEASUREMENT_CATALOG
1103            .iter()
1104            .filter(|s| s.group == group)
1105            .map(|s| {
1106                serde_json::json!({
1107                    "id": s.id,
1108                    "label": s.label,
1109                    "hint": s.hint,
1110                    "lo": s.lo,
1111                    "hi": s.hi,
1112                    "input_unit": s.input,
1113                    "store_unit": s.store_unit(),
1114                    "uses": s.uses_list(),
1115                })
1116            })
1117            .collect();
1118        groups.push(serde_json::json!({
1119            "id": group,
1120            "label": group.label(),
1121            "hint": group.hint(),
1122            "fields": fields,
1123        }));
1124    }
1125    serde_json::json!({
1126        "version": 1,
1127        "honesty": "Fill in what you have. Clothing, footwear, helmets, gloves, rings, and glasses in Qualia read this same record. Anatomy currently reshapes the reference body from height, sitting height, inseam, arm span, shoulders, chest, waist, and hip only.",
1128        "groups": groups,
1129        "field_count": MEASUREMENT_CATALOG.len(),
1130    })
1131}
1132
1133#[cfg(test)]
1134mod tests {
1135    use super::*;
1136
1137    #[test]
1138    fn catalog_ids_are_unique_and_cover_the_struct() {
1139        let mut ids = std::collections::BTreeSet::new();
1140        for spec in MEASUREMENT_CATALOG {
1141            assert!(ids.insert(spec.id), "duplicate catalog id {}", spec.id);
1142            assert!(spec.lo < spec.hi);
1143        }
1144        let populated = fully_populated();
1145        let json = serde_json::to_value(&populated).unwrap();
1146        let struct_keys: std::collections::BTreeSet<&str> = json
1147            .as_object()
1148            .unwrap()
1149            .keys()
1150            .map(|k| k.as_str())
1151            .collect();
1152        let catalog_keys: std::collections::BTreeSet<&str> =
1153            MEASUREMENT_CATALOG.iter().map(|s| s.id).collect();
1154        assert_eq!(
1155            struct_keys, catalog_keys,
1156            "every BodyMeasurements field must be in MEASUREMENT_CATALOG and vice versa"
1157        );
1158    }
1159
1160    #[test]
1161    fn clothing_footwear_and_helmet_slices_are_useful() {
1162        let mut m = BodyMeasurements::default();
1163        m.chest_mm = Some(980);
1164        m.sleeve_mm = Some(620);
1165        m.neck_mm = Some(390);
1166        m.foot_left_mm = Some(265);
1167        m.foot_right_mm = Some(268);
1168        m.head_mm = Some(570);
1169        m.head_length_mm = Some(196);
1170        assert!(
1171            m.values_for(MeasurementUse::Clothing)
1172                .iter()
1173                .any(|(s, _)| s.id == "sleeve_mm")
1174        );
1175        assert!(
1176            m.values_for(MeasurementUse::Footwear)
1177                .iter()
1178                .any(|(s, _)| s.id == "foot_right_mm")
1179        );
1180        assert_eq!(m.foot_length_mm(), Some(268));
1181        assert!(
1182            m.values_for(MeasurementUse::Headwear)
1183                .iter()
1184                .any(|(s, _)| s.id == "head_mm")
1185        );
1186        assert!(
1187            !m.values_for(MeasurementUse::AnatomyFit)
1188                .iter()
1189                .any(|(s, _)| s.id == "sleeve_mm")
1190        );
1191    }
1192
1193    #[test]
1194    fn validate_uses_per_field_ranges() {
1195        let mut m = BodyMeasurements::default();
1196        m.ring_finger_circ_mm = Some(2000);
1197        assert!(m.validate().is_err());
1198        m.ring_finger_circ_mm = Some(55);
1199        assert!(m.validate().is_ok());
1200        m.stature_mm = Some(1600);
1201        m.sitting_height_mm = Some(1600);
1202        assert!(m.validate().is_err());
1203    }
1204
1205    #[test]
1206    fn legacy_json_still_loads() {
1207        let v: BodyMeasurements =
1208            serde_json::from_str(r#"{"stature_mm":1720,"chest_mm":940,"foot_mm":255}"#).unwrap();
1209        assert_eq!(v.stature_mm, Some(1720));
1210        assert_eq!(v.chest_mm, Some(940));
1211        assert_eq!(v.foot_mm, Some(255));
1212        assert!(v.sleeve_mm.is_none());
1213    }
1214
1215    #[test]
1216    fn catalog_json_lists_every_group() {
1217        let j = measurement_catalog_json();
1218        assert_eq!(j["field_count"], MEASUREMENT_CATALOG.len());
1219        assert_eq!(j["groups"].as_array().unwrap().len(), 7);
1220        assert!(MEASUREMENT_CATALOG.len() >= 60);
1221    }
1222
1223    fn fully_populated() -> BodyMeasurements {
1224        let mut obj = serde_json::Map::new();
1225        for spec in MEASUREMENT_CATALOG {
1226            obj.insert(spec.id.to_string(), serde_json::json!(spec.lo + 1));
1227        }
1228        serde_json::from_value(serde_json::Value::Object(obj)).unwrap()
1229    }
1230}