millimeter 0.1.0

Primitive type with millimeter unit attached
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
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(has_const_float_classify, feature(const_float_classify))]
#![allow(uncommon_codepoints)]
#![warn(rust_2018_idioms, unreachable_pub)]
#![forbid(unsafe_code)]

//! This crate provides [`mm`] and [`mm2`] newtype structs. These can be used both as an indication
//! that a value is expected to have a certain unit, as well as to prove at compile time that your
//! computation yields the unit you expect it to.
//!
//! # Example
//!
//! ```rust
//! use millimeter::{mm, mm2, Unit};
//!
//! #[derive(Clone, Copy, Default)]
//! pub struct Point {
//! 	x: mm,
//! 	y: mm
//! }
//!
//! #[derive(Clone, Copy)]
//! pub struct Rectangle {
//! 	top_left: Point,
//! 	bottom_right: Point
//! }
//!
//! impl Rectangle {
//! 	pub fn one_inch_square(top_left: Point) -> Self {
//! 		Self {
//! 			top_left,
//! 			bottom_right: Point {
//! 				x: top_left.x + 1.0.inch(),
//! 				y: top_left.y + 1.0.inch()
//! 			}
//! 		}
//! 	}
//!
//! 	pub fn area(&self) -> mm2 {
//! 		(self.bottom_right.x - self.top_left.x) * (self.bottom_right.y - self.top_left.y)
//! 	}
//!
//! 	pub fn diagonal_len(&self) -> mm {
//! 		let a = self.bottom_right.x - self.top_left.x;
//! 		let b = self.bottom_right.y - self.top_left.y;
//! 		(a*a + b*b).sqrt()
//! 	}
//! }
//! # assert_eq!(Rectangle::one_inch_square(Point::default()).area(), 1.0.inch2());
//! # assert_eq!(Rectangle::one_inch_square(Point::default()).diagonal_len(), 2f32.sqrt().inch());
//! ```
//!
//!  [`mm`]: crate::mm
//!  [`mm2`]: crate::mm2

use core::{
	cmp::{Eq, Ord, Ordering},
	fmt::{self, Debug, Display, Formatter},
	hash::{Hash, Hasher},
	ops::{
		Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign
	},
	str::FromStr
};
use paste::paste;
#[cfg(feature = "serde")]
use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "std")]
use thiserror::Error;

#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "std", derive(Error))]
#[cfg_attr(feature = "std", error("non-finite number"))]
pub struct NonFinite;

macro_rules! unit {
	(pub const struct $name:ident($inner:ident);) => {
		unit!(@internal [const]; $name($inner););
	};

	(pub struct $name:ident($inner:ident);) => {
		unit!(@internal []; $name($inner););
	};

	(@internal [$($const:tt)?]; $name:ident($inner:ident);) => {
		paste! {
			mod [<unit_ $name>] {
				use super::NonFinite;

				#[derive(Clone, Copy, PartialEq, PartialOrd)]
				#[allow(non_camel_case_types)]
				pub struct $name($inner);

				impl $name {
					/// This is a helper method for creating this type. Take a look at the [`Unit`]
					/// trait for a more idiomatic way to create this type.
					///
					/// **Note:** This method is only `const` when using a nightly Rust compiler.
					///
					///  [`Unit`]: super::Unit
					pub $($const)? fn try_new(inner: $inner) -> Result<Self, NonFinite> {
						if !inner.is_finite() {
							return Err(NonFinite);
						}
						Ok(Self(inner))
					}

					/// This is a helper method for creating this type. Take a look at the [`Unit`]
					/// trait for a more idiomatic way to create this type.
					///
					/// **Note:** This method is only `const` when using a nightly Rust compiler.
					///
					/// ### Panics
					///
					/// This method panics if the inner value is non-finite.
					///
					///  [`Unit`]: super::Unit
					pub $($const)? fn new(inner: $inner) -> Self {
						match Self::try_new(inner) {
							Ok(unit) => unit,
							Err(NonFinite) => panic!(concat!(
								stringify!($name),
								" only supports finite numbers"
							))
						}
					}

					/// Return the raw value.
					pub const fn raw_value(self) -> $inner {
						self.0
					}
				}
			}
			pub use [<unit_ $name>]::$name;
		}

		impl Default for $name
		where
			$inner: Default
		{
			fn default() -> Self {
				Self::new(Default::default())
			}
		}

		#[cfg(feature = "std")]
		impl $name {
			/// Returns the nearest integer to `self`. Round half-way cases away
			/// from `0.0`.
			#[must_use = "method returns a new number and does not mutate the original value"]
			pub fn round(self) -> Self {
				Self::new(self.raw_value().round())
			}

			/// Returns the absolute value of `self`.
			#[must_use = "method returns a new number and does not mutate the original value"]
			pub fn abs(self) -> Self {
				Self::new(self.raw_value().abs())
			}

			/// Computes the four quadrant arctangent of `self` and `other`
			/// in radians.
			#[must_use = "method returns a new number and does not mutate the original value"]
			pub fn atan2(self, other: Self) -> f32 {
				self.raw_value().atan2(other.raw_value())
			}
		}

		impl Eq for $name {}

		impl Ord for $name {
			fn cmp(&self, other: &Self) -> Ordering {
				// unwrap: Self will never store non-finite values, so all values
				// should be comparable
				self.partial_cmp(other).unwrap()
			}
		}

		impl Hash for $name {
			fn hash<H: Hasher>(&self, state: &mut H) {
				Hash::hash::<H>(&self.raw_value().to_bits(), state);
			}
		}

		impl Neg for $name {
			type Output = Self;
			fn neg(self) -> Self {
				Self::new(-self.raw_value())
			}
		}

		impl Add for $name {
			type Output = Self;
			fn add(self, rhs: Self) -> Self {
				Self::new(self.raw_value() + rhs.raw_value())
			}
		}

		impl AddAssign for $name {
			fn add_assign(&mut self, rhs: Self) {
				*self = *self + rhs;
			}
		}

		impl Sub for $name {
			type Output = Self;
			fn sub(self, rhs: Self) -> Self {
				Self::new(self.raw_value() - rhs.raw_value())
			}
		}


		impl SubAssign for $name {
			fn sub_assign(&mut self, rhs: Self) {
				*self = *self - rhs;
			}
		}

		impl Mul<$inner> for $name {
			type Output = Self;
			fn mul(self, rhs: $inner) -> Self {
				Self::new(self.raw_value() * rhs)
			}
		}

		impl Mul<$name> for $inner {
			type Output = $name;
			fn mul(self, rhs: $name) -> $name {
				$name::new(self * rhs.raw_value())
			}
		}

		impl MulAssign<$inner> for $name {
			fn mul_assign(&mut self, rhs: $inner) {
				*self = *self * rhs;
			}
		}

		impl Div<$inner> for $name {
			type Output = Self;
			fn div(self, rhs: $inner) -> Self {
				if !rhs.is_finite() {
					panic!("Division through non-finite number");
				}
				if rhs == 0.0 {
					panic!("Division through zero");
				}
				Self::new(self.raw_value() / rhs)
			}
		}

		impl Div<$name> for $name {
			type Output = $inner;
			fn div(self, rhs: $name) -> $inner {
				self.raw_value() / rhs.raw_value()
			}
		}

		impl DivAssign<$inner> for $name {
			fn div_assign(&mut self, rhs: $inner) {
				*self = *self / rhs;
			}
		}

		impl Rem for $name {
			type Output = Self;

			fn rem(self, rhs: Self) -> Self {
				self % rhs.raw_value()
			}
		}

		impl Rem<$inner> for $name {
			type Output = Self;

			fn rem(self, rhs: $inner) -> Self {
				Self::new(self.raw_value() % rhs)
			}
		}

		impl FromStr for $name {
			type Err = <$inner as FromStr>::Err;
			fn from_str(s: &str) -> Result<Self, Self::Err> {
				Ok(Self::new(s.parse()?))
			}
		}

		impl Display for $name {
			fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
				Display::fmt(&self.raw_value(), f)
			}
		}

		impl Debug for $name {
			fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
				Debug::fmt(&self.raw_value(), f)?;
				f.write_str(stringify!($name))
			}
		}

		#[cfg(feature = "serde")]
		impl<'de> Deserialize<'de> for $name {
			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
			where
				D: Deserializer<'de>
			{
				$inner::deserialize(deserializer).and_then(|inner| {
					Self::try_new(inner).map_err(|err| D::Error::custom(err))
				})
			}
		}

		#[cfg(feature = "serde")]
		impl Serialize for $name {
			fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
			where
				S: Serializer
			{
				self.raw_value().serialize(serializer)
			}
		}
	};
}

macro_rules! square_unit {
	(pub const struct $name:ident($inner:ident) = $base:ident^2;) => {
		unit!(@internal [const]; $name($inner););
		square_unit!(@internal $name($inner) = $base^2);
	};

	(pub struct $name:ident($inner:ident) = $base:ident^2;) => {
		unit!(@internal []; $name($inner););
		square_unit!(@internal $name($inner) = $base^2);
	};

	(@internal $name:ident($inner:ident) = $base:ident^2) => {
		#[cfg(feature = "std")]
		impl $name {
			pub fn sqrt(self) -> $base {
				$base::new(self.raw_value().sqrt())
			}
		}

		impl Mul<$base> for $base {
			type Output = $name;
			fn mul(self, rhs: $base) -> $name {
				$name::new(self.raw_value() * rhs.raw_value())
			}
		}

		impl Div<$base> for $name {
			type Output = $base;
			fn div(self, rhs: $base) -> $base {
				$base::new(self.raw_value() / rhs.raw_value())
			}
		}
	};
}

#[cfg(not(has_const_float_classify))]
unit! {
	pub struct mm(f32);
}

#[cfg(has_const_float_classify)]
unit! {
	pub const struct mm(f32);
}

#[cfg(not(has_const_float_classify))]
square_unit! {
	pub struct mm2(f32) = mm^2;
}

#[cfg(has_const_float_classify)]
square_unit! {
	pub const struct mm2(f32) = mm^2;
}

macro_rules! unit_trait {
	(pub trait $ident:ident {
		$(fn $name:ident(self) -> $unit:ident $(= self * $convert:literal)? ;)*
	}) => {
		paste! {
			mod [<private_ $ident:lower>] {
				pub trait Sealed {}
				impl Sealed for f32 {}
			}

			pub trait $ident: [<private_ $ident:lower>]::Sealed {
				$(fn $name(self) -> $unit;)*
			}

			impl $ident for f32 {
				$(unit_trait!(@internal fn $name(self) -> $unit $(= self * $convert)?);)*
			}
		}
	};

	(@internal fn $name:ident(self) -> $unit:ident) => {
		fn $name(self) -> $unit {
			$unit::new(self)
		}
	};

	(@internal fn $name:ident(self) -> $unit:ident = self * $convert:literal) => {
		fn $name(self) -> $unit {
			$unit::new(self * $convert)
		}
	};
}

unit_trait! {
	pub trait Unit {
		fn nm(self) -> mm = self * 1e-6;
		fn nm2(self) -> mm2 = self * 1e-12;

		fn µm(self) -> mm = self * 1e-3;
		fn µm2(self) -> mm2 = self * 1e-6;

		fn mm(self) -> mm;
		fn mm2(self) -> mm2;

		fn cm(self) -> mm = self * 1e1;
		fn cm2(self) -> mm2 = self * 1e2;

		fn dm(self) -> mm = self * 1e2;
		fn dm2(self) -> mm2 = self * 1e4;

		fn m(self) -> mm = self * 1e3;
		fn m2(self) -> mm2 = self * 1e6;

		fn km(self) -> mm = self * 1e6;
		fn km2(self) -> mm2 = self * 1e12;

		fn inch(self) -> mm = self * 25.4;
		fn inch2(self) -> mm2 = self * 645.16;
	}
}