leb128fmt/lib.rs
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 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
//! Leb128fmt is a library to decode and encode [LEB128][leb128] formatted numbers.
//! LEB128 is a variable length integer compression format.
//!
//! The library does not allocate memory and can be used in `no_std` and
//! `no_std::no_alloc` environments.
//!
//! Various functions are provided which encode and decode signed and unsigned
//! integers with the number of bits in the function name. There are generic
//! functions provided to read and write slices of encoded values as well.
//!
//! There are encoding functions with the word `fixed` in the name which will
//! write out a value using the maximum number of bytes for a given bit size.
//! For instance, using [`encode_fixed_u32`] will always use 5 bytes to
//! write out the value. While always using the maximum number of bytes removes
//! the benefit of compression, in some scenarios, it is beneficial to have a
//! fixed encoding size.
//!
//! Finally, there are macros provided which you can use to build your own
//! encoding and decoding functions for unusual variants like signed 33 bit
//! values.
//!
//! # Examples
//!
//! ## Functions using Arrays
//!
//! ```rust
//! // Encode an unsigned 32 bit number:
//! let (output, written_len) = leb128fmt::encode_u32(43110).unwrap();
//! // The number of bytes written in the output array
//! assert_eq!(written_len, 3);
//! assert_eq!(&output[..written_len], &[0xE6, 0xD0, 0x02]);
//! // The entire output array. Note you should only use &output[..written_len] to copy
//! // into your output buffer
//! assert_eq!(output, [0xE6, 0xD0, 0x02, 0x00, 0x00]);
//!
//! // Decode an unsigned 32 bit number:
//! let input = [0xE6, 0xD0, 0x02, 0x00, 0x00];
//! let (result, read_len) = leb128fmt::decode_u32(input).unwrap();
//! assert_eq!(result, 43110);
//! assert_eq!(read_len, 3);
//! ```
//!
//! ### Helper Functions
//!
//! If you are reading from an input buffer, you can use [`is_last`] and
//! [`max_len`] to determine the bytes to copy into the array.
//!
//! ```rust
//! let buffer = vec![0xFE, 0xFE, 0xE6, 0xD0, 0x02, 0xFE, 0xFE, 0xFE];
//! let pos = 2;
//! let end = buffer.iter().skip(pos).copied().position(leb128fmt::is_last).map(|p| pos + p);
//! if let Some(end) = end {
//! if end <= pos + leb128fmt::max_len::<32>() {
//! let mut input = [0u8; leb128fmt::max_len::<32>()];
//! input[..=end - pos].copy_from_slice(&buffer[pos..=end]);
//! let (result, read_len) = leb128fmt::decode_u32(input).unwrap();
//! assert_eq!(result, 43110);
//! assert_eq!(read_len, 3);
//! } else {
//! // invalid LEB128 encoding
//!# panic!();
//! }
//! } else {
//! if buffer.len() - pos < leb128fmt::max_len::<32>() {
//! // Need more bytes in the buffer
//!# panic!();
//! } else {
//! // invalid LEB128 encoding
//!# panic!();
//! }
//! }
//!
//! ```
//!
//! ## Functions Using Slices
//!
//! ```rust
//! let mut buffer = vec![0xFE; 10];
//! let mut pos = 1;
//!
//! // Encode an unsigned 64 bit number with a mutable slice:
//! let result = leb128fmt::encode_uint_slice::<u64, 64>(43110u64, &mut buffer, &mut pos);
//! // The number of bytes written in the output array
//! assert_eq!(result, Some(3));
//! assert_eq!(pos, 4);
//!
//! assert_eq!(buffer, [0xFE, 0xE6, 0xD0, 0x02, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE]);
//!
//! // Decode an unsigned 64 bit number with a slice:
//! pos = 1;
//! let result = leb128fmt::decode_uint_slice::<u64, 64>(&buffer, &mut pos);
//! assert_eq!(result, Ok(43110));
//! assert_eq!(pos, 4);
//! ```
//!
//! ## Functions Using Fixed Sized Encoding
//!
//! There may be several different ways to encode a value. For instance, `0` can
//! be encoded as 32 bits unsigned:
//!
//! ```rust
//! let mut pos = 0;
//! assert_eq!(leb128fmt::decode_uint_slice::<u32, 32>(&[0x00], &mut pos), Ok(0));
//! pos = 0;
//! assert_eq!(leb128fmt::decode_uint_slice::<u32, 32>(&[0x80, 0x00], &mut pos), Ok(0));
//! pos = 0;
//! assert_eq!(leb128fmt::decode_uint_slice::<u32, 32>(&[0x80, 0x80, 0x00], &mut pos), Ok(0));
//! pos = 0;
//! assert_eq!(leb128fmt::decode_uint_slice::<u32, 32>(&[0x80, 0x80, 0x80, 0x00], &mut pos), Ok(0));
//! pos = 0;
//! assert_eq!(leb128fmt::decode_uint_slice::<u32, 32>(&[0x80, 0x80, 0x80, 0x80, 0x00], &mut pos), Ok(0));
//! ```
//!
//! There are functions provided to encode a value using the maximum number of
//! bytes possible for a given bit size. Using the maximum number of bytes
//! removes the benefit of compression, but it may be useful in a few scenarios.
//!
//! For instance, if a binary format needs to store the size or offset of some
//! data before the size of data is known, it can be beneficial to write a fixed
//! sized `0` placeholder value first. Then, once the real value is known, the
//! `0` placeholder can be overwritten without moving other bytes. The real
//! value is also written out using the fixed maximum number of bytes.
//!
//! ```rust
//! // Encode an unsigned 32 bit number with all 5 bytes:
//! let output = leb128fmt::encode_fixed_u32(43110).unwrap();
//! assert_eq!(output, [0xE6, 0xD0, 0x82, 0x80, 0x00]);
//!
//! // Decode an unsigned 32 bit number:
//! let input = output;
//! let (result, read_len) = leb128fmt::decode_u32(input).unwrap();
//! assert_eq!(result, 43110);
//!
//! // Note that all 5 bytes are read
//! assert_eq!(read_len, 5);
//! ```
//!
//! [leb128]: https://en.wikipedia.org/wiki/LEB128
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
unused_lifetimes,
unused_qualifications
)]
use core::fmt;
/// Returns the maximum byte length that is used to encode a value for a given
/// number of `BITS`.
///
/// A value can possibly be encoded with a fewer number of bytes.
///
/// # Example
///
/// ```rust
/// assert_eq!(5, leb128fmt::max_len::<32>());
/// assert_eq!(10, leb128fmt::max_len::<64>());
///
/// assert_eq!(5, leb128fmt::max_len::<33>());
/// ```
#[inline]
#[must_use]
pub const fn max_len<const BITS: u32>() -> usize {
let rem = if BITS % 7 == 0 { 0 } else { 1 };
((BITS / 7) + rem) as usize
}
/// Returns true if this is the last byte in an encoded LEB128 value.
///
/// # Example
///
/// ```rust
/// let bytes = &[0x42, 0x8F, 0xFF, 0x7F, 0xFF];
/// let pos = 1;
/// let end = bytes.iter().skip(pos).copied().position(leb128fmt::is_last);
/// let end = end.unwrap();
/// assert_eq!(pos + end, 3);
/// let value = &bytes[pos..=pos + end];
/// ```
#[inline]
#[must_use]
pub const fn is_last(byte: u8) -> bool {
byte & 0x80 == 0
}
/// Builds custom unsigned integer encode functions.
///
/// The macro's 3 parameters are:
///
/// 1. The name of the function.
/// 2. The type to return.
/// 3. The number of encoded BITS to decode.
///
/// ```rust
/// leb128fmt::encode_uint_arr!(encode_u33, u64, 33);
///
/// let result = encode_u33(0);
/// assert_eq!(Some(([0x00, 0x00, 0x00, 0x00, 0x00], 1)), result);
///
/// let result = encode_u33(8589934591);
/// assert_eq!(Some(([0xFF, 0xFF, 0xFF, 0xFF, 0x1F], 5)), result);
/// ```
#[macro_export]
macro_rules! encode_uint_arr {
($func:ident, $num_ty:ty, $bits:literal) => {
/// Encodes a value as an unsigned LEB128 number.
///
/// If the value can be encoded in the given number of bits, then return
/// the encoded output and the index after the last byte written.
///
/// If the value cannot be encoded with the given number of bits, then return None.
#[must_use]
pub const fn $func(
mut value: $num_ty,
) -> Option<(
[u8; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize],
usize,
)> {
const BITS: u32 = $bits;
if <$num_ty>::BITS > BITS && 1 < value >> BITS - 1 {
return None;
}
let mut output = [0; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize];
let mut index = 0;
loop {
let mut b = (value & 0x7f) as u8;
value >>= 7;
let done = value == 0;
if !done {
b |= 0x80;
}
output[index] = b;
index += 1;
if done {
return Some((output, index));
}
}
}
};
}
encode_uint_arr!(encode_u32, u32, 32);
encode_uint_arr!(encode_u64, u64, 64);
/// Builds custom unsigned integer encode functions with the max byte length of
/// byte arrays used.
///
/// The macro's 3 parameters are:
///
/// 1. The name of the function.
/// 2. The type to return.
/// 3. The number of encoded BITS to decode.
///
/// ```rust
/// leb128fmt::encode_fixed_uint_arr!(encode_fixed_u33, u64, 33);
///
/// let output = encode_fixed_u33(0);
/// assert_eq!(Some([0x80, 0x80, 0x80, 0x80, 0x00]), output);
///
/// let output = encode_fixed_u33(8589934591);
/// assert_eq!(Some([0xFF, 0xFF, 0xFF, 0xFF, 0x1F]), output);
/// ```
#[macro_export]
macro_rules! encode_fixed_uint_arr {
($func:ident, $num_ty:ty, $bits:literal) => {
/// Encodes an unsigned LEB128 number with using the maximum number of
/// bytes for the given bits length.
///
/// If the value can be encoded in the given number of bits, then return
/// the encoded value.
///
/// If the value cannot be encoded with the given number of bits, then return None.
#[must_use]
pub const fn $func(
value: $num_ty,
) -> Option<[u8; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize]> {
const BITS: u32 = $bits;
if <$num_ty>::BITS > BITS && 1 < value >> BITS - 1 {
return None;
}
let mut output = [0; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize];
let mut index = 0;
let mut shift: u32 = 0;
loop {
let v = value >> shift;
let mut b = (v & 0x7f) as u8;
let done = shift == BITS - (BITS % 7);
if !done {
b |= 0x80;
}
output[index] = b;
index += 1;
shift += 7;
if done {
return Some(output);
}
}
}
};
}
encode_fixed_uint_arr!(encode_fixed_u32, u32, 32);
encode_fixed_uint_arr!(encode_fixed_u64, u64, 64);
/// Builds custom unsigned integer decode functions.
///
/// The macro's 3 parameters are:
///
/// 1. The name of the function.
/// 2. The type to return.
/// 3. The number of encoded BITS to decode.
///
/// ```rust
/// leb128fmt::decode_uint_arr!(decode_u33, u64, 33);
///
/// let input = [0xFF, 0xFF, 0xFF, 0xFF, 0x1F];
/// let result = decode_u33(input);
/// assert_eq!(Some((8589934591, 5)), result);
/// ```
#[macro_export]
macro_rules! decode_uint_arr {
($func:ident, $num_ty:ty, $bits:literal) => {
/// Decodes an unsigned LEB128 number.
///
/// If there is a valid encoded value, returns the decoded value and the
/// index after the last byte read.
///
/// If the encoding is incorrect, returns `None`.
///
/// If the size in bits of the returned type is less than the size of the value in bits, returns `None`.
/// For instance, if 33 bits are being decoded, then the returned type must be at least a `u64`.
#[must_use]
pub const fn $func(
input: [u8; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize],
) -> Option<($num_ty, usize)> {
const BITS: u32 = $bits;
if <$num_ty>::BITS < BITS {
return None;
}
let n = input[0];
if n & 0x80 == 0 {
return Some((n as $num_ty, 1));
}
let mut result = (n & 0x7f) as $num_ty;
let mut shift = 7;
let mut pos = 1;
loop {
let n = input[pos];
// If unnecessary bits are set (the bits would be dropped when
// the value is shifted), then return an error.
//
// This error may be too strict.
//
// There should be at least a simple check to quickly
// determine that the decoding has failed instead of
// misinterpreting further data.
//
// For a less strict check, the && condition could be:
//
// (n & 0x80) != 0
//
// Another stricter condition is if the last byte has a 0 value.
// The encoding is correct but not the minimal number of bytes
// was used to express the final value.
if shift == BITS - (BITS % 7) && 1 << (BITS % 7) <= n {
return None;
}
if n & 0x80 == 0 {
result |= (n as $num_ty) << shift;
return Some((result, pos + 1));
}
result |= ((n & 0x7f) as $num_ty) << shift;
shift += 7;
pos += 1;
}
}
};
}
decode_uint_arr!(decode_u32, u32, 32);
decode_uint_arr!(decode_u64, u64, 64);
mod private {
pub trait Sealed {}
impl Sealed for u8 {}
impl Sealed for u16 {}
impl Sealed for u32 {}
impl Sealed for u64 {}
impl Sealed for u128 {}
impl Sealed for i8 {}
impl Sealed for i16 {}
impl Sealed for i32 {}
impl Sealed for i64 {}
impl Sealed for i128 {}
}
/// Sealed trait for supported unsigned integer types.
pub trait UInt: private::Sealed {
/// Size of the type in bits.
const BITS: u32;
}
impl UInt for u8 {
const BITS: u32 = u8::BITS;
}
impl UInt for u16 {
const BITS: u32 = u16::BITS;
}
impl UInt for u32 {
const BITS: u32 = u32::BITS;
}
impl UInt for u64 {
const BITS: u32 = u64::BITS;
}
impl UInt for u128 {
const BITS: u32 = u128::BITS;
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum InnerError {
NeedMoreBytes,
InvalidEncoding,
}
/// Error when decoding a LEB128 value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(InnerError);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
InnerError::NeedMoreBytes => f.write_str("need more bytes"),
InnerError::InvalidEncoding => f.write_str("invalid encoding"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl Error {
/// If more bytes are needed in the slice to decode the value
#[inline]
#[must_use]
pub const fn is_more_bytes_needed(&self) -> bool {
matches!(self.0, InnerError::NeedMoreBytes)
}
/// If the value has an invalid encoding
#[inline]
#[must_use]
pub const fn is_invalid_encoding(&self) -> bool {
matches!(self.0, InnerError::InvalidEncoding)
}
}
/// Encodes a given value into an output slice using the fixed set of bytes.
///
/// # Examples
///
/// ```rust
/// let mut buffer = vec![254; 10];
/// let mut pos = 0;
/// let result = leb128fmt::encode_uint_slice::<_, 32>(0u32, &mut buffer, &mut pos);
/// assert_eq!(Some(1), result);
/// assert_eq!(1, pos);
/// assert_eq!(&[0x00], &buffer[..pos]);
///
/// assert_eq!(&[0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
///
/// let result = leb128fmt::encode_uint_slice::<_, 32>(u32::MAX, &mut buffer, &mut pos);
/// assert_eq!(Some(5), result);
/// assert_eq!(6, pos);
/// assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF, 0x0F], &buffer[1..pos]);
///
/// assert_eq!(&[0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
///
/// // Will try to encode even if the output slice is not as big as the maximum
/// // number of bytes required to output every value for the given BITS
/// let mut buffer = vec![254; 4];
/// let mut pos = 0;
/// let result = leb128fmt::encode_uint_slice::<_, 32>(1028u32, &mut buffer, &mut pos);
/// assert_eq!(Some(2), result);
/// assert_eq!(&[0x84, 0x08, 0xFE, 0xFE], buffer.as_slice());
///
/// // Will return `None` if the output buffer is not long enough but will have partially written
/// // the value
/// let mut buffer = vec![254; 4];
/// let mut pos = 0;
/// let result = leb128fmt::encode_uint_slice::<_, 32>(u32::MAX, &mut buffer, &mut pos);
/// assert_eq!(None, result);
/// assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF], buffer.as_slice());
///
/// // Will return `None` if the given value cannot be encoded with the given number of bits.
/// let mut buffer = vec![254; 10];
/// let mut pos = 0;
/// let result = leb128fmt::encode_uint_slice::<_, 32>(u64::MAX, &mut buffer, &mut pos);
/// assert_eq!(None, result);
/// assert_eq!(&[0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
/// ```
#[allow(clippy::manual_let_else)]
pub fn encode_uint_slice<T, const BITS: u32>(
mut value: T,
output: &mut [u8],
pos: &mut usize,
) -> Option<usize>
where
T: Copy
+ PartialEq
+ core::ops::BitAnd
+ core::ops::Shr<u32>
+ core::ops::ShrAssign<u32>
+ From<u8>
+ UInt,
<T as core::ops::Shr<u32>>::Output: PartialEq<T>,
u8: TryFrom<<T as core::ops::BitAnd<T>>::Output>,
{
if BITS < T::BITS && value >> BITS != T::from(0) {
return None;
}
let mut index = *pos;
loop {
if output.len() <= index {
return None;
}
let mut b = match u8::try_from(value & T::from(0x7f)) {
Ok(b) => b,
Err(_) => unreachable!(),
};
value >>= 7;
let done = value == T::from(0);
if !done {
b |= 0x80;
}
output[index] = b;
index += 1;
if done {
let len = index - *pos;
*pos = index;
return Some(len);
}
}
}
/// Encodes a given value into an output slice using a fixed set of bytes.
///
/// # Examples
///
/// ```rust
/// let mut buffer = vec![254; 10];
/// let mut pos = 0;
/// let result = leb128fmt::encode_fixed_uint_slice::<_, 32>(0u32, &mut buffer, &mut pos);
/// assert_eq!(Some(5), result);
/// assert_eq!(5, pos);
/// assert_eq!(&[0x80, 0x80, 0x80, 0x80, 0x00], &buffer[..pos]);
///
/// assert_eq!(&[0x80, 0x80, 0x80, 0x80, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
///
/// let result = leb128fmt::encode_fixed_uint_slice::<_, 32>(u32::MAX, &mut buffer, &mut pos);
/// assert_eq!(Some(5), result);
/// assert_eq!(10, pos);
/// assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF, 0x0F], &buffer[5..pos]);
///
/// assert_eq!(&[0x80, 0x80, 0x80, 0x80, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F], buffer.as_slice());
///
/// // Will return `None` if the output buffer is not long enough.
/// let mut buffer = vec![254; 4];
/// let mut pos = 0;
/// let result = leb128fmt::encode_fixed_uint_slice::<_, 32>(u32::MAX, &mut buffer, &mut pos);
/// assert_eq!(None, result);
/// assert_eq!(&[0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
///
/// // Will return `None` if the given value cannot be encoded with the given number of bits.
/// let mut buffer = vec![254; 10];
/// let mut pos = 0;
/// let result = leb128fmt::encode_fixed_uint_slice::<_, 32>(u64::MAX, &mut buffer, &mut pos);
/// assert_eq!(None, result);
/// assert_eq!(&[0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
/// ```
#[allow(clippy::manual_let_else)]
pub fn encode_fixed_uint_slice<T, const BITS: u32>(
mut value: T,
output: &mut [u8],
pos: &mut usize,
) -> Option<usize>
where
T: Copy + core::ops::BitAnd + core::ops::Shr<u32> + core::ops::ShrAssign<u32> + From<u8> + UInt,
<T as core::ops::Shr<u32>>::Output: PartialEq<T>,
u8: TryFrom<<T as core::ops::BitAnd>::Output>,
{
if BITS < T::BITS && value >> BITS != T::from(0) {
return None;
}
if output[*pos..].len() < max_len::<BITS>() {
return None;
}
let mut index = *pos;
for _ in 0..(max_len::<BITS>() - 1) {
let mut b = match u8::try_from(value & T::from(0x7f)) {
Ok(b) => b,
Err(_) => unreachable!(),
};
b |= 0x80;
value >>= 7;
output[index] = b;
index += 1;
}
let b = match u8::try_from(value & T::from(0x7f)) {
Ok(b) => b,
Err(_) => unreachable!(),
};
output[index] = b;
index += 1;
let len = index - *pos;
*pos = index;
Some(len)
}
/// Decodes an unsigned integer from a slice of bytes and starting at a given position.
///
/// # Errors
///
/// Returns an error if the value is not properly encoded or if more bytes are
/// needed to decode the value.
///
/// # Panics
///
/// Panics if the size in bits of the returned type is less than the size of the value in bits.
/// For instance, if 33 bits are being decoded, then the returned type must be at least a `u64`.
///
/// ```rust
/// let input = [0x42, 0x8F, 0xFF, 0x7F, 0xFF];
/// let mut pos = 1;
/// let result = leb128fmt::decode_uint_slice::<u32, 32>(&input, &mut pos);
/// assert_eq!(result, Ok(2097039));
/// assert_eq!(pos, 4);
/// ```
pub fn decode_uint_slice<T, const BITS: u32>(input: &[u8], pos: &mut usize) -> Result<T, Error>
where
T: core::ops::Shl<u32, Output = T> + core::ops::BitOrAssign + From<u8> + UInt,
{
assert!(BITS <= T::BITS);
if input.len() <= *pos {
return Err(Error(InnerError::NeedMoreBytes));
}
let n = input[*pos];
if is_last(n) {
*pos += 1;
return Ok(T::from(n));
}
let mut result = T::from(n & 0x7f);
let mut shift: u32 = 7;
let mut idx = *pos + 1;
loop {
if input.len() <= idx {
return Err(Error(InnerError::NeedMoreBytes));
}
let n = input[idx];
// If unnecessary bits are set (the bits would be dropped when
// the value is shifted), then return an error.
//
// This error may be too strict.
//
// There should be at least a simple check to quickly
// determine that the decoding has failed instead of
// misinterpreting further data.
//
// For a less strict check, the && condition could be:
//
// (n & 0x80) != 0
//
// Another stricter condition is if the last byte has a 0 value.
// The encoding is correct but not the minimal number of bytes
// was used to express the final value.
if shift == BITS - (BITS % 7) && 1 << (BITS % 7) <= n {
return Err(Error(InnerError::InvalidEncoding));
}
if is_last(n) {
result |= T::from(n) << shift;
*pos = idx + 1;
return Ok(result);
}
result |= T::from(n & 0x7f) << shift;
shift += 7;
idx += 1;
}
}
/// Builds custom signed integer encode functions.
///
/// The macro's 3 parameters are:
///
/// 1. The name of the function.
/// 2. The type to return.
/// 3. The number of encoded BITS to decode.
///
/// ```rust
/// leb128fmt::encode_sint_arr!(encode_s33, i64, 33);
///
/// let result = encode_s33(0);
/// assert_eq!(Some(([0x00, 0x00, 0x00, 0x00, 0x00], 1)), result);
///
/// let result = encode_s33(4_294_967_295);
/// assert_eq!(Some(([0xFF, 0xFF, 0xFF, 0xFF, 0x0F], 5)), result);
///
/// let result = encode_s33(-4_294_967_296);
/// assert_eq!(Some(([0x80, 0x80, 0x80, 0x80, 0x70], 5)), result);
///
/// let result = encode_s33(-1);
/// assert_eq!(Some(([0x7F, 0x00, 0x00, 0x00, 0x00], 1)), result);
/// ```
#[macro_export]
macro_rules! encode_sint_arr {
($func:ident, $num_ty:ty, $bits:literal) => {
/// Encodes a value as a signed LEB128 number.
#[must_use]
pub fn $func(
mut value: $num_ty,
) -> Option<(
[u8; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize],
usize,
)> {
const BITS: u32 = $bits;
if BITS < <$num_ty>::BITS {
let v: $num_ty = value >> BITS - 1;
if v != 0 && v != -1 {
return None;
}
}
let mut output = [0; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize];
let mut index = 0;
loop {
let b = (value & 0x7f) as u8;
value >>= 7;
if (value == 0 && b & 0x40 == 0) || (value == -1 && (b & 0x40) != 0) {
output[index] = b;
return Some((output, index + 1));
}
output[index] = b | 0x80;
index += 1;
}
}
};
}
encode_sint_arr!(encode_s32, i32, 32);
encode_sint_arr!(encode_s64, i64, 64);
/// Builds custom signed integer encode functions with the max byte length of
/// byte arrays used.
///
/// The macro's 3 parameters are:
///
/// 1. The name of the function.
/// 2. The type to return.
/// 3. The number of encoded BITS to decode.
///
/// ```rust
/// leb128fmt::encode_fixed_sint_arr!(encode_fixed_s33, i64, 33);
///
/// let result = encode_fixed_s33(0);
/// assert_eq!(Some([0x80, 0x80, 0x80, 0x80, 0x00]), result);
///
/// let result = encode_fixed_s33(4_294_967_295);
/// assert_eq!(Some([0xFF, 0xFF, 0xFF, 0xFF, 0x0F]), result);
///
/// let result = encode_fixed_s33(-4_294_967_296);
/// assert_eq!(Some([0x80, 0x80, 0x80, 0x80, 0x70]), result);
///
/// let result = encode_fixed_s33(-1);
/// assert_eq!(Some([0xFF, 0xFF, 0xFF, 0xFF, 0x7F]), result);
/// ```
#[macro_export]
macro_rules! encode_fixed_sint_arr {
($func:ident, $num_ty:ty, $bits:literal) => {
/// Encodes a value as a signed LEB128 number.
#[must_use]
pub const fn $func(
mut value: $num_ty,
) -> Option<[u8; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize]> {
const BITS: u32 = $bits;
if BITS < <$num_ty>::BITS {
let v = value >> BITS - 1;
if v != 0 && v != -1 {
return None;
}
}
let mut output = [0; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize];
let mut index = 0;
let mut extend_negative = false;
loop {
let b = (value & 0x7f) as u8;
value >>= 7;
output[index] = b | 0x80;
index += 1;
if value == 0 && b & 0x40 == 0 {
break;
}
if value == -1 && (b & 0x40) != 0 {
extend_negative = true;
break;
}
}
loop {
if index == output.len() {
output[index - 1] &= 0x7F;
return Some(output);
}
if extend_negative {
output[index] = 0xFF;
} else {
output[index] = 0x80;
}
index += 1;
}
}
};
}
encode_fixed_sint_arr!(encode_fixed_s32, i32, 32);
encode_fixed_sint_arr!(encode_fixed_s64, i64, 64);
/// Builds custom signed integer decode functions.
///
/// The macro's 3 parameters are:
///
/// 1. The name of the function.
/// 2. The type to return.
/// 3. The number of encoded BITS to decode.
///
/// ```rust
/// leb128fmt::decode_sint_arr!(decode_s33, i64, 33);
///
/// let input = [0xFF, 0xFF, 0xFF, 0xFF, 0x0F];
/// let result = decode_s33(input);
/// assert_eq!(Some((4_294_967_295, 5)), result);
///
/// let input = [0x7F, 0x00, 0x00, 0x00, 0x00];
/// let result = decode_s33(input);
/// assert_eq!(Some((-1, 1)), result);
///
/// let input = [0xFF, 0xFF, 0xFF, 0xFF, 0x7F];
/// let result = decode_s33(input);
/// assert_eq!(Some((-1, 5)), result);
///
/// let input = [0xFF, 0xFF, 0xFF, 0xFF, 0x1F];
/// let result = decode_s33(input);
/// assert_eq!(None, result);
/// ```
#[macro_export]
macro_rules! decode_sint_arr {
($func:ident, $num_ty:ty, $bits:literal) => {
/// Decodes an unsigned LEB128 number.
///
/// If there is a valid encoded value, returns the decoded value and the
/// index after the last byte read.
///
/// If the encoding is incorrect, returns `None`.
///
/// If the size in bits of the returned type is less than the size of the value in bits, returns `None`.
/// For instance, if 33 bits are being decoded, then the returned type must be at least a `u64`.
#[must_use]
pub const fn $func(
input: [u8; (($bits / 7) + if $bits % 7 == 0 { 0 } else { 1 }) as usize],
) -> Option<($num_ty, usize)> {
const BITS: u32 = $bits;
if <$num_ty>::BITS < BITS {
return None;
}
let mut result = 0;
let mut shift = 0;
let mut n;
let mut pos = 0;
loop {
n = input[pos];
let more = n & 0x80 != 0;
// For the last valid shift, perform some checks to ensure the
// encoding is valid.
//
// Notably, the one bit that MUST NOT be set is the high order bit
// indicating there are more bytes to decode.
//
// For a signed integer, depending on if the value is positive or negative,
// some bits SHOULD or SHOULD NOT be set.
//
// The expectation is that if this is a negative number, then
// there should have been a sign extension so that all the bits
// greater than the highest order bit is a 1.
//
// 32-bit
// ------
//
// The maximum shift value is 28 meaning a 32-bit number is
// encoded in a maximum of 5 bytes. If the shift value is 35 or
// greater, then, the byte's value will be shifted out beyond the
// 32-bit value.
//
// With 28 being the highest valid shift value, the highest
// order relevant bit in the final byte should be 0x08 or:
//
// 0000 1000
//
// Any higher bit is "lost" during the bitshift.
//
// Due to the encoding rules and two's complement, if the
// highest order relevant bit is set, then the number is
// negative and the `1` is extended to the higher bits like:
//
// 0111 1000
//
// Note that the highest order bit (the first bit from left to right)
// MUST BE a 0. It is the bit which indicates more bytes should
// be processed. For the maximum final byte (byte #5 for a
// 32-bit number)), it MUST be 0. There are no additional bytes
// to decode.
//
// If the highest order relevant bit is not set, then the
// integer is positive. Any of the lower bits can be set.
//
// 0000 0111
//
// So the conditions to check are:
//
// 1. The highest order bit is not set (so there are no more
// bytes to decode). If it is set, the encoding is invalid.
// This is the "more" check.
//
// 2. Determine if any sign extended negative bit is set.
// So is any bit in:
//
// 0111 1000
//
// set. If none of the bits are set, then the number is
// positive, and the encoding is valid.
// This is the "(n & mask != 0)" check.
// 3. If any sign extended negative bits are set, the number is
// negative, and ALL of the bits MUST be set for a valid negative number.
// This is the "(n < mask)"" check.
// An equivalent check would be that "(n < mask) || (n >= 0x80)"
// But the earlier check for "more" removes the need for the additional check.
//
// The check could also be "(n & mask) != mask".
//
// Another stricter condition is if the last byte has a 0 value.
// The encoding is correct but not the minimal number of bytes
// was used to express the final value.
if shift == BITS - (BITS % 7) {
#[allow(clippy::cast_sign_loss)]
let mask = ((-1i8 << ((BITS % 7).saturating_sub(1))) & 0x7f) as u8;
if more || (n & mask != 0 && n < mask) {
return None;
}
}
result |= ((n & 0x7f) as $num_ty) << shift;
shift += 7;
pos += 1;
if !more {
break;
}
}
if shift < <$num_ty>::BITS && n & 0x40 != 0 {
result |= -1 << shift;
}
Some((result, pos))
}
};
}
decode_sint_arr!(decode_s32, i32, 32);
decode_sint_arr!(decode_s64, i64, 64);
/// Sealed trait for supported signed integer types.
pub trait SInt: private::Sealed {
/// Size of the type in bits.
const BITS: u32;
}
impl SInt for i8 {
const BITS: u32 = i8::BITS;
}
impl SInt for i16 {
const BITS: u32 = i16::BITS;
}
impl SInt for i32 {
const BITS: u32 = i32::BITS;
}
impl SInt for i64 {
const BITS: u32 = i64::BITS;
}
impl SInt for i128 {
const BITS: u32 = i128::BITS;
}
/// Encodes a given value into an output slice using the fixed set of bytes.
///
/// # Examples
///
/// ```rust
/// let mut buffer = vec![254; 10];
/// let mut pos = 0;
/// let result = leb128fmt::encode_sint_slice::<_, 32>(0i32, &mut buffer, &mut pos);
/// assert_eq!(Some(1), result);
/// assert_eq!(1, pos);
/// assert_eq!(&[0x00], &buffer[..pos]);
///
/// assert_eq!(&[0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
///
/// let result = leb128fmt::encode_sint_slice::<_, 32>(i32::MAX, &mut buffer, &mut pos);
/// assert_eq!(Some(5), result);
/// assert_eq!(6, pos);
/// assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF, 0x07], &buffer[1..pos]);
///
/// assert_eq!(&[0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
///
/// // Will try to encode even if the output slice is not as big as the maximum
/// // number of bytes required to output every value for the given BITS
/// let mut buffer = vec![254; 4];
/// let mut pos = 0;
/// let result = leb128fmt::encode_sint_slice::<_, 32>(1028i32, &mut buffer, &mut pos);
/// assert_eq!(Some(2), result);
/// assert_eq!(&[0x84, 0x08, 0xFE, 0xFE], buffer.as_slice());
///
/// // Will return `None` if the output buffer is not long enough but will have partially written
/// // the value
/// let mut buffer = vec![254; 4];
/// let mut pos = 0;
/// let result = leb128fmt::encode_sint_slice::<_, 32>(i32::MAX, &mut buffer, &mut pos);
/// assert_eq!(None, result);
/// assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF], buffer.as_slice());
///
/// // Will return `None` if the given value cannot be encoded with the given number of bits.
/// let mut buffer = vec![254; 10];
/// let mut pos = 0;
/// let result = leb128fmt::encode_sint_slice::<_, 32>(i64::MAX, &mut buffer, &mut pos);
/// assert_eq!(None, result);
/// assert_eq!(&[0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
/// ```
#[allow(clippy::manual_let_else)]
pub fn encode_sint_slice<T, const BITS: u32>(
mut value: T,
output: &mut [u8],
pos: &mut usize,
) -> Option<usize>
where
T: Copy
+ PartialEq
+ core::ops::BitAnd
+ core::ops::Shr<u32>
+ core::ops::ShrAssign<u32>
+ From<i8>
+ SInt,
<T as core::ops::Shr<u32>>::Output: PartialEq<T>,
u8: TryFrom<<T as core::ops::BitAnd<T>>::Output>,
{
if BITS < T::BITS {
let v = value >> BITS;
if v != T::from(0) && v != T::from(-1) {
return None;
}
}
let mut index = *pos;
loop {
if output.len() <= index {
return None;
}
let b = match u8::try_from(value & T::from(0x7f)) {
Ok(b) => b,
Err(_) => unreachable!(),
};
value >>= 7;
if (value == T::from(0) && b & 0x40 == 0) || (value == T::from(-1) && (b & 0x40) != 0) {
output[index] = b;
index += 1;
let len = index - *pos;
*pos = index;
return Some(len);
}
output[index] = b | 0x80;
index += 1;
}
}
/// Encodes a given value into an output slice using a fixed set of bytes.
///
/// # Examples
///
/// ```rust
/// let mut buffer = vec![254; 10];
/// let mut pos = 0;
/// let result = leb128fmt::encode_fixed_sint_slice::<_, 32>(0i32, &mut buffer, &mut pos);
/// assert_eq!(Some(5), result);
/// assert_eq!(5, pos);
/// assert_eq!(&[0x80, 0x80, 0x80, 0x80, 0x00], &buffer[..pos]);
///
/// assert_eq!(&[0x80, 0x80, 0x80, 0x80, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
///
/// let result = leb128fmt::encode_fixed_sint_slice::<_, 32>(i32::MAX, &mut buffer, &mut pos);
/// assert_eq!(Some(5), result);
/// assert_eq!(10, pos);
/// assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF, 0x07], &buffer[5..pos]);
///
/// assert_eq!(&[0x80, 0x80, 0x80, 0x80, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x07], buffer.as_slice());
///
/// // Will return `None` if the output buffer is not long enough.
/// let mut buffer = vec![254; 4];
/// let mut pos = 0;
/// let result = leb128fmt::encode_fixed_sint_slice::<_, 32>(i32::MAX, &mut buffer, &mut pos);
/// assert_eq!(None, result);
/// assert_eq!(&[0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
///
/// // Will return `None` if the given value cannot be encoded with the given number of bits.
/// let mut buffer = vec![254; 10];
/// let mut pos = 0;
/// let result = leb128fmt::encode_fixed_sint_slice::<_, 32>(i64::MAX, &mut buffer, &mut pos);
/// assert_eq!(None, result);
/// assert_eq!(&[0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());
/// ```
#[allow(clippy::manual_let_else)]
pub fn encode_fixed_sint_slice<T, const BITS: u32>(
mut value: T,
output: &mut [u8],
pos: &mut usize,
) -> Option<usize>
where
T: Copy
+ PartialEq
+ core::ops::BitAnd
+ core::ops::Shr<u32>
+ core::ops::ShrAssign<u32>
+ From<i8>
+ SInt,
<T as core::ops::Shr<u32>>::Output: PartialEq<T>,
u8: TryFrom<<T as core::ops::BitAnd>::Output>,
{
if BITS < T::BITS {
let v = value >> BITS;
if v != T::from(0) && v != T::from(-1) {
return None;
}
}
if output[*pos..].len() < max_len::<BITS>() {
return None;
}
let mut index = *pos;
let mut extend_negative = false;
loop {
let b = match u8::try_from(value & T::from(0x7f)) {
Ok(b) => b,
Err(_) => unreachable!(),
};
value >>= 7;
output[index] = b | 0x80;
index += 1;
if value == T::from(0) && b & 0x40 == 0 {
break;
}
if value == T::from(-1) && (b & 0x40) != 0 {
extend_negative = true;
break;
}
}
loop {
if index == *pos + max_len::<BITS>() {
output[index - 1] &= 0x7F;
let len = index - *pos;
*pos = index;
return Some(len);
}
if extend_negative {
output[index] = 0xFF;
} else {
output[index] = 0x80;
}
index += 1;
}
}
/// Decodes an unsigned integer from a slice of bytes and starting at a given position.
///
/// # Errors
///
/// Returns an error if the value is not properly encoded or if more bytes are
/// needed to decode the value.
///
/// # Panics
///
/// Panics if the size in bits of the returned type is less than the size of the value in bits.
/// For instance, if 33 bits are being decoded, then the returned type must be at least a `u64`.
///
/// ```rust
/// let input = [0x42, 0x8F, 0xFF, 0x7F, 0xFF];
/// let mut pos = 1;
/// let result = leb128fmt::decode_sint_slice::<i32, 32>(&input, &mut pos);
/// assert_eq!(result, Ok(-113));
/// assert_eq!(pos, 4);
/// ```
pub fn decode_sint_slice<T, const BITS: u32>(input: &[u8], pos: &mut usize) -> Result<T, Error>
where
T: core::ops::Shl<u32, Output = T> + core::ops::BitOrAssign + From<i8> + From<u8> + SInt,
{
assert!(BITS <= T::BITS);
let mut result = T::from(0i8);
let mut shift = 0;
let mut n;
let mut idx = *pos;
loop {
if input.len() <= idx {
return Err(Error(InnerError::NeedMoreBytes));
}
n = input[idx];
let more = n & 0x80 != 0;
// For the last valid shift, perform some checks to ensure the
// encoding is valid.
//
// Notably, the one bit that MUST NOT be set is the high order bit
// indicating there are more bytes to decode.
//
// For a signed integer, depending on if the value is positive or negative,
// some bits SHOULD or SHOULD NOT be set.
//
// The expectation is that if this is a negative number, then
// there should have been a sign extension so that all the bits
// greater than the highest order bit is a 1.
//
// 32-bit
// ------
//
// The maximum shift value is 28 meaning a 32-bit number is
// encoded in a maximum of 5 bytes. If the shift value is 35 or
// greater, then, the byte's value will be shifted out beyond the
// 32-bit value.
//
// With 28 being the highest valid shift value, the highest
// order relevant bit in the final byte should be 0x08 or:
//
// 0000 1000
//
// Any higher bit is "lost" during the bitshift.
//
// Due to the encoding rules and two's complement, if the
// highest order relevant bit is set, then the number is
// negative and the `1` is extended to the higher bits like:
//
// 0111 1000
//
// Note that the highest order bit (the first bit from left to right)
// MUST BE a 0. It is the bit which indicates more bytes should
// be processed. For the maximum final byte (byte #5 for a
// 32-bit number)), it MUST be 0. There are no additional bytes
// to decode.
//
// If the highest order relevant bit is not set, then the
// integer is positive. Any of the lower bits can be set.
//
// 0000 0111
//
// So the conditions to check are:
//
// 1. The highest order bit is not set (so there are no more
// bytes to decode). If it is set, the encoding is invalid.
// This is the "more" check.
//
// 2. Determine if any sign extended negative bit is set.
// So is any bit in:
//
// 0111 1000
//
// set. If none of the bits are set, then the number is
// positive, and the encoding is valid.
// This is the "(n & mask != 0)" check.
// 3. If any sign extended negative bits are set, the number is
// negative, and ALL of the bits MUST be set for a valid negative number.
// This is the "(n < mask)"" check.
// An equivalent check would be that "(n < mask) || (n >= 0x80)"
// But the earlier check for "more" removes the need for the additional check.
//
// The check could also be "(n & mask) != mask".
//
// Another stricter condition is if the last byte has a 0 value.
// The encoding is correct but not the minimal number of bytes
// was used to express the final value.
if shift == BITS - (BITS % 7) {
#[allow(clippy::cast_sign_loss)]
let mask = ((-1i8 << ((BITS % 7).saturating_sub(1))) & 0x7f) as u8;
if more || (n & mask != 0 && n < mask) {
return Err(Error(InnerError::InvalidEncoding));
}
}
result |= T::from(n & 0x7f) << shift;
shift += 7;
idx += 1;
if !more {
break;
}
}
if shift < T::BITS && n & 0x40 != 0 {
result |= T::from(-1i8) << shift;
}
*pos = idx;
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encode_u8() {
let mut buffer = [0; 4];
let mut pos = 1;
let written = encode_fixed_uint_slice::<_, 8>(u8::MAX, &mut buffer, &mut pos);
assert_eq!(3, pos);
assert_eq!([0x00, 0xFF, 0x01, 0x00], buffer);
assert_eq!(Some(2), written);
}
#[test]
fn test_encode_u32() {
let mut buffer = [0; 6];
let mut pos = 1;
let written = encode_fixed_uint_slice::<_, 32>(u32::MAX, &mut buffer, &mut pos);
assert_eq!(6, pos);
assert_eq!([0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F], buffer);
assert_eq!(Some(5), written);
}
#[test]
fn test_encode_u64_as_33_bits_2() {
let mut buffer = [0; 6];
let mut pos = 1;
let written = encode_fixed_uint_slice::<_, 33>(2u64.pow(33) - 1, &mut buffer, &mut pos);
let mut pos = 1;
let value = decode_uint_slice::<u64, 33>(&buffer, &mut pos).unwrap();
assert_eq!(8_589_934_592 - 1, value);
assert_eq!(6, pos);
assert_eq!([0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F], buffer);
assert_eq!(Some(5), written);
}
#[test]
fn test_encode_u64_as_33_bits_with_too_large_value() {
let mut buffer = [0; 6];
let mut pos = 1;
let written = encode_fixed_uint_slice::<_, 33>(2u64.pow(34) - 1, &mut buffer, &mut pos);
assert_eq!(1, pos);
assert_eq!([0x00, 0x00, 0x00, 0x00, 0x00, 0x00], buffer);
assert_eq!(None, written);
}
#[test]
fn test_encode_u64() {
let mut buffer = [0; 20];
let mut pos = 1;
let written = encode_fixed_uint_slice::<_, 64>(u64::MAX, &mut buffer, &mut pos);
assert_eq!(11, pos);
assert_eq!(Some(10), written);
}
#[test]
fn test_decode_u32() {
let input = [0xff, 0xff, 0xff, 0xff, 0x0f];
let result = decode_u32(input);
assert_eq!(result, Some((u32::MAX, 5)));
let input = [0x00, 0x00, 0x00, 0x00, 0x00];
let result = decode_u32(input);
assert_eq!(result, Some((u32::MIN, 1)));
// Valid but in-efficient way to encode 0.
let input = [0x80, 0x80, 0x80, 0x80, 0x00];
let result = decode_u32(input);
assert_eq!(result, Some((u32::MIN, 5)));
}
#[test]
fn test_decode_u32_errors() {
// Maximum of 5 bytes encoding, the 0x80 bit must not be set.
let input = [0xff, 0xff, 0xff, 0xff, 0x8f];
let result = decode_u32(input);
assert_eq!(result, None);
// Parts of 0x1f (0x10) will be shifted out of the final value and lost.
// This may too strict of a check since it could be ok.
let input = [0xff, 0xff, 0xff, 0xff, 0x1f];
let result = decode_u32(input);
assert_eq!(result, None);
}
#[test]
fn test_decode_u64() {
let input = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01];
let result = decode_u64(input);
assert_eq!(result, Some((u64::MAX, 10)));
let input = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let result = decode_u64(input);
assert_eq!(result, Some((u64::MIN, 1)));
// Valid but in-efficient way to encode 0.
let input = [0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00];
let result = decode_u64(input);
assert_eq!(result, Some((u64::MIN, 10)));
}
#[test]
fn test_decode_u64_errors() {
// Maximum of 10 bytes encoding, the 0x80 bit must not be set in the final byte.
let input = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81];
let result = decode_u64(input);
assert_eq!(result, None);
// 0x02 will be shifted out of the final value and lost.
// This may too strict of a check since it could be ok.
let input = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02];
let result = decode_u64(input);
assert_eq!(result, None);
}
#[test]
fn test_decode_s32() {
let input = [0xff, 0xff, 0xff, 0xff, 0x07];
let result = decode_s32(input);
assert_eq!(result, Some((i32::MAX, 5)));
let input = [0x80, 0x80, 0x80, 0x80, 0x78];
let result = decode_s32(input);
assert_eq!(result, Some((i32::MIN, 5)));
let input = [0x00, 0x00, 0x00, 0x00, 0x00];
let result = decode_s32(input);
assert_eq!(result, Some((0, 1)));
// Valid but in-efficient way to encode 0.
let input = [0x80, 0x80, 0x80, 0x80, 0x00];
let result = decode_s32(input);
assert_eq!(result, Some((0, 5)));
let input = [0x40, 0x00, 0x00, 0x00, 0x00];
let result = decode_s32(input);
assert_eq!(result, Some((-64, 1)));
// Valid but in-efficient way to encode -64.
let input = [0xc0, 0x7f, 0x00, 0x00, 0x00];
let result = decode_s32(input);
assert_eq!(result, Some((-64, 2)));
}
#[test]
fn test_decode_s32_errors() {
// Maximum of 5 bytes encoding, the 0x80 bit must not be set in the final byte.
let input = [0x80, 0x80, 0x80, 0x80, 0x80];
let result = decode_s32(input);
assert_eq!(result, None);
// If the highest valid bit is set, it should be sign extended. (final byte should be 0x78)
let input = [0x80, 0x80, 0x80, 0x80, 0x08];
let result = decode_s32(input);
assert_eq!(result, None);
// If the highest valid bit is set, it should be sign extended. (final byte should be 0x78)
let input = [0x80, 0x80, 0x80, 0x80, 0x38];
let result = decode_s32(input);
assert_eq!(result, None);
}
#[test]
fn test_decode_s33() {
decode_sint_arr!(decode_s33, i64, 33);
let input = [0xff, 0xff, 0xff, 0xff, 0x0f];
let result = decode_s33(input);
assert_eq!(result, Some((i64::from(u32::MAX), 5)));
let input = [0x80, 0x80, 0x80, 0x80, 0x70];
let result = decode_s33(input);
assert_eq!(result, Some((i64::from(i32::MIN) * 2, 5)));
let input = [0x00, 0x00, 0x00, 0x00, 0x00];
let result = decode_s33(input);
assert_eq!(result, Some((0, 1)));
// Valid but in-efficient way to encode 0.
let input = [0x80, 0x80, 0x80, 0x80, 0x00];
let result = decode_s33(input);
assert_eq!(result, Some((0, 5)));
let input = [0x40, 0x00, 0x00, 0x00, 0x00];
let result = decode_s33(input);
assert_eq!(result, Some((-64, 1)));
// Valid but in-efficient way to encode -64.
let input = [0xc0, 0x7f, 0x00, 0x00, 0x00];
let result = decode_s33(input);
assert_eq!(result, Some((-64, 2)));
}
#[test]
fn test_decode_s33_errors() {
decode_sint_arr!(decode_s33, i64, 33);
// Maximum of 5 bytes encoding, the 0x80 bit must not be set in the final byte.
let input = [0x80, 0x80, 0x80, 0x80, 0x80];
let result = decode_s33(input);
assert_eq!(result, None);
// If the highest valid bit is set, it should be sign extended. (final byte should be 0x70)
let input = [0x80, 0x80, 0x80, 0x80, 0x10];
let result = decode_s33(input);
assert_eq!(result, None);
// If the highest valid bit is set, it should be sign extended. (final byte should be 0x70)
let input = [0x80, 0x80, 0x80, 0x80, 0x30];
let result = decode_s33(input);
assert_eq!(result, None);
}
#[test]
fn test_decode_s64() {
let input = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00];
let result = decode_s64(input);
assert_eq!(result, Some((i64::MAX, 10)));
let input = [0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f];
let result = decode_s64(input);
assert_eq!(result, Some((i64::MIN, 10)));
let input = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let result = decode_s64(input);
assert_eq!(result, Some((0, 1)));
// Valid but in-efficient way to encode 0.
let input = [0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00];
let result = decode_s64(input);
assert_eq!(result, Some((0, 10)));
}
#[test]
fn test_decode_s64_errors() {
// Maximum of 10 bytes encoding, the 0x80 bit must not be set in the final byte.
let input = [0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80];
let result = decode_s64(input);
assert_eq!(result, None);
// If the highest valid bit is set, it should be sign extended. (final byte should be 0x78)
let input = [0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x08];
let result = decode_s64(input);
assert_eq!(result, None);
// If the highest valid bit is set, it should be sign extended. (final byte should be 0x78)
let input = [0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x28];
let result = decode_s64(input);
assert_eq!(result, None);
}
}