blob: 19b9c9c3dea34202336c1f14525d0e45f7f94ea8 [file] [log] [blame]
Wyatt Hepler92ccb662020-01-21 18:28:41 -08001// Copyright 2020 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#include "pw_checksum/ccitt_crc16.h"
16
17#include <string_view>
18
19#include "gtest/gtest.h"
20
21namespace pw::checksum {
22namespace {
23
24// The expected CRC16 values were calculated using
25//
26// http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
27//
28// with polynomial 0x1021, initial value 0xFFFF.
29constexpr uint8_t kBytes[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
30constexpr uint16_t kBufferCrc = 0x3B0A;
31
32constexpr std::string_view kString =
33 "In the beginning the Universe was created. This has made a lot of "
34 "people very angry and been widely regarded as a bad move.";
35constexpr uint16_t kStringCrc = 0xC184;
36
37TEST(Crc16, Empty) {
38 EXPECT_EQ(CcittCrc16(span<std::byte>()), kCcittCrc16DefaultInitialValue);
39}
40
41TEST(Crc16, ByteByByte) {
42 uint16_t crc = kCcittCrc16DefaultInitialValue;
43 for (size_t i = 0; i < sizeof(kBytes); i++) {
44 crc = CcittCrc16(std::byte{kBytes[i]}, crc);
45 }
46 EXPECT_EQ(crc, kBufferCrc);
47}
48
49TEST(Crc16, Buffer) {
50 EXPECT_EQ(CcittCrc16(as_bytes(span(kBytes))), kBufferCrc);
51}
52
53TEST(Crc16, String) {
54 EXPECT_EQ(CcittCrc16(as_bytes(span(kString))), kStringCrc);
55}
56
57extern "C" uint16_t CallChecksumCcittCrc16(const void* data, size_t size_bytes);
58
59TEST(Crc16FromC, Buffer) {
60 EXPECT_EQ(CallChecksumCcittCrc16(kBytes, sizeof(kBytes)), kBufferCrc);
61}
62
63TEST(Crc16FromC, String) {
64 EXPECT_EQ(CallChecksumCcittCrc16(kString.data(), kString.size()), kStringCrc);
65}
66
67} // namespace
68} // namespace pw::checksum