Bob Beck | bc97b7a | 2023-04-18 08:35:15 -0600 | [diff] [blame] | 1 | // Copyright 2015 The Chromium Authors |
| 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 "input.h" |
| 6 | |
| 7 | #include <algorithm> |
| 8 | |
| 9 | #include "fillins/check.h" |
| 10 | |
| 11 | namespace bssl::der { |
| 12 | |
| 13 | Input::Input(std::string_view in) |
| 14 | : data_(reinterpret_cast<const uint8_t*>(in.data())), len_(in.length()) {} |
| 15 | |
| 16 | Input::Input(const std::string* s) : Input(std::string_view(*s)) {} |
| 17 | |
| 18 | std::string Input::AsString() const { |
| 19 | return std::string(reinterpret_cast<const char*>(data_), len_); |
| 20 | } |
| 21 | |
| 22 | std::string_view Input::AsStringView() const { |
| 23 | return std::string_view(reinterpret_cast<const char*>(data_), len_); |
| 24 | } |
| 25 | |
| 26 | bssl::Span<const uint8_t> Input::AsSpan() const { |
| 27 | return bssl::MakeSpan(data_, len_); |
| 28 | } |
| 29 | |
| 30 | bool operator==(const Input& lhs, const Input& rhs) { |
| 31 | return lhs.Length() == rhs.Length() && |
| 32 | std::equal(lhs.UnsafeData(), lhs.UnsafeData() + lhs.Length(), |
| 33 | rhs.UnsafeData()); |
| 34 | } |
| 35 | |
| 36 | bool operator!=(const Input& lhs, const Input& rhs) { |
| 37 | return !(lhs == rhs); |
| 38 | } |
| 39 | |
| 40 | ByteReader::ByteReader(const Input& in) |
| 41 | : data_(in.UnsafeData()), len_(in.Length()) { |
| 42 | } |
| 43 | |
| 44 | bool ByteReader::ReadByte(uint8_t* byte_p) { |
| 45 | if (!HasMore()) |
| 46 | return false; |
| 47 | *byte_p = *data_; |
| 48 | Advance(1); |
| 49 | return true; |
| 50 | } |
| 51 | |
| 52 | bool ByteReader::ReadBytes(size_t len, Input* out) { |
| 53 | if (len > len_) |
| 54 | return false; |
| 55 | *out = Input(data_, len); |
| 56 | Advance(len); |
| 57 | return true; |
| 58 | } |
| 59 | |
| 60 | // Returns whether there is any more data to be read. |
| 61 | bool ByteReader::HasMore() { |
| 62 | return len_ > 0; |
| 63 | } |
| 64 | |
| 65 | void ByteReader::Advance(size_t len) { |
| 66 | CHECK_LE(len, len_); |
| 67 | data_ += len; |
| 68 | len_ -= len; |
| 69 | } |
| 70 | |
| 71 | } // namespace bssl::der |