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 5 #include "quiche/quic/core/internet_checksum.h" 6 7 #include <stdint.h> 8 #include <string.h> 9 10 #include "absl/strings/string_view.h" 11 #include "absl/types/span.h" 12 13 namespace quic { 14 Update(const char * data,size_t size)15void InternetChecksum::Update(const char* data, size_t size) { 16 const char* current; 17 for (current = data; current + 1 < data + size; current += 2) { 18 uint16_t v; 19 memcpy(&v, current, sizeof(v)); 20 accumulator_ += v; 21 } 22 if (current < data + size) { 23 accumulator_ += *reinterpret_cast<const unsigned char*>(current); 24 } 25 } 26 Update(const uint8_t * data,size_t size)27void InternetChecksum::Update(const uint8_t* data, size_t size) { 28 Update(reinterpret_cast<const char*>(data), size); 29 } 30 Update(absl::string_view data)31void InternetChecksum::Update(absl::string_view data) { 32 Update(data.data(), data.size()); 33 } 34 Update(absl::Span<const uint8_t> data)35void InternetChecksum::Update(absl::Span<const uint8_t> data) { 36 Update(reinterpret_cast<const char*>(data.data()), data.size()); 37 } 38 Value() const39uint16_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 48