1 | // Copyright 2004 The RE2 Authors. All Rights Reserved. |
2 | // Use of this source code is governed by a BSD-style |
3 | // license that can be found in the LICENSE file. |
4 | |
5 | #include "re2/stringpiece.h" |
6 | |
7 | #include <ostream> |
8 | |
9 | #include "util/util.h" |
10 | |
11 | namespace re2 { |
12 | |
13 | const StringPiece::size_type StringPiece::npos; // initialized in stringpiece.h |
14 | |
15 | StringPiece::size_type StringPiece::copy(char* buf, size_type n, |
16 | size_type pos) const { |
17 | size_type ret = std::min(size_ - pos, n); |
18 | memcpy(buf, data_ + pos, ret); |
19 | return ret; |
20 | } |
21 | |
22 | StringPiece StringPiece::substr(size_type pos, size_type n) const { |
23 | if (pos > size_) pos = size_; |
24 | if (n > size_ - pos) n = size_ - pos; |
25 | return StringPiece(data_ + pos, n); |
26 | } |
27 | |
28 | StringPiece::size_type StringPiece::find(const StringPiece& s, |
29 | size_type pos) const { |
30 | if (pos > size_) return npos; |
31 | const_pointer result = std::search(data_ + pos, data_ + size_, |
32 | s.data_, s.data_ + s.size_); |
33 | size_type xpos = result - data_; |
34 | return xpos + s.size_ <= size_ ? xpos : npos; |
35 | } |
36 | |
37 | StringPiece::size_type StringPiece::find(char c, size_type pos) const { |
38 | if (size_ <= 0 || pos >= size_) return npos; |
39 | const_pointer result = std::find(data_ + pos, data_ + size_, c); |
40 | return result != data_ + size_ ? result - data_ : npos; |
41 | } |
42 | |
43 | StringPiece::size_type StringPiece::rfind(const StringPiece& s, |
44 | size_type pos) const { |
45 | if (size_ < s.size_) return npos; |
46 | if (s.size_ == 0) return std::min(size_, pos); |
47 | const_pointer last = data_ + std::min(size_ - s.size_, pos) + s.size_; |
48 | const_pointer result = std::find_end(data_, last, s.data_, s.data_ + s.size_); |
49 | return result != last ? result - data_ : npos; |
50 | } |
51 | |
52 | StringPiece::size_type StringPiece::rfind(char c, size_type pos) const { |
53 | if (size_ <= 0) return npos; |
54 | for (size_t i = std::min(pos + 1, size_); i != 0;) { |
55 | if (data_[--i] == c) return i; |
56 | } |
57 | return npos; |
58 | } |
59 | |
60 | std::ostream& operator<<(std::ostream& o, const StringPiece& p) { |
61 | o.write(p.data(), p.size()); |
62 | return o; |
63 | } |
64 | |
65 | } // namespace re2 |
66 | |