Add EncodeHex and DecodeHex functions to test_util.h.
We have enough copies of these.
Change-Id: I1ff8915b8ca781dc070e802e634d1dc12832e272
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/39304
Commit-Queue: Adam Langley <agl@google.com>
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/test/test_util.cc b/crypto/test/test_util.cc
index 29be702..7f95413 100644
--- a/crypto/test/test_util.cc
+++ b/crypto/test/test_util.cc
@@ -35,10 +35,51 @@
}
// Print a byte slice as hex.
- static const char hex[] = "0123456789abcdef";
- for (uint8_t b : in.span_) {
- os << hex[b >> 4];
- os << hex[b & 0xf];
- }
+ os << EncodeHex(in.span_);
return os;
}
+
+static bool FromHexDigit(uint8_t *out, char c) {
+ if ('0' <= c && c <= '9') {
+ *out = c - '0';
+ return true;
+ }
+ if ('a' <= c && c <= 'f') {
+ *out = c - 'a' + 10;
+ return true;
+ }
+ if ('A' <= c && c <= 'F') {
+ *out = c - 'A' + 10;
+ return true;
+ }
+ return false;
+}
+
+bool DecodeHex(std::vector<uint8_t> *out, const std::string &in) {
+ out->clear();
+ if (in.size() % 2 != 0) {
+ return false;
+ }
+ out->reserve(in.size() / 2);
+ for (size_t i = 0; i < in.size(); i += 2) {
+ uint8_t hi, lo;
+ if (!FromHexDigit(&hi, in[i]) ||
+ !FromHexDigit(&lo, in[i + 1])) {
+ return false;
+ }
+ out->push_back((hi << 4) | lo);
+ }
+ return true;
+}
+
+std::string EncodeHex(bssl::Span<const uint8_t> in) {
+ static const char kHexDigits[] = "0123456789abcdef";
+ std::string ret;
+ ret.reserve(in.size() * 2);
+ for (uint8_t b : in) {
+ ret += kHexDigits[b >> 4];
+ ret += kHexDigits[b & 0xf];
+ }
+ return ret;
+}
+