• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 #pragma once
18 
19 #include <cstdint>
20 #include <forward_list>
21 
22 #include "packet/view.h"
23 
24 namespace bluetooth {
25 namespace packet {
26 
27 // Templated Iterator for endianness
28 template <bool little_endian>
29 class Iterator : public std::iterator<std::random_access_iterator_tag, uint8_t> {
30  public:
31   Iterator(std::forward_list<View> data, size_t offset);
32   Iterator(const Iterator& itr) = default;
33   virtual ~Iterator() = default;
34 
35   // All addition and subtraction operators are unbounded.
36   Iterator operator+(int offset);
37   Iterator& operator+=(int offset);
38   Iterator operator++(int);
39   Iterator& operator++();
40 
41   Iterator operator-(int offset);
42   int operator-(Iterator& itr);
43   Iterator& operator-=(int offset);
44   Iterator operator--(int);
45   Iterator& operator--();
46 
47   Iterator& operator=(const Iterator& itr);
48 
49   bool operator!=(const Iterator& itr) const;
50   bool operator==(const Iterator& itr) const;
51 
52   bool operator<(const Iterator& itr) const;
53   bool operator>(const Iterator& itr) const;
54 
55   bool operator<=(const Iterator& itr) const;
56   bool operator>=(const Iterator& itr) const;
57 
58   uint8_t operator*() const;
59   uint8_t operator->() const;
60 
61   size_t NumBytesRemaining() const;
62 
63   // Get the next sizeof(FixedWidthPODType) bytes and return the filled type
64   template <typename FixedWidthPODType>
extract()65   FixedWidthPODType extract() {
66     static_assert(std::is_pod<FixedWidthPODType>::value, "Iterator::extract requires an fixed type.");
67     FixedWidthPODType extracted_value;
68     uint8_t* value_ptr = (uint8_t*)&extracted_value;
69 
70     for (size_t i = 0; i < sizeof(FixedWidthPODType); i++) {
71       size_t index = (little_endian ? i : sizeof(FixedWidthPODType) - i - 1);
72       value_ptr[index] = *((*this)++);
73     }
74     return extracted_value;
75   }
76 
77  private:
78   std::forward_list<View> data_;
79   size_t index_;
80   size_t length_;
81 };
82 
83 }  // namespace packet
84 }  // namespace bluetooth
85