input_reader.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2022 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. #ifndef COMPONENTS_WEB_PACKAGE_INPUT_READER_H_
  5. #define COMPONENTS_WEB_PACKAGE_INPUT_READER_H_
  6. #include "base/big_endian.h"
  7. #include "base/containers/span.h"
  8. #include "base/strings/string_piece_forward.h"
  9. #include "third_party/abseil-cpp/absl/types/optional.h"
  10. namespace web_package {
  11. // https://datatracker.ietf.org/doc/html/rfc8949.html#section-3.1
  12. enum class CBORType {
  13. // kUnsignedInt = 0,
  14. // kNegativeInt = 1,
  15. kByteString = 2,
  16. kTextString = 3,
  17. kArray = 4,
  18. kMap = 5,
  19. };
  20. // The maximum length of the CBOR item header (type and argument).
  21. // https://datatracker.ietf.org/doc/html/rfc8949.html#section-3
  22. // When the additional information (the low-order 5 bits of the first
  23. // byte) is 27, the argument's value is held in the following 8 bytes.
  24. constexpr uint64_t kMaxCBORItemHeaderSize = 9;
  25. // A utility class for reading various values from input buffer.
  26. class InputReader {
  27. public:
  28. explicit InputReader(base::span<const uint8_t> buf) : buf_(buf) {}
  29. InputReader(const InputReader&) = delete;
  30. InputReader& operator=(const InputReader&) = delete;
  31. uint64_t CurrentOffset() const { return current_offset_; }
  32. size_t Size() const { return buf_.size(); }
  33. absl::optional<uint8_t> ReadByte();
  34. template <typename T>
  35. bool ReadBigEndian(T* out) {
  36. auto bytes = ReadBytes(sizeof(T));
  37. if (!bytes)
  38. return false;
  39. base::ReadBigEndian(bytes->data(), out);
  40. return true;
  41. }
  42. absl::optional<base::span<const uint8_t>> ReadBytes(size_t n);
  43. absl::optional<base::StringPiece> ReadString(size_t n);
  44. // Parses the type and argument of a CBOR item from the input head. If parsed
  45. // successfully and the type matches |expected_type|, returns the argument.
  46. // Otherwise returns nullopt.
  47. absl::optional<uint64_t> ReadCBORHeader(CBORType expected_type);
  48. private:
  49. absl::optional<std::pair<CBORType, uint64_t>> ReadTypeAndArgument();
  50. void Advance(size_t n);
  51. base::span<const uint8_t> buf_;
  52. uint64_t current_offset_ = 0;
  53. };
  54. } // namespace web_package
  55. #endif // COMPONENTS_WEB_PACKAGE_INPUT_READER_H_