aboutsummaryrefslogtreecommitdiffstats
path: root/staging_vespalib/src/tests/bits/bits_test.cpp
blob: f7b3ef1bf840257e778995e0afacfbf0304cf3e3 (plain) (blame)
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
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/log/log.h>
LOG_SETUP("bits_test");
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/bits.h>
#include <boost/crc.hpp>

using namespace vespalib;

class Test : public TestApp
{
public:
    int Main() override;
    template <typename T>
    void testFixed(const T * v, size_t sz);
    void testBuffer();
};

int
Test::Main()
{
    TEST_INIT("bits_test");
    uint8_t u8[5] = { 0, 1, 127, 135, 255 };
    testFixed(u8, sizeof(u8)/sizeof(u8[0]));
    uint16_t u16[5] = { 0, 1, 127, 135, 255 };
    testFixed(u16, sizeof(u16)/sizeof(u16[0]));
    uint32_t u32[5] = { 0, 1, 127, 135, 255 };
    testFixed(u32, sizeof(u32)/sizeof(u32[0]));
    uint64_t u64[5] = { 0, 1, 127, 135, 255 };
    testFixed(u64, sizeof(u64)/sizeof(u64[0]));
    testBuffer();
    TEST_DONE();
}

template <typename T>
void Test::testFixed(const T * v, size_t sz)
{
    EXPECT_EQUAL(0u, Bits::reverse(static_cast<T>(0)));
    EXPECT_EQUAL(1ul << (sizeof(T)*8 - 1), Bits::reverse(static_cast<T>(1)));
    EXPECT_EQUAL(static_cast<T>(-1), Bits::reverse(static_cast<T>(-1)));
    for (size_t i(0); i < sz; i++) {
        EXPECT_EQUAL(Bits::reverse(v[i]), boost::detail::reflector<sizeof(T)*8>::reflect(v[i]));
        EXPECT_EQUAL(Bits::reverse(Bits::reverse(v[i])), v[i]);
    }
}

void Test::testBuffer()
{
    uint64_t a(0x0102040810204080ul);
    uint64_t b(a);
    Bits::reverse(&a, sizeof(a));
    EXPECT_EQUAL(a, Bits::reverse(b));
    Bits::reverse(&a, sizeof(a));
    EXPECT_EQUAL(a, b);
}

TEST_APPHOOK(Test)