Repository navigation
Expand file tree
/
Copy pathBase64Test.cpp
More file actions
96 lines (80 loc) · 2.53 KB
/
Copy pathBase64Test.cpp
File metadata and controls
96 lines (80 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <cstdio>
#include <optional>
#include <string>
#include "ns/Base64.h"
namespace {
int failures = 0;
void Check(bool ok, const char* what, const std::string& input) {
if (!ok) {
failures++;
std::fprintf(stderr, "FAIL %s: \"%s\"\n", what, input.c_str());
}
}
std::string Encode(const std::string& in) {
return nativescript::common::base64::Encode(
reinterpret_cast<const uint8_t*>(in.data()), in.size());
}
std::optional<std::string> Decode(const std::string& in) {
auto out = nativescript::common::base64::ForgivingDecode(
reinterpret_cast<const uint8_t*>(in.data()), in.size());
if (!out) {
return std::nullopt;
}
return std::string(out->begin(), out->end());
}
void ExpectEncode(const std::string& in, const std::string& expected) {
Check(Encode(in) == expected, "encode", in);
}
void ExpectDecode(const std::string& in, const std::string& expected) {
auto out = Decode(in);
Check(out.has_value() && *out == expected, "decode", in);
}
void ExpectInvalid(const std::string& in) {
Check(!Decode(in).has_value(), "decode rejects", in);
}
} // namespace
int main() {
// RFC 4648 section 10.
ExpectEncode("", "");
ExpectEncode("f", "Zg==");
ExpectEncode("fo", "Zm8=");
ExpectEncode("foo", "Zm9v");
ExpectEncode("foob", "Zm9vYg==");
ExpectEncode("fooba", "Zm9vYmE=");
ExpectEncode("foobar", "Zm9vYmFy");
ExpectEncode(std::string("\xff\xfe\x00", 3), "//4A");
ExpectDecode("", "");
ExpectDecode("Zg==", "f");
ExpectDecode("Zm8=", "fo");
ExpectDecode("Zm9vYmFy", "foobar");
ExpectDecode("//4A", std::string("\xff\xfe\x00", 3));
// Forgiving: padding is optional, ASCII whitespace anywhere is dropped.
ExpectDecode("Zg", "f");
ExpectDecode("Zm8", "fo");
ExpectDecode(" Zm9v\tYm\nFy\f\r", "foobar");
ExpectDecode("Zg= =", "f");
// Leftover bits that do not complete a byte are discarded.
ExpectDecode("Zh==", "f");
ExpectInvalid("Z");
ExpectInvalid("Zg=");
ExpectInvalid("Zg===");
ExpectInvalid("=Zg=");
ExpectInvalid("Zm9v-_");
ExpectInvalid("Zm\v9v");
ExpectInvalid("Zm9vYg=a");
for (int length = 0; length < 64; length++) {
std::string bytes;
for (int i = 0; i < length; i++) {
bytes.push_back(static_cast<char>((i * 37 + length) & 0xFF));
}
auto roundTrip = Decode(Encode(bytes));
Check(roundTrip.has_value() && *roundTrip == bytes, "round trip",
std::to_string(length));
}
if (failures != 0) {
std::fprintf(stderr, "%d failure(s)\n", failures);
return 1;
}
std::printf("all base64 checks passed\n");
return 0;
}