dusk_core/dusk.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4//
5// Copyright (c) DUSK NETWORK. All rights reserved.
6
7//! Dusk denomination.
8
9const DUSK_UNIT: f64 = 1_000_000_000.0;
10
11/// The minimum increment of Dusk.
12pub const LUX: Dusk = dusk(1.0 / DUSK_UNIT);
13
14/// The Dusk denomination. Use the [`dusk`] function to convert from floating
15/// point format, and the [`from_dusk`] function to convert back to Dusk.
16///
17/// Values of Dusk should *never* be assigned directly. Instead they should use
18/// a call to the [`dusk`] function. If increments of the smallest denomination
19/// are desired, the [`LUX`] constant can be used.
20pub type Dusk = u64;
21
22/// Converts from floating point format to Dusk.
23#[must_use]
24#[allow(clippy::cast_possible_truncation)]
25#[allow(clippy::cast_sign_loss)]
26pub const fn dusk(value: f64) -> Dusk {
27 (value * DUSK_UNIT) as Dusk
28}
29
30/// Converts from Dusk to floating point format.
31#[must_use]
32#[allow(clippy::cast_precision_loss)]
33pub const fn from_dusk(dusk: Dusk) -> f64 {
34 dusk as f64 / DUSK_UNIT
35}
36
37#[cfg(test)]
38mod tests {
39 use super::*;
40
41 #[test]
42 fn from_to_dusk() {
43 let value = 5f64;
44 let dusk_value = dusk(value);
45
46 assert_eq!(value, from_dusk(dusk_value));
47 }
48
49 #[test]
50 fn lux_is_one() {
51 assert_eq!(LUX, 1);
52 }
53}