Skip to content

Commit

Permalink
Add test for fletcher32 (values taken from Wikipedia) and fix it.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarod42 committed Oct 11, 2023
1 parent c1d1e0b commit 6d3505a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
15 changes: 6 additions & 9 deletions src/stratagus/util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -178,28 +178,25 @@ long isqrt(long num)
// ascii chars to hopefully avoid issues with filesystem encodings
uint32_t fletcher32(const std::string &content)
{
std::vector<uint16_t> alphas(content.size() / 2);
size_t shorts = 0;
std::vector<uint16_t> alphas;
size_t consideredChars = 0;
for (size_t i = 0; i < content.size(); i++) {
uint16_t c = content[i];
if (c >= 'A' && c <= 'z') {
consideredChars++;
if ((consideredChars % 2) == 0) {
alphas[shorts] = c << 8;
if ((consideredChars++ % 2) == 0) {
alphas.push_back(c);
} else {
alphas[shorts] = alphas[shorts] || c;
shorts++;
alphas.back() |= c << 8;
}
}
}

const uint16_t *data = alphas.data();
uint32_t sum1 = 0xffff, sum2 = 0xffff;
size_t tlen;

auto shorts = alphas.size();
while (shorts) {
tlen = ((shorts >= 359) ? 359 : shorts);
size_t tlen = ((shorts >= 359) ? 359 : shorts);
shorts -= tlen;
do {
sum2 += sum1 += *data++;
Expand Down
7 changes: 7 additions & 0 deletions tests/stratagus/test_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ TEST_CASE("strnlen")
CHECK(5u == strnlen("hello", 10));
}

TEST_CASE("fletcher32")
{
CHECK(4031760169 == fletcher32("abcde")); // 0xF04FC729
CHECK(1448095018 == fletcher32("abcdef")); // 0x56502D2A
CHECK(3957429649 == fletcher32("abcdefgh")); // 0xEBE19591
}

// TODO: int getopt(int argc, char *const argv[], const char *optstring);
// TODO: int GetClipboard(std::string &str);
// TODO: int UTF8GetNext(const std::string &text, int curpos);
Expand Down

0 comments on commit 6d3505a

Please sign in to comment.