iterator.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright 2019 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <cstdint>
  18. #include <forward_list>
  19. #include "packet/view.h"
  20. namespace bluetooth {
  21. namespace packet {
  22. // Templated Iterator for endianness
  23. template <bool little_endian>
  24. class Iterator : public std::iterator<std::random_access_iterator_tag, uint8_t> {
  25. public:
  26. Iterator(std::forward_list<View> data, size_t offset);
  27. Iterator(const Iterator& itr) = default;
  28. virtual ~Iterator() = default;
  29. // All addition and subtraction operators are unbounded.
  30. Iterator operator+(int offset);
  31. Iterator& operator+=(int offset);
  32. Iterator operator++(int);
  33. Iterator& operator++();
  34. Iterator operator-(int offset);
  35. int operator-(Iterator& itr);
  36. Iterator& operator-=(int offset);
  37. Iterator operator--(int);
  38. Iterator& operator--();
  39. Iterator& operator=(const Iterator& itr);
  40. bool operator!=(const Iterator& itr) const;
  41. bool operator==(const Iterator& itr) const;
  42. bool operator<(const Iterator& itr) const;
  43. bool operator>(const Iterator& itr) const;
  44. bool operator<=(const Iterator& itr) const;
  45. bool operator>=(const Iterator& itr) const;
  46. uint8_t operator*() const;
  47. uint8_t operator->() const;
  48. size_t NumBytesRemaining() const;
  49. // Get the next sizeof(FixedWidthPODType) bytes and return the filled type
  50. template <typename FixedWidthPODType>
  51. FixedWidthPODType extract() {
  52. static_assert(std::is_pod<FixedWidthPODType>::value, "Iterator::extract requires an fixed type.");
  53. FixedWidthPODType extracted_value;
  54. uint8_t* value_ptr = (uint8_t*)&extracted_value;
  55. for (size_t i = 0; i < sizeof(FixedWidthPODType); i++) {
  56. size_t index = (little_endian ? i : sizeof(FixedWidthPODType) - i - 1);
  57. value_ptr[index] = *((*this)++);
  58. }
  59. return extracted_value;
  60. }
  61. private:
  62. std::forward_list<View> data_;
  63. size_t index_;
  64. size_t length_;
  65. };
  66. } // namespace packet
  67. } // namespace bluetooth