]> git.nega.tv - josh/narcissus/commitdiff
Add `is_aligned_to` and `is_aligned` functions
authorJoshua Simmons <josh@nega.tv>
Sat, 29 Oct 2022 14:09:14 +0000 (16:09 +0200)
committerJoshua Simmons <josh@nega.tv>
Sat, 29 Oct 2022 14:09:14 +0000 (16:09 +0200)
narcissus-core/src/lib.rs

index 7a4b304d9823d18b5a016d8b29c058082af92b03..a503bc565c6439fff337dda6d9e71036a1dfbd36 100644 (file)
@@ -271,6 +271,20 @@ pub fn align_offset(x: usize, align: usize) -> usize {
     (x + align - 1) & !(align - 1)
 }
 
+#[must_use]
+pub fn is_aligned_to<T>(ptr: *const T, align: usize) -> bool {
+    if align == 0 || !align.is_power_of_two() {
+        panic!("is_aligned_to: align is not a power-of-two");
+    }
+
+    (ptr as usize) & (align - 1) == 0
+}
+
+#[must_use]
+pub fn is_aligned<T>(ptr: *const T) -> bool {
+    is_aligned_to(ptr, std::mem::align_of::<T>())
+}
+
 pub fn page_size() -> usize {
     4096
 }