blob: 87b8430ec8b4bb3bfe7c94ec914403465552db35 [file] [log] [blame]
Zihan Chen0a7db3e2020-06-23 16:36:06 -07001// 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#include "pw_checksum/crc32.h"
15
16#include <span>
17#include <string_view>
18
19#include "gtest/gtest.h"
20
21namespace pw::checksum {
22namespace {
23
24// The expected CRC32 values were calculated using
25//
26// http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
27//
28// with polynomial 0x4C11DB7, initial value 0xFFFFFFFF.
29
30constexpr uint8_t kBytes[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
31constexpr uint8_t kBytesPart0[] = {1, 2, 3, 4, 5};
32constexpr uint8_t kBytesPart1[] = {6, 7, 8, 9};
33constexpr uint32_t kBufferCrc = 0x40EFAB9E;
34
35constexpr std::string_view kString =
36 "In the beginning the Universe was created. This has made a lot of "
37 "people very angry and been widely regarded as a bad move.";
38constexpr uint32_t kStringCrc = 0x9EC87F88;
39
40TEST(Crc32, Empty) {
41 EXPECT_EQ(Crc32(std::span<std::byte>()), ~kCrc32InitialValue);
42}
43
44TEST(Crc32, ByteByByte) {
45 uint32_t crc;
46 crc = Crc32(std::byte{kBytes[0]});
47 for (size_t i = 1; i < sizeof(kBytes); i++) {
48 crc = Crc32(std::byte{kBytes[i]}, crc);
49 }
50 EXPECT_EQ(crc, kBufferCrc);
51}
52
53TEST(Crc32, Buffer) {
54 EXPECT_EQ(Crc32(as_bytes(std::span(kBytes))), kBufferCrc);
55}
56
57TEST(Crc32, BufferAppend) {
58 uint32_t crc = Crc32(as_bytes(std::span(kBytesPart0)));
59 EXPECT_EQ(Crc32(as_bytes(std::span(kBytesPart1)), crc), kBufferCrc);
60}
61
62TEST(Crc32, String) {
63 EXPECT_EQ(Crc32(as_bytes(std::span(kString))), kStringCrc);
64}
65
66extern "C" uint32_t CallChecksumCrc32(const void* data, size_t size_bytes);
67extern "C" uint32_t CallChecksumCrc32Append(const void* data,
68 size_t size_bytes);
69
70TEST(Crc32FromC, Buffer) {
71 EXPECT_EQ(CallChecksumCrc32(kBytes, sizeof(kBytes)), kBufferCrc);
72}
73
74TEST(Crc32FromC, String) {
75 EXPECT_EQ(CallChecksumCrc32(kString.data(), kString.size()), kStringCrc);
76}
77
78TEST(Crc32AppendFromC, Buffer) {
79 EXPECT_EQ(CallChecksumCrc32(kBytes, sizeof(kBytes)), kBufferCrc);
80}
81
82TEST(Crc32AppendFromC, String) {
83 EXPECT_EQ(CallChecksumCrc32Append(kString.data(), kString.size()),
84 kStringCrc);
85}
86
87} // namespace
88} // namespace pw::checksum