Bence Béky | bac0405 | 2022-04-07 15:44:29 -0400 | [diff] [blame] | 1 | // Copyright (c) 2019 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
ericorth | 920d43f | 2023-12-11 12:43:42 -0800 | [diff] [blame] | 5 | #include "quiche/quic/core/internet_checksum.h" |
Bence Béky | bac0405 | 2022-04-07 15:44:29 -0400 | [diff] [blame] | 6 | |
Benjamin Barenblat | 66cfacd | 2022-05-27 13:37:07 -0700 | [diff] [blame] | 7 | #include <stdint.h> |
| 8 | #include <string.h> |
| 9 | |
ericorth | 055049e | 2023-12-13 10:06:39 -0800 | [diff] [blame] | 10 | #include "absl/strings/string_view.h" |
| 11 | #include "absl/types/span.h" |
| 12 | |
Bence Béky | bac0405 | 2022-04-07 15:44:29 -0400 | [diff] [blame] | 13 | namespace quic { |
| 14 | |
| 15 | void InternetChecksum::Update(const char* data, size_t size) { |
| 16 | const char* current; |
| 17 | for (current = data; current + 1 < data + size; current += 2) { |
Benjamin Barenblat | 66cfacd | 2022-05-27 13:37:07 -0700 | [diff] [blame] | 18 | uint16_t v; |
| 19 | memcpy(&v, current, sizeof(v)); |
| 20 | accumulator_ += v; |
Bence Béky | bac0405 | 2022-04-07 15:44:29 -0400 | [diff] [blame] | 21 | } |
| 22 | if (current < data + size) { |
Benjamin Barenblat | 66cfacd | 2022-05-27 13:37:07 -0700 | [diff] [blame] | 23 | accumulator_ += *reinterpret_cast<const unsigned char*>(current); |
Bence Béky | bac0405 | 2022-04-07 15:44:29 -0400 | [diff] [blame] | 24 | } |
| 25 | } |
| 26 | |
| 27 | void InternetChecksum::Update(const uint8_t* data, size_t size) { |
| 28 | Update(reinterpret_cast<const char*>(data), size); |
| 29 | } |
| 30 | |
ericorth | 055049e | 2023-12-13 10:06:39 -0800 | [diff] [blame] | 31 | void InternetChecksum::Update(absl::string_view data) { |
| 32 | Update(data.data(), data.size()); |
| 33 | } |
| 34 | |
| 35 | void InternetChecksum::Update(absl::Span<const uint8_t> data) { |
| 36 | Update(reinterpret_cast<const char*>(data.data()), data.size()); |
| 37 | } |
| 38 | |
Bence Béky | bac0405 | 2022-04-07 15:44:29 -0400 | [diff] [blame] | 39 | uint16_t InternetChecksum::Value() const { |
| 40 | uint32_t total = accumulator_; |
| 41 | while (total & 0xffff0000u) { |
| 42 | total = (total >> 16u) + (total & 0xffffu); |
| 43 | } |
| 44 | return ~static_cast<uint16_t>(total); |
| 45 | } |
| 46 | |
| 47 | } // namespace quic |