Skip to content

Commit 03b19e4

Browse files
committed
Add nonzero helpers
1 parent f35542d commit 03b19e4

3 files changed

Lines changed: 36 additions & 3 deletions

File tree

Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

deranged/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "deranged"
3-
version = "0.5.0"
3+
version = "0.5.1"
44
authors = ["Jacob Pratt <jacob@jhpratt.dev>"]
55
edition = "2021"
66
rust-version = "1.81.0"

deranged/src/lib.rs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ use core::borrow::Borrow;
1616
use core::cmp::Ordering;
1717
use core::error::Error;
1818
use core::fmt;
19-
use core::num::IntErrorKind;
2019
use core::hint::assert_unchecked;
20+
use core::num::{IntErrorKind, NonZero};
2121
use core::str::FromStr;
2222

2323
/// A macro to define a ranged integer with an automatically computed inner type.
@@ -255,6 +255,23 @@ macro_rules! impl_ranged {
255255
}
256256
}
257257

258+
if_unsigned! { $is_signed
259+
impl $type<1, { $internal::MAX }> {
260+
/// Creates a ranged integer from a non-zero value.
261+
#[inline(always)]
262+
pub const fn from_nonzero(value: NonZero<$internal>) -> Self {
263+
// Safety: The value is non-zero, so it is in range.
264+
unsafe { Self::new_unchecked(value.get()) }
265+
}
266+
267+
/// Creates a non-zero value from a ranged integer.
268+
#[inline(always)]
269+
pub const fn to_nonzero(self) -> NonZero<$internal> {
270+
// Safety: The value is in range, so it is non-zero.
271+
unsafe { NonZero::new_unchecked(self.get()) }
272+
}
273+
}}
274+
258275
impl<const MIN: $internal, const MAX: $internal> $type<MIN, MAX> {
259276
/// The smallest value that can be represented by this type.
260277
// Safety: `MIN` is in range by definition.
@@ -1282,6 +1299,22 @@ macro_rules! impl_ranged {
12821299
}
12831300
}
12841301

1302+
if_unsigned! { $is_signed
1303+
impl From<NonZero<$internal>> for $type<1, { $internal::MAX }> {
1304+
#[inline(always)]
1305+
fn from(value: NonZero<$internal>) -> Self {
1306+
Self::from_nonzero(value)
1307+
}
1308+
}
1309+
1310+
impl From<$type<1, { $internal::MAX }>> for NonZero<$internal> {
1311+
#[inline(always)]
1312+
fn from(value: $type<1, { $internal::MAX }>) -> Self {
1313+
value.to_nonzero()
1314+
}
1315+
}
1316+
}
1317+
12851318
impl<const MIN: $internal, const MAX: $internal> From<$type<MIN, MAX>> for $internal {
12861319
#[inline(always)]
12871320
fn from(value: $type<MIN, MAX>) -> Self {

0 commit comments

Comments
 (0)