Skip to main content

datafusion_common/utils/
hex.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Hex encoding of bytes and integers.
6//!
7//! [`encode_bytes`] and [`encode_bytes_into`] encode a byte slice into an
8//! owned `String` or an appended `Vec<u8>`, respectively; [`encode_bytes_to_slice`]
9//! writes into a caller-provided, pre-sized buffer. [`encode_u64`] encodes an
10//! integer, trimming leading zeros. All four take a [`HexCase`] to choose
11//! between lowercase and uppercase digits.
12
13use arrow::datatypes::ArrowNativeType;
14
15use crate::Result;
16use crate::error::_internal_err;
17
18/// Case of the emitted hex digits.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum HexCase {
21    /// Digits `0123456789abcdef`.
22    Lower,
23    /// Digits `0123456789ABCDEF`.
24    Upper,
25}
26
27const LOWER_DIGITS: &[u8; 16] = b"0123456789abcdef";
28const UPPER_DIGITS: &[u8; 16] = b"0123456789ABCDEF";
29
30/// Maps a full byte to its two hex digits, so encoding advances a whole byte
31/// per iteration instead of a nibble.
32const LOOKUP_LOWER: [[u8; 2]; 256] = build_lookup(LOWER_DIGITS);
33const LOOKUP_UPPER: [[u8; 2]; 256] = build_lookup(UPPER_DIGITS);
34
35const fn build_lookup(digits: &[u8; 16]) -> [[u8; 2]; 256] {
36    let mut table = [[0u8; 2]; 256];
37    let mut i = 0;
38    while i < 256 {
39        table[i][0] = digits[i >> 4];
40        table[i][1] = digits[i & 0xF];
41        i += 1;
42    }
43    table
44}
45
46impl HexCase {
47    #[inline]
48    const fn lookup(self) -> &'static [[u8; 2]; 256] {
49        match self {
50            HexCase::Lower => &LOOKUP_LOWER,
51            HexCase::Upper => &LOOKUP_UPPER,
52        }
53    }
54
55    #[inline]
56    const fn digits(self) -> &'static [u8; 16] {
57        match self {
58            HexCase::Lower => LOWER_DIGITS,
59            HexCase::Upper => UPPER_DIGITS,
60        }
61    }
62}
63
64/// Trait for converting integer types to hexadecimal in a buffer
65pub trait ToHex: ArrowNativeType {
66    /// Writes the hex representation into `buf` and returns the written
67    /// subslice. Digits are right-aligned with leading zeros trimmed.
68    fn write_hex(self, case: HexCase, buf: &mut [u8; 16]) -> &[u8];
69}
70
71macro_rules! impl_to_hex_signed {
72    ($ty:ty) => {
73        impl ToHex for $ty {
74            #[inline(always)]
75            fn write_hex(self, case: HexCase, buf: &mut [u8; 16]) -> &[u8] {
76                encode_u64(self as i64 as u64, case, buf)
77            }
78        }
79    };
80}
81
82macro_rules! impl_to_hex_unsigned {
83    ($ty:ty) => {
84        impl ToHex for $ty {
85            #[inline(always)]
86            fn write_hex(self, case: HexCase, buf: &mut [u8; 16]) -> &[u8] {
87                encode_u64(self as u64, case, buf)
88            }
89        }
90    };
91}
92
93impl_to_hex_signed!(i8);
94impl_to_hex_signed!(i16);
95impl_to_hex_signed!(i32);
96impl_to_hex_signed!(i64);
97impl_to_hex_unsigned!(u8);
98impl_to_hex_unsigned!(u16);
99impl_to_hex_unsigned!(u32);
100impl_to_hex_unsigned!(u64);
101
102/// Appends the hex encoding of `bytes` to `out`.
103///
104/// Allocates only through `out`'s own growth. Callers that must bound or guard
105/// that growth should reserve capacity in `out` before calling.
106#[inline(always)]
107pub fn encode_bytes_into(bytes: &[u8], case: HexCase, out: &mut Vec<u8>) {
108    let lookup = case.lookup();
109    for &byte in bytes {
110        out.extend_from_slice(&lookup[byte as usize]);
111    }
112}
113
114/// Writes the hex encoding of `bytes` into `out`.
115///
116/// This is for callers that already own a pre-sized buffer (for example a
117/// slice of a larger, pre-allocated output array) and want to write directly
118/// into it rather than appending to a `Vec`.
119///
120/// Returns an internal error if `out` is not exactly `2 * bytes.len()` bytes
121/// long, without filling any of the `out` buffer.
122///
123/// # Example
124///
125/// ```
126/// use datafusion_common::utils::hex::{HexCase, encode_bytes_to_slice};
127///
128/// let mut out = [0u8; 8];
129/// encode_bytes_to_slice(&[0xde, 0xad, 0xbe, 0xef], HexCase::Lower, &mut out)?;
130/// assert_eq!(&out, b"deadbeef");
131/// # Ok::<(), datafusion_common::DataFusionError>(())
132/// ```
133#[inline(always)]
134pub fn encode_bytes_to_slice(bytes: &[u8], case: HexCase, out: &mut [u8]) -> Result<()> {
135    let expected = bytes.len() * 2;
136    if out.len() != expected {
137        return _internal_err!(
138            "hex output buffer is {} bytes, expected {expected}",
139            out.len()
140        );
141    }
142    let lookup = case.lookup();
143    for (&b, chunk) in bytes.iter().zip(out.as_chunks_mut::<2>().0) {
144        *chunk = lookup[b as usize];
145    }
146    Ok(())
147}
148
149/// Returns the hex encoding of `bytes` as an owned `String`.
150///
151/// Prefer [`encode_bytes_into`] when you already have a reusable output buffer.
152///
153/// # Example
154///
155/// ```
156/// use datafusion_common::utils::hex::{HexCase, encode_bytes};
157///
158/// assert_eq!(encode_bytes(&[0xde, 0xad, 0xbe, 0xef], HexCase::Lower), "deadbeef");
159/// assert_eq!(encode_bytes(&[0xde, 0xad, 0xbe, 0xef], HexCase::Upper), "DEADBEEF");
160/// ```
161#[inline]
162pub fn encode_bytes(bytes: &[u8], case: HexCase) -> String {
163    let mut out = Vec::with_capacity(bytes.len() * 2);
164    encode_bytes_into(bytes, case, &mut out);
165    // SAFETY: `out` holds only ASCII hex digits, which are valid UTF-8.
166    unsafe { String::from_utf8_unchecked(out) }
167}
168
169/// Writes `v` as hex into `buf` and returns the written subslice.
170///
171/// Digits are written right-aligned with leading zeros trimmed, so the result
172/// borrows the tail of `buf`. Zero encodes as `"0"`.
173///
174/// Signed values should be cast with `as u64`, which yields the two's
175/// complement representation that both `to_hex` and Spark's `hex` produce for
176/// negative input.
177///
178/// # Example
179///
180/// The caller owns the buffer and can reuse it across calls; each call
181/// returns a fresh subslice of it, borrowed for as long as `buf` is:
182///
183/// ```
184/// use datafusion_common::utils::hex::{HexCase, encode_u64};
185///
186/// let mut buf = [0u8; 16];
187/// assert_eq!(encode_u64(0xAB, HexCase::Lower, &mut buf), b"ab");
188/// assert_eq!(encode_u64(0, HexCase::Lower, &mut buf), b"0");
189/// ```
190#[inline(always)]
191pub fn encode_u64(v: u64, case: HexCase, buf: &mut [u8; 16]) -> &[u8] {
192    let start = write_digits(v, case, buf);
193    &buf[start..]
194}
195
196/// Writes the digits of `v` right-aligned in `buf`, returning the index of the
197/// first digit.
198///
199/// Split out from [`encode_u64`] so the mutable borrow of `buf` ends before the
200/// returned slice reborrows it.
201#[inline(always)]
202fn write_digits(v: u64, case: HexCase, buf: &mut [u8; 16]) -> usize {
203    if v == 0 {
204        buf[15] = b'0';
205        return 15;
206    }
207
208    // Consume two nibbles (one full byte) per iteration.
209    let lookup = case.lookup();
210    let mut pos = 16;
211    let mut rest = v;
212    while rest >= 0x10 {
213        pos -= 2;
214        let pair = lookup[(rest & 0xFF) as usize];
215        buf[pos] = pair[0];
216        buf[pos + 1] = pair[1];
217        rest >>= 8;
218    }
219    if rest > 0 {
220        // A single high nibble (0x1..=0xF) remains.
221        pos -= 1;
222        buf[pos] = case.digits()[rest as usize];
223    }
224
225    pos
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use std::fmt::Write as _;
232
233    fn hex_u64(v: u64, case: HexCase) -> String {
234        let mut buf = [0u8; 16];
235        String::from_utf8(encode_u64(v, case, &mut buf).to_vec()).unwrap()
236    }
237
238    #[test]
239    fn encode_u64_zero() {
240        assert_eq!(hex_u64(0, HexCase::Lower), "0");
241        assert_eq!(hex_u64(0, HexCase::Upper), "0");
242    }
243
244    #[test]
245    fn encode_u64_single_nibble() {
246        for v in 1..=0xFu64 {
247            assert_eq!(hex_u64(v, HexCase::Lower), format!("{v:x}"));
248            assert_eq!(hex_u64(v, HexCase::Upper), format!("{v:X}"));
249        }
250    }
251
252    #[test]
253    fn encode_u64_digit_count_boundaries() {
254        // Straddle each odd/even digit-count boundary: the two-nibbles-per
255        // iteration loop plus the trailing single-nibble fixup.
256        for v in [
257            0x10u64,
258            0xFF,
259            0x100,
260            0xFFF,
261            0x1000,
262            0xFFFFF,
263            0xFFFF_FFFF,
264            0x1_0000_0000,
265        ] {
266            assert_eq!(hex_u64(v, HexCase::Lower), format!("{v:x}"));
267            assert_eq!(hex_u64(v, HexCase::Upper), format!("{v:X}"));
268        }
269    }
270
271    #[test]
272    fn encode_u64_max() {
273        assert_eq!(hex_u64(u64::MAX, HexCase::Lower), "ffffffffffffffff");
274        assert_eq!(hex_u64(u64::MAX, HexCase::Upper), "FFFFFFFFFFFFFFFF");
275    }
276
277    #[test]
278    fn encode_u64_signed_is_twos_complement() {
279        // Callers cast signed values with `as u64`; this is the behaviour both
280        // `to_hex` and Spark `hex` rely on for negative input.
281        assert_eq!(hex_u64(-1i64 as u64, HexCase::Lower), "ffffffffffffffff");
282        assert_eq!(hex_u64(i64::MIN as u64, HexCase::Upper), "8000000000000000");
283    }
284
285    #[test]
286    fn encode_bytes_empty() {
287        assert_eq!(encode_bytes(&[], HexCase::Lower), "");
288        assert_eq!(encode_bytes(&[], HexCase::Upper), "");
289    }
290
291    #[test]
292    fn encode_bytes_examples() {
293        assert_eq!(encode_bytes(&[0x00], HexCase::Lower), "00");
294        assert_eq!(encode_bytes(&[0xAB], HexCase::Lower), "ab");
295        assert_eq!(encode_bytes(&[0xAB], HexCase::Upper), "AB");
296        assert_eq!(
297            encode_bytes(&[0xde, 0xad, 0xbe, 0xef], HexCase::Lower),
298            "deadbeef"
299        );
300        assert_eq!(
301            encode_bytes(&[0xde, 0xad, 0xbe, 0xef], HexCase::Upper),
302            "DEADBEEF"
303        );
304    }
305
306    #[test]
307    fn encode_bytes_covers_every_byte_value() {
308        let bytes: Vec<u8> = (0..=255u8).collect();
309
310        let expected: String = bytes.iter().fold(String::new(), |mut acc, b| {
311            write!(acc, "{b:02x}").ok();
312            acc
313        });
314        assert_eq!(encode_bytes(&bytes, HexCase::Lower), expected);
315
316        let expected: String = bytes.iter().fold(String::new(), |mut acc, b| {
317            write!(acc, "{b:02X}").ok();
318            acc
319        });
320        assert_eq!(encode_bytes(&bytes, HexCase::Upper), expected);
321    }
322
323    #[test]
324    fn encode_bytes_into_appends_without_clearing() {
325        let mut out = b"prefix-".to_vec();
326        encode_bytes_into(&[0x01, 0x02], HexCase::Lower, &mut out);
327        assert_eq!(out, b"prefix-0102");
328    }
329
330    #[test]
331    fn encode_u64_reused_buffer_leaks_no_stale_digits() {
332        let mut buf = [0u8; 16];
333        assert_eq!(
334            encode_u64(u64::MAX, HexCase::Lower, &mut buf),
335            b"ffffffffffffffff"
336        );
337        assert_eq!(encode_u64(0, HexCase::Lower, &mut buf), b"0");
338        assert_eq!(encode_u64(0xAB, HexCase::Lower, &mut buf), b"ab");
339    }
340
341    #[test]
342    fn encode_bytes_to_slice_empty() -> Result<()> {
343        let mut out: [u8; 0] = [];
344        encode_bytes_to_slice(&[], HexCase::Lower, &mut out)?;
345        assert_eq!(out, [] as [u8; 0]);
346        Ok(())
347    }
348
349    #[test]
350    fn encode_bytes_to_slice_examples() -> Result<()> {
351        let mut out = [0u8; 8];
352        encode_bytes_to_slice(&[0xde, 0xad, 0xbe, 0xef], HexCase::Lower, &mut out)?;
353        assert_eq!(&out, b"deadbeef");
354
355        let mut out = [0u8; 8];
356        encode_bytes_to_slice(&[0xde, 0xad, 0xbe, 0xef], HexCase::Upper, &mut out)?;
357        assert_eq!(&out, b"DEADBEEF");
358        Ok(())
359    }
360
361    #[test]
362    fn encode_bytes_to_slice_agrees_with_encode_bytes() -> Result<()> {
363        let bytes: Vec<u8> = (0..=255u8).collect();
364        for case in [HexCase::Lower, HexCase::Upper] {
365            let mut out = vec![0u8; bytes.len() * 2];
366            encode_bytes_to_slice(&bytes, case, &mut out)?;
367            assert_eq!(String::from_utf8(out).unwrap(), encode_bytes(&bytes, case));
368        }
369        Ok(())
370    }
371
372    #[test]
373    fn encode_bytes_to_slice_rejects_wrong_length() {
374        // Too short: the old `debug_assert` let release builds silently drop
375        // the remaining input.
376        let mut short = [0u8; 6];
377        let err =
378            encode_bytes_to_slice(&[0xde, 0xad, 0xbe, 0xef], HexCase::Lower, &mut short)
379                .unwrap_err();
380        assert!(
381            err.message()
382                .contains("hex output buffer is 6 bytes, expected 8"),
383            "unexpected message: {err}"
384        );
385
386        // Too long: would have left stale bytes at the tail.
387        let mut long = [0u8; 10];
388        assert!(
389            encode_bytes_to_slice(&[0xde, 0xad, 0xbe, 0xef], HexCase::Lower, &mut long)
390                .is_err()
391        );
392    }
393}