Shaka Packager SDK
Loading...
Searching...
No Matches
hex_parser.cc
1// Copyright 2022 Google LLC. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file or at
5// https://developers.google.com/open-source/licenses/bsd
6
7#include <packager/utils/hex_parser.h>
8
9#include <absl/strings/escaping.h>
10#include <absl/types/span.h>
11
12namespace shaka {
13
14void HexStringToBytes(const std::string& hex, std::vector<uint8_t>* bytes) {
15 std::string raw = absl::HexStringToBytes(hex);
16
17 absl::string_view str_view(raw);
18 absl::Span<const uint8_t> span(
19 reinterpret_cast<const uint8_t*>(str_view.data()), str_view.size());
20 *bytes = std::vector<uint8_t>(span.begin(), span.end());
21}
22
23bool ValidHexStringToBytes(const std::string& hex,
24 std::vector<uint8_t>* bytes) {
25 std::string raw;
26 if (!ValidHexStringToBytes(hex, &raw))
27 return false;
28
29 absl::string_view str_view(raw);
30 absl::Span<const uint8_t> span(
31 reinterpret_cast<const uint8_t*>(str_view.data()), str_view.size());
32 *bytes = std::vector<uint8_t>(span.begin(), span.end());
33 return true;
34}
35
36bool ValidHexStringToBytes(const std::string& hex, std::string* bytes) {
37 // absl::HexStringToBytes will not validate the string! Any invalid byte
38 // sequence will be converted into NUL characters silently. So we do our own
39 // validation here.
40 for (char c : hex) {
41 c = static_cast<char>(std::tolower(c));
42 if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) {
43 // valid
44 } else {
45 return false;
46 }
47 }
48
49 *bytes = absl::HexStringToBytes(hex);
50 return true;
51}
52
53} // namespace shaka
All the methods that are virtual are virtual for mocking.