* Convert a hex-string to a byte-array, while validating it was actually hex. * * @param hex The hex-string to convert. * @param bytes The byte-array to write the result to. * * @note The length of the hex-string has to be exactly twice that of the length * of the byte-array, otherwise conversion will fail. * * @return True iff the hex-string was valid and the conversion succeeded. */
| 568 | * @return True iff the hex-string was valid and the conversion succeeded. |
| 569 | */ |
| 570 | bool ConvertHexToBytes(std::string_view hex, std::span<uint8_t> bytes) |
| 571 | { |
| 572 | if (bytes.size() != hex.size() / 2) { |
| 573 | return false; |
| 574 | } |
| 575 | |
| 576 | /* Hex-string lengths are always divisible by 2. */ |
| 577 | if (hex.size() % 2 != 0) { |
| 578 | return false; |
| 579 | } |
| 580 | |
| 581 | for (size_t i = 0; i < hex.size() / 2; i++) { |
| 582 | auto hi = ConvertHexNibbleToByte(hex[i * 2]); |
| 583 | auto lo = ConvertHexNibbleToByte(hex[i * 2 + 1]); |
| 584 | |
| 585 | if (hi < 0 || lo < 0) { |
| 586 | return false; |
| 587 | } |
| 588 | |
| 589 | bytes[i] = (hi << 4) | lo; |
| 590 | } |
| 591 | |
| 592 | return true; |
| 593 | } |
| 594 | |
| 595 | #ifdef WITH_UNISCRIBE |
| 596 |
no test coverage detected