input.cc 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2015 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. #include "net/der/input.h"
  5. #include <algorithm>
  6. #include "base/check_op.h"
  7. namespace net::der {
  8. Input::Input(const base::StringPiece& in)
  9. : data_(reinterpret_cast<const uint8_t*>(in.data())), len_(in.length()) {}
  10. Input::Input(const std::string* s) : Input(base::StringPiece(*s)) {}
  11. std::string Input::AsString() const {
  12. return std::string(reinterpret_cast<const char*>(data_), len_);
  13. }
  14. base::StringPiece Input::AsStringPiece() const {
  15. return base::StringPiece(reinterpret_cast<const char*>(data_), len_);
  16. }
  17. base::span<const uint8_t> Input::AsSpan() const {
  18. return base::make_span(data_, len_);
  19. }
  20. bool operator==(const Input& lhs, const Input& rhs) {
  21. return lhs.Length() == rhs.Length() &&
  22. std::equal(lhs.UnsafeData(), lhs.UnsafeData() + lhs.Length(),
  23. rhs.UnsafeData());
  24. }
  25. bool operator!=(const Input& lhs, const Input& rhs) {
  26. return !(lhs == rhs);
  27. }
  28. ByteReader::ByteReader(const Input& in)
  29. : data_(in.UnsafeData()), len_(in.Length()) {
  30. }
  31. bool ByteReader::ReadByte(uint8_t* byte_p) {
  32. if (!HasMore())
  33. return false;
  34. *byte_p = *data_;
  35. Advance(1);
  36. return true;
  37. }
  38. bool ByteReader::ReadBytes(size_t len, Input* out) {
  39. if (len > len_)
  40. return false;
  41. *out = Input(data_, len);
  42. Advance(len);
  43. return true;
  44. }
  45. // Returns whether there is any more data to be read.
  46. bool ByteReader::HasMore() {
  47. return len_ > 0;
  48. }
  49. void ByteReader::Advance(size_t len) {
  50. CHECK_LE(len, len_);
  51. data_ += len;
  52. len_ -= len;
  53. }
  54. } // namespace net::der