danwi 0.4.2

Zero-cost dimensional analysis library with SI units, compile-time checking, and no_std support
Documentation
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
//! The [`units!`](crate::units) macro for declarative unit definitions.
//!
//! The crate's own SI set lives in [`super::si`]; downstream crates invoke
//! the same macro to add their own units. Helper macros prefixed with
//! `__danwi` are implementation details and not part of the public API.

/// Define units: marker types, constants, `Quantity` aliases, and extension
/// traits.
///
/// # Grammar
///
/// ```text
/// units! {
///     /// Optional doc comment, attached to the unit's marker type.
///     name: Dimension {
///         symbol: ident,            // constant name, e.g. `V`
///         display: "str",           // display symbol if it can't be an ident (default: stringify!(symbol))
///         scale: num / den,         // value in SI base units (default: 1/1)
///         offset: num / den,        // affine offset in SI base units (default: 0/1)
///         prefixes: all | none,     // generate SI-prefixed variants (default: none)
///     },
/// }
/// ```
///
/// `display`, `scale`, `offset`, and `prefixes` are optional but must appear
/// in that order. For each unit this expands to:
///
/// - a PascalCase marker type implementing [`UnitDef`](crate::unit::UnitDef)
///   (e.g. `volt` → `Volt`);
/// - a constant named after the symbol in `pub mod constants`, plus one per SI
///   prefix when `prefixes: all` (`V`, `kV`, `mV`, ...);
/// - a `Quantity` alias per enabled scalar in `pub mod types`
///   (`types::f64::Volt`);
/// - `F32QuantityExt`/`F64QuantityExt` traits in `pub mod ext` with literal
///   methods: symbol and name forms per prefix for `prefixes: all` units
///   (`5.0.kV()`, `5.0.kilovolt()`), name form only for `prefixes: none` units
///   (`5.0.minute()`).
///
/// Offset units (Celsius) must use `prefixes: none`; a prefixed affine unit
/// has no coherent meaning, and the macro rejects it at compile time.
///
/// One invocation per module; the generated `constants`/`types`/`ext`
/// modules would otherwise collide. For `prefixes: all` units the symbol
/// must differ from the unit's name, since both method forms are generated
/// (`symbol: stick` on a `stick` unit would emit `fn stick` twice).
///
/// # Example
///
/// ```
/// mod imperial {
///     use danwi::dimension::Length;
///
///     danwi::units! {
///         /// Exactly 201.168 m.
///         furlong: Length { symbol: fur, scale: 201_168 / 1_000 },
///     }
/// }
///
/// use imperial::ext::F64QuantityExt as _;
///
/// let race = 2.0.furlong() + 3.0.furlong();
/// assert_eq!(race.to(imperial::constants::fur), 5.0);
/// assert_eq!(race, 5.0_f64 * imperial::constants::fur);
/// ```
#[macro_export]
macro_rules! units {
    (
        $(
            $(#[$meta:meta])*
            $name:ident : $dim:ty {
                symbol: $sym:ident
                $(, display: $disp:literal)?
                $(, scale: $sn:literal $(/ $sd:literal)?)?
                $(, offset: $on:literal $(/ $od:literal)?)?
                $(, prefixes: $pfx:ident)?
                $(,)?
            }
        ),* $(,)?
    ) => {
        $(
            $crate::__private::paste! {
                // An uninhabited enum: markers are only ever used at the
                // type level, and unlike a unit struct an enum adds no
                // value-namespace entry that could collide with the unit's
                // constant (`Ohm` the marker vs `Ohm` the constant).
                $(#[$meta])*
                pub enum [<$name:camel>] {}

                impl $crate::unit::UnitDef for [<$name:camel>] {
                    type Dim = $dim;

                    const SCALE_NUM: i128 = $crate::unit::reduce_num(
                        $crate::__danwi_ratio_num!($($sn $(/ $sd)?)?),
                        $crate::__danwi_ratio_den!($($sn $(/ $sd)?)?),
                    );
                    const SCALE_DEN: i128 = $crate::unit::reduce_den(
                        $crate::__danwi_ratio_num!($($sn $(/ $sd)?)?),
                        $crate::__danwi_ratio_den!($($sn $(/ $sd)?)?),
                    );
                    const OFFSET_NUM: i128 = $crate::__danwi_offset_num!($($on $(/ $od)?)?);
                    const OFFSET_DEN: i128 = $crate::__danwi_offset_den!($($on $(/ $od)?)?);

                    const SYMBOL: &'static str = $crate::__danwi_symbol_str!($sym $(, $disp)?);
                }

                const _: () = assert!(
                    <[<$name:camel>] as $crate::unit::UnitDef>::OFFSET_DEN > 0,
                    "unit offset denominator must be positive",
                );

                $crate::__danwi_validate_prefixes! { ($($pfx)?) }
                $crate::__danwi_if_all! { ($($pfx)?)
                    impl $crate::unit::prefix::Prefixable for [<$name:camel>] {}

                    // A prefixed affine unit ("millicelsius") has no
                    // coherent meaning.
                    const _: () = assert!(
                        <[<$name:camel>] as $crate::unit::UnitDef>::OFFSET_NUM == 0,
                        "`prefixes: all` requires a zero-offset unit",
                    );
                }
            }
        )*

        /// Unit constants, e.g. `V`, `kV`, `mV`.
        pub mod constants {
            #![allow(non_upper_case_globals)]

            use super::*;

            $(
                $crate::__private::paste! {
                    pub const $sym: $crate::unit::Unit<[<$name:camel>]> =
                        $crate::unit::Unit::new();
                }
                $crate::__danwi_if_all! { ($($pfx)?)
                    $crate::__danwi_per_prefix! { const [$name $sym] }
                }
            )*
        }

        /// `Quantity` type aliases per scalar type, e.g. `types::f64::Volt`.
        pub mod types {
            pub use super::*;

            $crate::__danwi_if_f32! {
                pub mod f32 {
                    pub use super::*;

                    $(
                        $crate::__private::paste! {
                            pub type [<$name:camel>] = $crate::Quantity<
                                f32,
                                <super::super::[<$name:camel>] as $crate::unit::UnitDef>::Dim,
                            >;
                        }
                    )*
                }
            }

            $crate::__danwi_if_f64! {
                pub mod f64 {
                    pub use super::*;

                    $(
                        $crate::__private::paste! {
                            pub type [<$name:camel>] = $crate::Quantity<
                                f64,
                                <super::super::[<$name:camel>] as $crate::unit::UnitDef>::Dim,
                            >;
                        }
                    )*
                }
            }
        }

        /// Extension traits for building quantities from numeric literals,
        /// e.g. `5.0.kV()`.
        pub mod ext {
            #![allow(non_snake_case)]

            use super::{constants::*, *};

            $crate::__danwi_if_f32! {
                pub trait F32QuantityExt {
                    $( $crate::__danwi_ext_decl! { ($($pfx)?) f32, $name, $sym } )*
                }

                impl F32QuantityExt for f32 {
                    $( $crate::__danwi_ext_impl! { ($($pfx)?) f32, $name, $sym } )*
                }
            }

            $crate::__danwi_if_f64! {
                pub trait F64QuantityExt {
                    $( $crate::__danwi_ext_decl! { ($($pfx)?) f64, $name, $sym } )*
                }

                impl F64QuantityExt for f64 {
                    $( $crate::__danwi_ext_impl! { ($($pfx)?) f64, $name, $sym } )*
                }
            }
        }
    };
}

// Rational literals: `1_000`, `254 / 10_000`, or nothing (defaults below).

#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_ratio_num {
    () => {
        1
    };
    ($n:literal) => {
        $n
    };
    ($n:literal / $d:literal) => {
        $n
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_ratio_den {
    () => {
        1
    };
    ($n:literal) => {
        1
    };
    ($n:literal / $d:literal) => {
        $d
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_offset_num {
    () => {
        0
    };
    ($n:literal) => {
        $n
    };
    ($n:literal / $d:literal) => {
        $n
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_offset_den {
    () => {
        1
    };
    ($n:literal) => {
        1
    };
    ($n:literal / $d:literal) => {
        $d
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_symbol_str {
    ($sym:ident) => {
        stringify!($sym)
    };
    ($sym:ident, $disp:literal) => {
        $disp
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_validate_prefixes {
    (()) => {};
    ((all)) => {};
    ((none)) => {};
    (($bad:ident)) => {
        compile_error!(concat!(
            "`prefixes` must be `all` or `none`, got `",
            stringify!($bad),
            "`",
        ));
    };
}

/// Expands its body only for `prefixes: all` units.
#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_if_all {
    (() $($body:tt)*) => {};
    ((none) $($body:tt)*) => {};
    ((all) $($body:tt)*) => { $($body)* };
    (($bad:ident) $($body:tt)*) => {}; // already rejected by __danwi_validate_prefixes
}

// Feature-dependent expansion. Which definition of these macros exists is
// decided by *this* crate's features, so downstream `units!` invocations
// follow danwi's scalar support rather than the caller's feature set.

#[cfg(feature = "f32")]
#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_if_f32 {
    ($($body:tt)*) => { $($body)* };
}

#[cfg(not(feature = "f32"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_if_f32 {
    ($($body:tt)*) => {};
}

#[cfg(feature = "f64")]
#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_if_f64 {
    ($($body:tt)*) => { $($body)* };
}

#[cfg(not(feature = "f64"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_if_f64 {
    ($($body:tt)*) => {};
}

/// Invokes `__danwi_prefix_item!` once per SI prefix with the prefix's
/// symbol ident, name ident, and marker type. `$ctx` carries the per-unit
/// tokens through unchanged. The atto symbol is spelled out because `as`
/// (atto + second) is a keyword.
#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_per_prefix {
    ($kind:ident [$($ctx:tt)*]) => {
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] Q    quetta Quetta }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] R    ronna  Ronna }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] Y    yotta  Yotta }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] Z    zetta  Zetta }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] E    exa    Exa }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] P    peta   Peta }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] T    tera   Tera }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] G    giga   Giga }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] M    mega   Mega }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] k    kilo   Kilo }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] h    hecto  Hecto }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] da   deca   Deca }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] d    deci   Deci }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] c    centi  Centi }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] m    milli  Milli }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] u    micro  Micro }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] n    nano   Nano }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] p    pico   Pico }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] f    femto  Femto }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] atto atto   Atto }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] z    zepto  Zepto }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] y    yocto  Yocto }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] r    ronto  Ronto }
        $crate::__danwi_prefix_item! { $kind [$($ctx)*] q    quecto Quecto }
    };
}

// One prefixed item. `const` emits a unit constant; `decl`/`impl` emit the
// symbol and name extension methods for the scalar type in `$ctx`, so both
// float traits expand from the same source.
#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_prefix_item {
    (const [$name:ident $sym:ident] $psym:ident $pname:ident $ptype:ident) => {
        $crate::__private::paste! {
            pub const [<$psym $sym>]: $crate::unit::Unit<
                $crate::unit::prefix::$ptype<[<$name:camel>]>,
            > = $crate::unit::Unit::new();
        }
    };
    (decl [$fl:ty, $name:ident $sym:ident] $psym:ident $pname:ident $ptype:ident) => {
        $crate::__private::paste! {
            fn [<$psym $sym>](self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>;
            fn [<$pname $name:lower>](self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>;
        }
    };
    (impl [$fl:ty, $name:ident $sym:ident] $psym:ident $pname:ident $ptype:ident) => {
        $crate::__private::paste! {
            #[inline(always)]
            fn [<$psym $sym>](self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>
            {
                self * [<$psym $sym>]
            }

            #[inline(always)]
            fn [<$pname $name:lower>](self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>
            {
                self * [<$psym $sym>]
            }
        }
    };
}

// Extension-trait items per unit: symbol + name methods for every prefix
// when `prefixes: all`, just the base name method for `prefixes: none`.
// (Symbol methods are skipped for unprefixed units to avoid colliding with
// inherent float methods, e.g. a `.min()` method for minutes would shadow
// `f64::min`.)

#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_ext_decl {
    (() $fl:ty, $name:ident, $sym:ident) => {
        $crate::__danwi_ext_decl! { (none) $fl, $name, $sym }
    };
    ((none) $fl:ty, $name:ident, $sym:ident) => {
        $crate::__private::paste! {
            fn [<$name:lower>](self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>;
        }
    };
    ((all) $fl:ty, $name:ident, $sym:ident) => {
        $crate::__private::paste! {
            fn $sym(self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>;
            fn [<$name:lower>](self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>;
        }
        $crate::__danwi_per_prefix! { decl [$fl, $name $sym] }
    };
    (($bad:ident) $fl:ty, $name:ident, $sym:ident) => {};
}

#[doc(hidden)]
#[macro_export]
macro_rules! __danwi_ext_impl {
    (() $fl:ty, $name:ident, $sym:ident) => {
        $crate::__danwi_ext_impl! { (none) $fl, $name, $sym }
    };
    ((none) $fl:ty, $name:ident, $sym:ident) => {
        $crate::__private::paste! {
            #[inline(always)]
            fn [<$name:lower>](self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>
            {
                self * $sym
            }
        }
    };
    ((all) $fl:ty, $name:ident, $sym:ident) => {
        $crate::__private::paste! {
            #[inline(always)]
            fn $sym(self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>
            {
                self * $sym
            }

            #[inline(always)]
            fn [<$name:lower>](self)
                -> $crate::Quantity<$fl, <[<$name:camel>] as $crate::unit::UnitDef>::Dim>
            {
                self * $sym
            }
        }
        $crate::__danwi_per_prefix! { impl [$fl, $name $sym] }
    };
    (($bad:ident) $fl:ty, $name:ident, $sym:ident) => {};
}