Skip to content

Commit

Permalink
add conversions to/from u64 (#169)
Browse files Browse the repository at this point in the history
Useful as a sort key, or for saving in a binary format (in my case i
wanted a sort key :P )

decided to implement as `as_u64` and `from_u64` because i figured it
would be a kinda weird thing for `.into()` to do.

documentation and tests included.
  • Loading branch information
SIGSTACKFAULT committed Apr 19, 2024
1 parent cca90b7 commit b858433
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## [Unreleased]

* Added `Hex::as_u64` and `Hex::from_u64`

## 0.17.0

* Added `HexagonalMap` storage structure for dense, hexagon shaped maps (#163)
Expand Down
46 changes: 46 additions & 0 deletions src/hex/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,49 @@ impl From<IVec2> for Hex {
Self::new(v.x, v.y)
}
}

impl Hex {
/// Unpack from a [`u64`].
/// [x][`Hex::x`] is read from the most signifigant 32 bits; [y][`Hex::y`]
/// is read from the least signifigant 32 bits. Intended to be used with
/// [`Hex::as_u64`].
///
/// # Example
///
/// ```
/// # use hexx::*;
/// let x: u64 = 0x000000AA_FFFFFF45;
/// assert_eq!(Hex::from_u64(x), Hex::new(0xAA, -0xBB));
/// ```
#[inline]
#[must_use]
#[doc(alias = "unpack")]
pub const fn from_u64(value: u64) -> Self {
let x = (value >> 32) as i32;
let y = (value & 0xFFFF_FFFF) as i32;
Self::new(x, y)
}

/// Pack into a [`u64`].
/// [x][`Hex::x`] is placed in the most signifigant 32 bits; [y][`Hex::y`]
/// is placed in the least signifigant 32 bits. Can be used as a sort
/// key, or for saving in a binary format. Intended to be used with
/// [`Hex::from_u64`].
///
/// # Example
///
/// ```
/// # use hexx::*;
/// let x = Hex::new(0xAA, -0xBB).as_u64();
/// assert_eq!(x, 0x000000AA_FFFFFF45u64);
/// ```
#[inline]
#[must_use]
#[allow(clippy::cast_sign_loss)]
#[doc(alias = "pack")]
pub const fn as_u64(self) -> u64 {
let high = (self.x as u32 as u64) << 32;
let low = self.y as u32 as u64;
high | low
}
}
13 changes: 13 additions & 0 deletions src/hex/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,3 +544,16 @@ fn axis_pairs() {
assert_eq!(b.const_neg(), nb);
}
}

#[test]
fn u64_conversion() {
let coords = [i32::MIN, -100, -1, 0, 1, 100, i32::MAX];
for x in coords {
for y in coords {
let first = Hex::new(x, y);
let second = first.as_u64();
let third = Hex::from_u64(second);
assert_eq!(first, third);
}
}
}

0 comments on commit b858433

Please sign in to comment.