Skip to content

Commit

Permalink
Introduce align_up() helper function
Browse files Browse the repository at this point in the history
Introduce a helper function that can be used for aligning values to the
next power of two.

Signed-off-by: Daniel Müller <[email protected]>
  • Loading branch information
d-e-s-o committed Dec 27, 2024
1 parent 7d734eb commit 92b1fe8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/dwarf/debug_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use std::path::PathBuf;

use crate::elf::ElfParser;
use crate::error::IntoError as _;
use crate::util::align_up;
use crate::util::bytes_to_os_str;
use crate::util::ReadRaw as _;
use crate::Result;
Expand Down Expand Up @@ -161,7 +162,7 @@ fn parse_debug_link_section_data(mut data: &[u8]) -> Result<Option<(&OsStr, u32)
// The offset is aligned to the next four byte boundary relative to
// the start of the section.
let align = 4;
let crc_offset = (cur_offset + (align - 1)) & !(align - 1);
let crc_offset = align_up(cur_offset, align);
let () = data
.advance(crc_offset - cur_offset)
.ok_or_invalid_data(|| {
Expand Down
33 changes: 33 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,17 @@ where
}


/// Align a value to the next power of two.
pub(crate) fn align_up(value: usize, align_to: usize) -> usize {
debug_assert_eq!(
align_to.next_power_of_two(),
align_to,
"alignment ({align_to}) is no power of two"
);
(value + (align_to - 1)) & !(align_to - 1)
}


/// Split a byte slice at the first byte for which `check` returns
/// `true`.
///
Expand Down Expand Up @@ -718,6 +729,28 @@ mod tests {
);
}

/// Check that we can properly align values to a power of two.
#[tag(miri)]
#[test]
fn upwards_alignment() {
assert_eq!(align_up(0, 4), 0);
assert_eq!(align_up(1, 4), 4);
assert_eq!(align_up(2, 4), 4);
assert_eq!(align_up(3, 4), 4);
assert_eq!(align_up(4, 4), 4);
assert_eq!(align_up(5, 4), 8);
}

/// Make sure that `align_up` panics when attempting to align to
/// something other than a power of two.
#[cfg(debug_assertions)]
#[tag(miri)]
#[test]
#[should_panic = "alignment (3) is no power of two"]
fn upwards_alignment_no_power_of_two() {
assert_eq!(align_up(0, 3), 0);
}

/// Check that we can reorder elements in an array as expected.
#[tag(miri)]
#[test]
Expand Down

0 comments on commit 92b1fe8

Please sign in to comment.