Skip to main content

objdiff_core/
util.rs

1use alloc::{format, vec::Vec};
2use core::fmt;
3
4use anyhow::{Result, ensure};
5use num_traits::PrimInt;
6use object::{Endian, Object};
7
8// https://stackoverflow.com/questions/44711012/how-do-i-format-a-signed-integer-to-a-sign-aware-hexadecimal-representation
9pub struct ReallySigned<N: PrimInt>(pub N);
10
11impl<N: PrimInt> fmt::LowerHex for ReallySigned<N> {
12    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
13        let num = self.0.to_i64().unwrap();
14        let prefix = if f.alternate() { "0x" } else { "" };
15        let bare_hex = format!("{:x}", num.abs());
16        f.pad_integral(num >= 0, prefix, &bare_hex)
17    }
18}
19
20impl<N: PrimInt> fmt::UpperHex for ReallySigned<N> {
21    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
22        let num = self.0.to_i64().unwrap();
23        let prefix = if f.alternate() { "0x" } else { "" };
24        let bare_hex = format!("{:X}", num.abs());
25        f.pad_integral(num >= 0, prefix, &bare_hex)
26    }
27}
28
29pub fn read_u32(obj_file: &object::File, reader: &mut &[u8]) -> Result<u32> {
30    ensure!(reader.len() >= 4, "Not enough bytes to read u32");
31    let value = reader[..4].try_into()?;
32    *reader = &reader[4..];
33    Ok(obj_file.endianness().read_u32(value))
34}
35
36pub fn read_u16(obj_file: &object::File, reader: &mut &[u8]) -> Result<u16> {
37    ensure!(reader.len() >= 2, "Not enough bytes to read u16");
38    let value = reader[..2].try_into()?;
39    *reader = &reader[2..];
40    Ok(obj_file.endianness().read_u16(value))
41}
42
43pub fn align_size_to_4(size: usize) -> usize { (size + 3) & !3 }
44
45#[cfg(feature = "std")]
46pub fn align_data_to_4<W: std::io::Write + ?Sized>(
47    writer: &mut W,
48    len: usize,
49) -> std::io::Result<()> {
50    const ALIGN_BYTES: &[u8] = &[0; 4];
51    if !len.is_multiple_of(4) {
52        writer.write_all(&ALIGN_BYTES[..4 - len % 4])?;
53    }
54    Ok(())
55}
56
57pub fn align_u64_to(len: u64, align: u64) -> u64 { len + ((align - (len % align)) % align) }
58
59pub fn align_data_slice_to(data: &mut Vec<u8>, align: u64) {
60    data.resize(align_u64_to(data.len() as u64, align) as usize, 0);
61}
62
63// Float where we specifically care about comparing the raw bits rather than
64// caring about IEEE semantics.
65#[derive(Copy, Clone, Debug)]
66pub struct RawFloat(pub f32);
67impl PartialEq for RawFloat {
68    fn eq(&self, other: &Self) -> bool { self.0.to_bits() == other.0.to_bits() }
69}
70impl Eq for RawFloat {}
71impl Ord for RawFloat {
72    fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.0.to_bits().cmp(&other.0.to_bits()) }
73}
74impl PartialOrd for RawFloat {
75    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { Some(self.cmp(other)) }
76}
77
78// Double where we specifically care about comparing the raw bits rather than
79// caring about IEEE semantics.
80#[derive(Copy, Clone, Debug)]
81pub struct RawDouble(pub f64);
82impl PartialEq for RawDouble {
83    fn eq(&self, other: &Self) -> bool { self.0.to_bits() == other.0.to_bits() }
84}
85impl Eq for RawDouble {}
86impl Ord for RawDouble {
87    fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.0.to_bits().cmp(&other.0.to_bits()) }
88}
89impl PartialOrd for RawDouble {
90    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { Some(self.cmp(other)) }
91}