• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // 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/crc16_ccitt.h"
16 
17 #include <string_view>
18 
19 #include "gtest/gtest.h"
20 
21 namespace pw::checksum {
22 namespace {
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.
29 constexpr uint8_t kBytes[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
30 constexpr uint16_t kBufferCrc = 0x3B0A;
31 
32 constexpr 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.";
35 constexpr uint16_t kStringCrc = 0xC184;
36 
TEST(Crc16,Empty)37 TEST(Crc16, Empty) {
38   EXPECT_EQ(Crc16Ccitt::Calculate(span<std::byte>()),
39             Crc16Ccitt::kInitialValue);
40 }
41 
TEST(Crc16,ByteByByte)42 TEST(Crc16, ByteByByte) {
43   uint16_t crc = Crc16Ccitt::kInitialValue;
44   for (size_t i = 0; i < sizeof(kBytes); i++) {
45     crc = Crc16Ccitt::Calculate(std::byte{kBytes[i]}, crc);
46   }
47   EXPECT_EQ(crc, kBufferCrc);
48 }
49 
TEST(Crc16,Buffer)50 TEST(Crc16, Buffer) {
51   EXPECT_EQ(Crc16Ccitt::Calculate(as_bytes(span(kBytes))), kBufferCrc);
52 }
53 
TEST(Crc16,String)54 TEST(Crc16, String) {
55   EXPECT_EQ(Crc16Ccitt::Calculate(as_bytes(span(kString))), kStringCrc);
56 }
57 
TEST(Crc16Class,Buffer)58 TEST(Crc16Class, Buffer) {
59   Crc16Ccitt crc16;
60   crc16.Update(as_bytes(span(kBytes)));
61   EXPECT_EQ(crc16.value(), kBufferCrc);
62 }
63 
TEST(Crc16Class,String)64 TEST(Crc16Class, String) {
65   Crc16Ccitt crc16;
66   crc16.Update(as_bytes(span(kString)));
67   EXPECT_EQ(crc16.value(), kStringCrc);
68 }
69 
70 extern "C" uint16_t CallChecksumCrc16Ccitt(const void* data, size_t size_bytes);
71 
TEST(Crc16FromC,Buffer)72 TEST(Crc16FromC, Buffer) {
73   EXPECT_EQ(CallChecksumCrc16Ccitt(kBytes, sizeof(kBytes)), kBufferCrc);
74 }
75 
TEST(Crc16FromC,String)76 TEST(Crc16FromC, String) {
77   EXPECT_EQ(CallChecksumCrc16Ccitt(kString.data(), kString.size()), kStringCrc);
78 }
79 
80 }  // namespace
81 }  // namespace pw::checksum
82