libcruft-util/test/ascii.cpp

73 lines
2.5 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2017 Danny Robson <danny@nerdcruft.net>
*/
#include <cruft/util/tap.hpp>
#include <cruft/util/ascii.hpp>
int
main (int, char**)
{
static constexpr bool T = true;
static constexpr bool F = false;
static constexpr struct {
char character;
bool is_digit;
bool is_hex;
bool is_upper;
bool is_lower;
bool is_space;
int integer;
unsigned hexadecimal;
const char *msg;
} TESTS[] = {
{ '/', F, F, F, F, F, 0, 0, "/" }, // one below '0'
{ '0', T, T, F, F, F, 0, 0, "0" },
{ '9', T, T, F, F, F, 9, 9, "9" },
{ ':', F, F, F, F, F, 0, 0, ":" }, // one above '9'
{ '`', F, F, F, F, F, 0, 0, "`" }, // one below 'a'
{ 'a', F, T, F, T, F, 0, 10, "a" },
{ 'f', F, T, F, T, F, 0, 15, "f" },
{ 'g', F, F, F, T, F, 0, 0, "g" },
{ 'A', F, T, T, F, F, 0, 10, "A" },
{ 'F', F, T, T, F, F, 0, 15, "F" },
{ 'G', F, F, T, F, F, 0, 0, "G" },
{ ' ', F, F, F, F, T, 0, 0, "space" },
{ '\t', F, F, F, F, T, 0, 0, "tab" },
{ '\n', F, F, F, F, T, 0, 0, "newline" },
};
return cruft::TAP::logger::run ([] (auto &tap) {
#define TRY_BOOL(X) [&] () -> bool { try { return X; } catch (...) { return false; }; } ()
for (auto &t: TESTS) {
bool is_digit = TRY_BOOL(cruft::ascii::is_digit (t.character)) == t.is_digit;
bool is_hex = TRY_BOOL(cruft::ascii::is_hex (t.character)) == t.is_hex;
bool is_upper = TRY_BOOL(cruft::ascii::is_upper (t.character)) == t.is_upper;
bool is_lower = TRY_BOOL(cruft::ascii::is_lower (t.character)) == t.is_lower;
bool is_space = TRY_BOOL(cruft::ascii::is_space (t.character)) == t.is_space;
bool integer = !t.is_digit || cruft::ascii::to_integer (t.character) == t.integer;
bool hexadecimal = !t.is_hex || cruft::ascii::from_hex (t.character) == t.hexadecimal;
tap.expect (
is_digit && is_hex && is_upper && is_lower && is_space && integer && hexadecimal,
"{:s}", t.msg
);
}
tap.expect_eq ("6a"_hex2u08, std::vector<uint8_t>({0x6a}), "hex2u8, 1 byte");
tap.expect_eq ("a6"_hex2array, std::array<uint8_t,1> ({0xa6}), "hex2array, 1 byte");
});
}