Publishing 2019 R1 content
[platform/upstream/dldt.git] / inference-engine / src / inference_engine / range_iterator.hpp
1 // Copyright (C) 2018-2019 Intel Corporation
2 // SPDX-License-Identifier: Apache-2.0
3 //
4
5 #pragma once
6
7 #include <algorithm>
8
9 namespace InferenceEngine {
10
11 /**
12  * @Brief iterator for accesing standard c-style null terminated strings withing c++ algorithms
13  * @tparam Char
14  */
15 template<typename Char>
16 struct null_terminated_range_iterator : public std::iterator<std::forward_iterator_tag, Char> {
17  public:
18     null_terminated_range_iterator() = delete;
19
20     // make a non-end iterator (well, unless you pass nullptr ;)
21     explicit null_terminated_range_iterator(Char *ptr) : ptr(ptr) {}
22
23     bool operator != (null_terminated_range_iterator const &that) const {
24         // iterators are equal if they point to the same location
25         return !(operator==(that));
26     }
27
28     bool operator == (null_terminated_range_iterator const &that) const {
29         // iterators are equal if they point to the same location
30         return ptr == that.ptr
31             // or if they are both end iterators
32             || (is_end() && that.is_end());
33     }
34
35     null_terminated_range_iterator<Char> &operator++() {
36         get_accessor()++;
37         return *this;
38     }
39
40     null_terminated_range_iterator<Char> &operator++(int) {
41         return this->operator++();
42     }
43
44     Char &operator*() {
45         return *get_accessor();
46     }
47
48  protected:
49     Char *& get_accessor()  {
50         if (ptr == nullptr) {
51             throw std::logic_error("null_terminated_range_iterator dereference: pointer is zero");
52         }
53         return ptr;
54     }
55     bool is_end() const {
56         // end iterators can be created by the default ctor
57         return !ptr
58             // or by advancing until a null character
59             || !*ptr;
60     }
61
62     Char *ptr;
63 };
64
65 template<typename Char>
66 struct null_terminated_range_iterator_end : public null_terminated_range_iterator<Char> {
67  public:
68     // make an end iterator
69     null_terminated_range_iterator_end() :  null_terminated_range_iterator<Char>(nullptr) {
70         null_terminated_range_iterator<Char>::ptr = nullptr;
71     }
72 };
73
74
75 inline null_terminated_range_iterator<const char> null_terminated_string(const char *a) {
76     return null_terminated_range_iterator<const char>(a);
77 }
78
79 inline null_terminated_range_iterator<const char> null_terminated_string_end() {
80     return null_terminated_range_iterator_end<const char>();
81 }
82
83 }  // namespace InferenceEngine