1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
#![allow(clippy::tabs_in_doc_comments)]
#![deny(missing_docs)]
#![no_std]
//! A collection of array/bytes/hex utilities.
//!
//! Completely optimized for blockchain development.
//! Especially the Substrate.
extern crate alloc;
#[cfg(test)] mod test;
// core
use core::{cmp::Ordering, convert::TryInto, result::Result as CoreResult, str};
// alloc
use alloc::{format, string::String, vec::Vec};
// crates.io
#[cfg(feature = "serde")] use serde::{de::Error as DeError, Deserialize, Deserializer};
// use thiserror::Error as ThisError;
/// The main result of array-bytes.
pub type Result<T> = CoreResult<T, Error>;
/// Try to convert the given hex to a specific type.
///
/// # Examples
/// ```
/// use array_bytes::TryFromHex;
///
/// assert_eq!(u128::try_from_hex("0x1a2b3c4d5e6f"), Ok(28772997619311));
/// ```
pub trait TryFromHex
where
Self: Sized,
{
/// Try to convert [`Self`] from hex.
fn try_from_hex<H>(hex: H) -> Result<Self>
where
H: AsRef<[u8]>;
}
macro_rules! impl_num_try_from_hex {
($($t:ty,)+) => {
$(impl TryFromHex for $t {
fn try_from_hex<H>(hex: H) -> Result<Self>
where
H: AsRef<[u8]>,
{
let hex = strip_0x(hex.as_ref());
let hex = str::from_utf8(hex).map_err(Error::Utf8Error)?;
Self::from_str_radix(hex, 16).map_err(Error::ParseIntError)
}
})+
};
}
impl_num_try_from_hex! {
isize,
i8,
i16,
i32,
i64,
i128,
usize,
u8,
u16,
u32,
u64,
u128,
}
macro_rules! impl_array_try_from_hex {
($($t:ty,)+) => {
$(impl TryFromHex for $t {
fn try_from_hex<H>(hex: H) -> Result<Self>
where
H: AsRef<[u8]>,
{
hex2array(hex)
}
})+
};
}
impl_array_try_from_hex! {
[u8; 1],
[u8; 2],
[u8; 3],
[u8; 4],
[u8; 5],
[u8; 6],
[u8; 7],
[u8; 8],
[u8; 9],
[u8; 10],
[u8; 11],
[u8; 12],
[u8; 13],
[u8; 14],
[u8; 15],
[u8; 16],
[u8; 17],
[u8; 18],
[u8; 19],
[u8; 20],
[u8; 21],
[u8; 22],
[u8; 23],
[u8; 24],
[u8; 25],
[u8; 26],
[u8; 27],
[u8; 28],
[u8; 29],
[u8; 30],
[u8; 31],
[u8; 32],
[u8; 33],
[u8; 34],
[u8; 35],
[u8; 36],
[u8; 37],
[u8; 38],
[u8; 39],
[u8; 40],
[u8; 41],
[u8; 42],
[u8; 43],
[u8; 44],
[u8; 45],
[u8; 46],
[u8; 47],
[u8; 48],
[u8; 49],
[u8; 50],
[u8; 51],
[u8; 52],
[u8; 53],
[u8; 54],
[u8; 55],
[u8; 56],
[u8; 57],
[u8; 58],
[u8; 59],
[u8; 60],
[u8; 61],
[u8; 62],
[u8; 63],
[u8; 64],
[u8; 128],
[u8; 256],
[u8; 512],
}
impl TryFromHex for Vec<u8> {
fn try_from_hex<H>(hex: H) -> Result<Self>
where
H: AsRef<[u8]>,
{
hex2bytes(hex)
}
}
/// Convert the given type to hex.
///
/// # Examples
/// ```
/// use array_bytes::Hex;
///
/// assert_eq!(28772997619311_u128.hex("0x"), "0x1a2b3c4d5e6f");
/// ```
pub trait Hex {
/// Convert [`Self`] to hex with the given prefix.
fn hex(self, prefix: &str) -> String;
}
macro_rules! impl_num_hex {
($($t:ty,)+) => {
$(
impl Hex for $t {
fn hex(self, prefix: &str) -> String {
format!("{prefix}{self:x}")
}
}
impl Hex for &$t {
fn hex(self, prefix: &str) -> String {
format!("{prefix}{self:x}")
}
}
)+
};
}
impl_num_hex! {
isize,
i8,
i16,
i32,
i64,
i128,
usize,
u8,
u16,
u32,
u64,
u128,
}
macro_rules! impl_array_hex {
($($t:ty,)+) => {
$(
impl Hex for $t {
fn hex(self, prefix: &str) -> String {
bytes2hex(prefix, self)
}
}
impl Hex for &$t {
fn hex(self, prefix: &str) -> String {
bytes2hex(prefix, self)
}
}
)+
};
}
impl_array_hex! {
Vec<u8>,
[u8; 1],
[u8; 2],
[u8; 3],
[u8; 4],
[u8; 5],
[u8; 6],
[u8; 7],
[u8; 8],
[u8; 9],
[u8; 10],
[u8; 11],
[u8; 12],
[u8; 13],
[u8; 14],
[u8; 15],
[u8; 16],
[u8; 17],
[u8; 18],
[u8; 19],
[u8; 20],
[u8; 21],
[u8; 22],
[u8; 23],
[u8; 24],
[u8; 25],
[u8; 26],
[u8; 27],
[u8; 28],
[u8; 29],
[u8; 30],
[u8; 31],
[u8; 32],
[u8; 33],
[u8; 34],
[u8; 35],
[u8; 36],
[u8; 37],
[u8; 38],
[u8; 39],
[u8; 40],
[u8; 41],
[u8; 42],
[u8; 43],
[u8; 44],
[u8; 45],
[u8; 46],
[u8; 47],
[u8; 48],
[u8; 49],
[u8; 50],
[u8; 51],
[u8; 52],
[u8; 53],
[u8; 54],
[u8; 55],
[u8; 56],
[u8; 57],
[u8; 58],
[u8; 59],
[u8; 60],
[u8; 61],
[u8; 62],
[u8; 63],
[u8; 64],
[u8; 128],
[u8; 256],
[u8; 512],
}
impl Hex for &[u8] {
fn hex(self, prefix: &str) -> String {
bytes2hex(prefix, self)
}
}
/// The main error of array-bytes.
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
/// The length must not be odd.
InvalidLength,
/// Found the invalid character at `index`.
InvalidCharacter {
/// The invalid character.
character: char,
/// The invalid character's index.
index: usize,
},
/// The data can not fit the array/slice length well.
MismatchedLength {
/// Expected length.
expect: usize,
},
/// Failed to parse the hex number from hex string.
Utf8Error(core::str::Utf8Error),
/// Failed to parse the hex number from hex string.
ParseIntError(core::num::ParseIntError),
}
/// `&[T]` to `[T; N]`.
///
/// # Examples
/// ```
/// assert_eq!(array_bytes::slice2array::<_, 8>(&[0; 8]), Ok([0; 8]));
/// ```
pub fn slice2array<T, const N: usize>(slice: &[T]) -> Result<[T; N]>
where
T: Copy,
{
slice.try_into().map_err(|_| Error::MismatchedLength { expect: N })
}
/// Just like [`slice2array`] but without the checking.
///
/// # Examples
/// ```
/// assert_eq!(array_bytes::slice2array_unchecked::<_, 8>(&[0; 8]), [0; 8]);
/// ```
pub fn slice2array_unchecked<T, const N: usize>(slice: &[T]) -> [T; N]
where
T: Copy,
{
slice2array(slice).unwrap()
}
/// `&[T]` to `&[T; N]`.
///
/// # Examples
/// ```
/// assert_eq!(array_bytes::slice2array::<_, 8>(&[0; 8]), Ok(&[0; 8]));
/// ```
pub fn slice2array_ref<T, const N: usize>(slice: &[T]) -> Result<&[T; N]>
where
T: Copy,
{
slice.try_into().map_err(|_| Error::MismatchedLength { expect: N })
}
/// Just like [`slice2array_ref`] but without the checking.
///
/// # Examples
/// ```
/// assert_eq!(array_bytes::slice2array_unchecked::<_, 8>(&[0; 8]), &[0; 8]);
/// ```
pub fn slice2array_ref_unchecked<T, const N: usize>(slice: &[T]) -> &[T; N]
where
T: Copy,
{
slice2array_ref(slice).unwrap()
}
/// Prefixes the given element to the given array/slice/vector to make it a fixed-size array of
/// length `N`.
///
/// If the length of the array/slice/vector is already equal to `N`, it returns the
/// array/slice/vector as a fixed-size array.
/// If the length of the array/slice/vector is greater than `N`, it returns the first `N` elements
/// of the array/slice/vector as a fixed-size array.
/// If the length of the array/slice/vector is less than `N`, it creates a new fixed-size array of
/// length `N` and copies the array/slice/vector into it, padding the remaining elements with the
/// given element.
///
/// # Examples
/// ```
/// assert_eq!(array_bytes::prefix_with::<_, _, 4>([1, 2, 3, 4], 0), [1, 2, 3, 4]);
/// assert_eq!(array_bytes::prefix_with::<_, _, 4>([1, 2, 3, 4, 5, 6], 0), [1, 2, 3, 4]);
/// assert_eq!(array_bytes::prefix_with::<_, _, 5>([1, 2, 3], 0), [0, 0, 1, 2, 3]);
/// ```
pub fn prefix_with<A, T, const N: usize>(any: A, element: T) -> [T; N]
where
A: AsRef<[T]>,
T: Copy,
{
let a = any.as_ref();
match a.len().cmp(&N) {
Ordering::Equal => slice2array_unchecked(a),
Ordering::Greater => slice2array_unchecked(&a[..N]),
Ordering::Less => {
let mut padded = [element; N];
padded[N - a.len()..].copy_from_slice(a);
padded
},
}
}
/// Suffixes the given element to the given array/slice/vector to make it a fixed-size array of
/// length `N`.
///
/// If the length of the array/slice/vector is already equal to `N`, it returns the
/// array/slice/vector as a fixed-size array.
/// If the length of the array/slice/vector is greater than `N`, it returns the first `N` elements
/// of the array/slice/vector as a fixed-size array.
/// If the length of the array/slice/vector is less than `N`, it creates a new fixed-size array of
/// length `N` and copies the array/slice/vector into it, padding the remaining elements with the
/// given element.
///
/// # Examples
/// ```
/// assert_eq!(array_bytes::suffix_with::<_, _, 4>([1, 2, 3, 4], 0), [1, 2, 3, 4]);
/// assert_eq!(array_bytes::suffix_with::<_, _, 4>([1, 2, 3, 4, 5, 6], 0), [1, 2, 3, 4]);
/// assert_eq!(array_bytes::suffix_with::<_, _, 5>([1, 2, 3], 0), [1, 2, 3, 0, 0]);
/// ```
pub fn suffix_with<A, T, const N: usize>(any: A, element: T) -> [T; N]
where
A: AsRef<[T]>,
T: Copy,
{
let a = any.as_ref();
match a.len().cmp(&N) {
Ordering::Equal => slice2array_unchecked(a),
Ordering::Greater => slice2array_unchecked(&a[..N]),
Ordering::Less => {
let mut padded = [element; N];
padded[..a.len()].copy_from_slice(a);
padded
},
}
}
/// Convert `&[T]` to a type directly.
///
/// # Examples
/// ```
/// #[derive(Debug, PartialEq)]
/// struct LJF([u8; 17]);
/// impl From<[u8; 17]> for LJF {
/// fn from(array: [u8; 17]) -> Self {
/// Self(array)
/// }
/// }
///
/// assert_eq!(
/// array_bytes::slice_n_into::<u8, LJF, 17>(b"Love Jane Forever"),
/// Ok(LJF(*b"Love Jane Forever"))
/// );
/// ```
pub fn slice_n_into<T, V, const N: usize>(slice: &[T]) -> Result<V>
where
T: Copy,
V: From<[T; N]>,
{
Ok(slice2array(slice)?.into())
}
/// Just like [`slice_n_into`] but without the checking.
///
/// # Examples
/// ```
/// #[derive(Debug, PartialEq)]
/// struct LJF([u8; 17]);
/// impl From<[u8; 17]> for LJF {
/// fn from(array: [u8; 17]) -> Self {
/// Self(array)
/// }
/// }
///
/// assert_eq!(
/// array_bytes::slice_n_into_unchecked::<u8, LJF, 17>(b"Love Jane Forever"),
/// LJF(*b"Love Jane Forever")
/// );
/// ```
pub fn slice_n_into_unchecked<T, V, const N: usize>(slice: &[T]) -> V
where
T: Copy,
V: From<[T; N]>,
{
slice2array_unchecked(slice).into()
}
/// [`Vec<T>`] to `[T; N]`.
///
/// # Examples
/// ```
/// assert_eq!(array_bytes::vec2array::<_, 8>(vec![0; 8]), Ok([0; 8]));
/// ```
pub fn vec2array<T, const N: usize>(vec: Vec<T>) -> Result<[T; N]> {
vec.try_into().map_err(|_| Error::MismatchedLength { expect: N })
}
/// Just like [`vec2array`] but without the checking.
///
/// # Examples
/// ```
/// assert_eq!(array_bytes::vec2array_unchecked::<_, 8>(vec![0; 8]), [0; 8]);
/// ```
pub fn vec2array_unchecked<T, const N: usize>(vec: Vec<T>) -> [T; N] {
vec2array(vec).unwrap()
}
/// Convert [`Vec<T>`] to a type directly.
///
/// # Examples
///
/// ```
/// #[derive(Debug, PartialEq)]
/// struct LJF([u8; 17]);
/// impl From<[u8; 17]> for LJF {
/// fn from(array: [u8; 17]) -> Self {
/// Self(array)
/// }
/// }
///
/// assert_eq!(
/// array_bytes::vec_n_into::<u8, LJF, 17>(b"Love Jane Forever".to_vec()),
/// Ok(LJF(*b"Love Jane Forever"))
/// );
/// ```
pub fn vec_n_into<T, V, const N: usize>(vec: Vec<T>) -> Result<V>
where
V: From<[T; N]>,
{
Ok(vec2array(vec)?.into())
}
/// Just like [`vec_n_into`] but without the checking.
///
/// # Examples
/// ```
/// #[derive(Debug, PartialEq)]
/// struct LJF([u8; 17]);
/// impl From<[u8; 17]> for LJF {
/// fn from(array: [u8; 17]) -> Self {
/// Self(array)
/// }
/// }
///
/// assert_eq!(
/// array_bytes::vec_n_into_unchecked::<u8, LJF, 17>(b"Love Jane Forever".to_vec()),
/// LJF(*b"Love Jane Forever")
/// );
/// ```
pub fn vec_n_into_unchecked<T, V, const N: usize>(vec: Vec<T>) -> V
where
V: From<[T; N]>,
{
vec2array_unchecked(vec).into()
}
/// Convert hex bytes to hex string.
///
/// This is useful when you are interacting with the IO.
///
/// # Examples
/// ```
/// assert_eq!(
/// array_bytes::hex_bytes2hex_str(b"0x4c6f7665204a616e6520466f7265766572"),
/// Ok("0x4c6f7665204a616e6520466f7265766572"),
/// );
/// ```
pub fn hex_bytes2hex_str(bytes: &[u8]) -> Result<&str> {
for (i, byte) in bytes.iter().enumerate().skip(if bytes.starts_with(b"0x") { 2 } else { 0 }) {
if !is_hex_ascii(byte) {
Err(Error::InvalidCharacter { character: *byte as _, index: i })?;
}
}
Ok(
// Validated in previous step, never fails here; qed.
unsafe { str::from_utf8_unchecked(bytes) },
)
}
/// Just like [`hex_bytes2hex_str`] but without the checking.
///
/// # Safety
/// See the [`str::from_utf8_unchecked`].
///
/// # Examples
/// ```
/// unsafe {
/// assert_eq!(
/// array_bytes::hex_bytes2hex_str_unchecked(b"0x4c6f7665204a616e6520466f7265766572"),
/// "0x4c6f7665204a616e6520466f7265766572",
/// );
/// }
/// ```
pub unsafe fn hex_bytes2hex_str_unchecked(bytes: &[u8]) -> &str {
str::from_utf8_unchecked(bytes)
}
/// `AsRef<[u8]>` to [`String`].
///
/// # Examples
/// ```
/// assert_eq!(
/// array_bytes::bytes2hex("0x", b"Love Jane Forever"),
/// String::from("0x4c6f7665204a616e6520466f7265766572")
/// );
/// ```
pub fn bytes2hex<B>(prefix: &str, bytes: B) -> String
where
B: AsRef<[u8]>,
{
let bytes = bytes.as_ref();
let mut hex = String::with_capacity(prefix.len() + bytes.len() * 2);
prefix.chars().for_each(|byte| hex.push(byte));
bytes.iter().for_each(|byte| {
hex.push(char::from_digit((byte >> 4) as _, 16).unwrap());
hex.push(char::from_digit((byte & 0xf) as _, 16).unwrap());
});
hex
}
/// Just like [`hex2bytes`] but to a fixed length array.
///
/// # Examples
/// ```
/// assert_eq!(
/// array_bytes::hex2array("0x4c6f7665204a616e6520466f7265766572"),
/// Ok(*b"Love Jane Forever")
/// );
/// ```
pub fn hex2array<H, const N: usize>(hex: H) -> Result<[u8; N]>
where
H: AsRef<[u8]>,
{
vec2array(hex2bytes(hex.as_ref())?)
}
/// Just like [`hex2array`] but without the checking.
///
/// # Examples
/// ```
/// assert_eq!(
/// array_bytes::hex2array_unchecked("0x4c6f7665204a616e6520466f7265766572"),
/// *b"Love Jane Forever"
/// );
/// ```
pub fn hex2array_unchecked<H, const N: usize>(hex: H) -> [u8; N]
where
H: AsRef<[u8]>,
{
hex2bytes_unchecked(hex).try_into().unwrap()
}
/// `AsRef<[u8]>` to [`Vec<u8>`].
///
/// Return error if:
/// - length is odd
/// - encounter invalid hex ascii
///
/// # Examples
/// ```
/// assert_eq!(
/// array_bytes::hex2bytes("0x4c6f7665204a616e6520466f7265766572"),
/// Ok(b"Love Jane Forever".to_vec())
/// );
/// ```
pub fn hex2bytes<H>(hex: H) -> Result<Vec<u8>>
where
H: AsRef<[u8]>,
{
let hex = strip_0x(hex.as_ref());
if hex.len() % 2 != 0 {
Err(Error::InvalidLength)?;
}
let mut bytes = Vec::new();
for i in (0..hex.len()).step_by(2) {
bytes.push(hex2byte((&hex[i], i), (&hex[i + 1], i + 1))?);
}
Ok(bytes)
}
/// Just like [`hex2bytes`] but without checking.
///
/// # Examples
/// ```
/// assert_eq!(
/// array_bytes::hex2bytes_unchecked("0x4c6f7665204a616e6520466f7265766572"),
/// *b"Love Jane Forever"
/// );
/// ```
pub fn hex2bytes_unchecked<H>(hex: H) -> Vec<u8>
where
H: AsRef<[u8]>,
{
let hex = strip_0x(hex.as_ref());
(0..hex.len()).step_by(2).map(|i| hex2byte_unchecked(&hex[i], &hex[i + 1])).collect()
}
/// `AsRef<[u8]>` to `&[u8]`.
///
/// This function will modify the given slice's source and return the revised result.
///
/// Return error if:
/// - length is odd
/// - encounter invalid hex ascii
/// - mismatched slice size
///
/// # Examples
/// ```
/// let mut bytes = [0; 17];
///
/// assert_eq!(
/// array_bytes::hex2slice("0x4c6f7665204a616e6520466f7265766572", &mut bytes),
/// Ok(b"Love Jane Forever".as_slice())
/// );
/// assert_eq!(bytes, *b"Love Jane Forever");
/// ```
pub fn hex2slice<H>(hex: H, slice: &mut [u8]) -> Result<&[u8]>
where
H: AsRef<[u8]>,
{
let hex = strip_0x(hex.as_ref());
if hex.len() % 2 != 0 {
Err(Error::InvalidLength)?;
}
let expected_len = hex.len() >> 1;
if expected_len != slice.len() {
Err(Error::MismatchedLength { expect: expected_len })?;
}
for (byte, i) in slice.iter_mut().zip((0..hex.len()).step_by(2)) {
*byte = hex2byte((&hex[i], i), (&hex[i + 1], i + 1))?;
}
Ok(slice)
}
/// Just like [`hex2slice`] but without checking.
///
/// # Examples
/// ```
/// let mut bytes = [0; 17];
///
/// assert_eq!(
/// array_bytes::hex2slice_unchecked("0x4c6f7665204a616e6520466f7265766572", &mut bytes),
/// b"Love Jane Forever"
/// );
/// assert_eq!(bytes, *b"Love Jane Forever");
/// ```
pub fn hex2slice_unchecked<H>(hex: H, slice: &mut [u8]) -> &[u8]
where
H: AsRef<[u8]>,
{
let hex = strip_0x(hex.as_ref());
slice
.iter_mut()
.zip((0..hex.len()).step_by(2))
.for_each(|(byte, i)| *byte = hex2byte_unchecked(&hex[i], &hex[i + 1]));
slice
}
/// Try to convert `AsRef<[u8]>` to `T` directly, where `T: From<Vec<u8>>`.
///
/// # Examples
/// ```
/// #[derive(Debug, PartialEq)]
/// struct LJF(Vec<u8>);
/// impl From<Vec<u8>> for LJF {
/// fn from(vec: Vec<u8>) -> Self {
/// Self(vec)
/// }
/// }
///
/// assert_eq!(
/// array_bytes::hex_into::<_, LJF>("0x4c6f7665204a616e6520466f7265766572"),
/// Ok(LJF(b"Love Jane Forever".to_vec()))
/// );
/// ```
pub fn hex_into<H, T>(hex: H) -> Result<T>
where
H: AsRef<[u8]>,
T: From<Vec<u8>>,
{
Ok(hex2bytes(hex.as_ref())?.into())
}
/// Just like [`hex_into`] but without the checking.
///
/// # Examples
/// ```
/// #[derive(Debug, PartialEq)]
/// struct LJF(Vec<u8>);
/// impl From<Vec<u8>> for LJF {
/// fn from(vec: Vec<u8>) -> Self {
/// Self(vec)
/// }
/// }
///
/// assert_eq!(
/// array_bytes::hex_into_unchecked::<_, LJF>("0x4c6f7665204a616e6520466f7265766572"),
/// LJF(b"Love Jane Forever".to_vec())
/// );
/// ```
pub fn hex_into_unchecked<H, T>(hex: H) -> T
where
H: AsRef<[u8]>,
T: From<Vec<u8>>,
{
hex2bytes_unchecked(hex).into()
}
/// Try to convert `AsRef<[u8]>` to `T` directly, where `T: From<[u8; N]>`.
///
/// # Examples
/// ```
/// #[derive(Debug, PartialEq)]
/// struct LJF([u8; 17]);
/// impl From<[u8; 17]> for LJF {
/// fn from(array: [u8; 17]) -> Self {
/// Self(array)
/// }
/// }
///
/// assert_eq!(
/// array_bytes::hex_n_into::<_, LJF, 17>("0x4c6f7665204a616e6520466f7265766572"),
/// Ok(LJF(*b"Love Jane Forever"))
/// );
/// ```
pub fn hex_n_into<H, T, const N: usize>(hex: H) -> Result<T>
where
H: AsRef<[u8]>,
T: From<[u8; N]>,
{
Ok(hex2array(hex)?.into())
}
/// Just like [`hex_n_into`] but without the checking.
///
/// # Examples
/// ```
/// #[derive(Debug, PartialEq)]
/// struct LJF([u8; 17]);
/// impl From<[u8; 17]> for LJF {
/// fn from(array: [u8; 17]) -> Self {
/// Self(array)
/// }
/// }
///
/// assert_eq!(
/// array_bytes::hex_n_into_unchecked::<_, LJF, 17>("0x4c6f7665204a616e6520466f7265766572"),
/// LJF(*b"Love Jane Forever")
/// );
/// ```
pub fn hex_n_into_unchecked<H, T, const N: usize>(hex: H) -> T
where
H: AsRef<[u8]>,
T: From<[u8; N]>,
{
hex2array_unchecked(hex).into()
}
/// Deserialize hex to `T`, where `T: From<Vec<u8>>`.
///
/// # Examples
/// ```
/// use serde::Deserialize;
///
/// #[derive(Debug, PartialEq)]
/// struct LJF(Vec<u8>);
/// impl From<Vec<u8>> for LJF {
/// fn from(vec: Vec<u8>) -> Self {
/// Self(vec)
/// }
/// }
///
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct WrappedLJF {
/// #[serde(deserialize_with = "array_bytes::hex_deserialize_into")]
/// ljf: LJF,
/// }
///
/// assert_eq!(
/// serde_json::from_str::<WrappedLJF>(r#"{
/// "ljf": "0x4c6f7665204a616e6520466f7265766572"
/// }"#).unwrap(),
/// WrappedLJF {
/// ljf: LJF(b"Love Jane Forever".to_vec())
/// }
/// );
#[cfg(feature = "serde")]
pub fn hex_deserialize_into<'de, D, T>(hex: D) -> CoreResult<T, D::Error>
where
D: Deserializer<'de>,
T: From<Vec<u8>>,
{
Ok(hex2bytes_unchecked(<&str>::deserialize(hex)?).into())
}
/// Deserialize hex to `T`, where `T: From<[u8; N]>`.
///
/// # Examples
/// ```
/// use serde::Deserialize;
///
/// #[derive(Debug, PartialEq)]
/// struct LJF([u8; 17]);
/// impl From<[u8; 17]> for LJF {
/// fn from(array: [u8; 17]) -> Self {
/// Self(array)
/// }
/// }
///
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct WrappedLJF {
/// #[serde(deserialize_with = "array_bytes::hex_deserialize_n_into")]
/// ljf: LJF,
/// }
///
/// assert_eq!(
/// serde_json::from_str::<WrappedLJF>(r#"{
/// "ljf": "0x4c6f7665204a616e6520466f7265766572"
/// }"#).unwrap(),
/// WrappedLJF {
/// ljf: LJF(*b"Love Jane Forever")
/// }
/// );
#[cfg(feature = "serde")]
pub fn hex_deserialize_n_into<'de, D, T, const N: usize>(hex: D) -> CoreResult<T, D::Error>
where
D: Deserializer<'de>,
T: From<[u8; N]>,
{
Ok(hex2array_unchecked(<&str>::deserialize(hex)?).into())
}
/// Deserialize hex to any Rust primitive num types.
///
/// # Examples
/// ```
/// use serde::Deserialize;
///
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct LJF {
/// #[serde(deserialize_with = "array_bytes::de_hex2num")]
/// _0: u8,
/// #[serde(deserialize_with = "array_bytes::de_hex2num")]
/// _1: u8,
/// #[serde(deserialize_with = "array_bytes::de_hex2num")]
/// _2: u8,
/// #[serde(deserialize_with = "array_bytes::de_hex2num")]
/// _3: u32,
/// }
///
/// assert_eq!(
/// serde_json::from_str::<LJF>(
/// r#"{
/// "_0": "0x5",
/// "_1": "0x2",
/// "_2": "0x0",
/// "_3": "0x522"
/// }"#
/// )
/// .unwrap(),
/// LJF { _0: 5, _1: 2, _2: 0, _3: 1314 }
/// );
/// ```
#[cfg(feature = "serde")]
pub fn de_hex2num<'de, D, T>(hex: D) -> CoreResult<T, D::Error>
where
D: Deserializer<'de>,
T: TryFromHex,
{
let hex = <&str>::deserialize(hex)?;
T::try_from_hex(hex).map_err(|_| D::Error::custom(alloc::format!("Invalid hex str `{}`", hex)))
}
/// Deserialize hex to [`Vec<u8>`].
///
/// # Examples
/// ```
/// use serde::Deserialize;
///
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct LJF {
/// #[serde(deserialize_with = "array_bytes::de_hex2bytes")]
/// ljf: Vec<u8>,
/// }
///
/// assert_eq!(
/// serde_json::from_str::<LJF>(
/// r#"{
/// "ljf": "0x4c6f7665204a616e6520466f7265766572"
/// }"#
/// )
/// .unwrap(),
/// LJF { ljf: (*b"Love Jane Forever").to_vec() }
/// );
/// ```
#[cfg(feature = "serde")]
pub fn de_hex2bytes<'de, D>(hex: D) -> CoreResult<Vec<u8>, D::Error>
where
D: Deserializer<'de>,
{
let hex = <&str>::deserialize(hex)?;
hex2bytes(hex).map_err(|_| D::Error::custom(alloc::format!("Invalid hex str `{}`", hex)))
}
fn strip_0x(hex: &[u8]) -> &[u8] {
if let Some(hex) = hex.strip_prefix(b"0x") {
hex
} else {
hex
}
}
fn is_hex_ascii(byte: &u8) -> bool {
// Convert to lowercase.
let byte = byte | 0b10_0000;
matches!(byte, b'0'..=b'9' | b'a'..=b'f')
}
fn hex_ascii2digit(hex_ascii: &u8) -> Option<u8> {
// Convert to lowercase.
let hex_ascii = hex_ascii | 0b10_0000;
match hex_ascii {
b'0'..=b'9' => Some(hex_ascii - b'0'),
b'a'..=b'f' => Some(hex_ascii - b'a' + 10),
_ => None,
}
}
fn hex2byte(hex_ascii_1: (&u8, usize), hex_ascii_2: (&u8, usize)) -> Result<u8> {
let byte = hex_ascii2digit(hex_ascii_1.0)
.ok_or(Error::InvalidCharacter { character: *hex_ascii_1.0 as _, index: hex_ascii_1.1 })?
<< 4 | hex_ascii2digit(hex_ascii_2.0)
.ok_or(Error::InvalidCharacter { character: *hex_ascii_2.0 as _, index: hex_ascii_2.1 })?;
Ok(byte)
}
fn hex2byte_unchecked(hex_ascii_1: &u8, hex_ascii_2: &u8) -> u8 {
hex_ascii2digit(hex_ascii_1).unwrap() << 4 | hex_ascii2digit(hex_ascii_2).unwrap()
}