encode/number: add number decoding for base36

This commit is contained in:
Danny Robson 2018-12-16 16:24:45 +11:00
parent 5fedbdbdfe
commit 8047bf0f83
3 changed files with 64 additions and 0 deletions

View File

@ -247,6 +247,7 @@ list (
cpuid_x86.hpp cpuid_x86.hpp
debug.cpp debug.cpp
debug.hpp debug.hpp
encode/number.hpp
encode/base.cpp encode/base.cpp
encode/base.hpp encode/base.hpp
endian.cpp endian.cpp
@ -531,6 +532,7 @@ if (TESTS)
colour colour
comparator comparator
coord coord
encode/number
encode/base encode/base
endian endian
exe exe

34
encode/number.hpp Normal file
View File

@ -0,0 +1,34 @@
/*
* 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 2018 Danny Robson <danny@nerdcruft.net>
*/
#pragma once
#include "../view.hpp"
///////////////////////////////////////////////////////////////////////////////
namespace cruft::encode {
template <typename ValueT>
ValueT
decode36 (cruft::view<char const*> &src)
{
ValueT accum = 0;
for (auto const i: src) {
accum *= 36;
switch (i) {
case '0'...'9': accum += i - '0'; continue;
case 'a'...'z': accum += i - 'a' + 10; continue;
case 'A'...'Z': accum += i - 'A' + 10; continue;
default:
throw std::invalid_argument ("invalid character");
}
}
return accum;
}
}

28
test/encode/number.cpp Normal file
View File

@ -0,0 +1,28 @@
#include "encode/number.hpp"
#include "tap.hpp"
int main ()
{
static struct {
char const *str;
unsigned value;
} const TESTS[] = {
{ "0", 0 },
{ "a", 10 },
{ "A", 10 },
{ "10", 36 },
{ "11", 37 },
{ "bfi0", 533304 },
{ "15bfi0", 69397560 },
};
cruft::TAP::logger tap;
for (auto const &t: TESTS) {
cruft::view src (t.str);
tap.expect_eq (cruft::encode::decode36<unsigned> (src), t.value, "base36 decode '%!'", t.str);
}
return tap.status ();
}