stringpiece.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #include "re2/stringpiece.h"
  5. #include <ostream>
  6. #include "util/util.h"
  7. namespace re2 {
  8. const StringPiece::size_type StringPiece::npos; // initialized in stringpiece.h
  9. StringPiece::size_type StringPiece::copy(char* buf, size_type n,
  10. size_type pos) const {
  11. size_type ret = std::min(size_ - pos, n);
  12. memcpy(buf, data_ + pos, ret);
  13. return ret;
  14. }
  15. StringPiece StringPiece::substr(size_type pos, size_type n) const {
  16. if (pos > size_) pos = size_;
  17. if (n > size_ - pos) n = size_ - pos;
  18. return StringPiece(data_ + pos, n);
  19. }
  20. StringPiece::size_type StringPiece::find(const StringPiece& s,
  21. size_type pos) const {
  22. if (pos > size_) return npos;
  23. const_pointer result = std::search(data_ + pos, data_ + size_,
  24. s.data_, s.data_ + s.size_);
  25. size_type xpos = result - data_;
  26. return xpos + s.size_ <= size_ ? xpos : npos;
  27. }
  28. StringPiece::size_type StringPiece::find(char c, size_type pos) const {
  29. if (size_ <= 0 || pos >= size_) return npos;
  30. const_pointer result = std::find(data_ + pos, data_ + size_, c);
  31. return result != data_ + size_ ? result - data_ : npos;
  32. }
  33. StringPiece::size_type StringPiece::rfind(const StringPiece& s,
  34. size_type pos) const {
  35. if (size_ < s.size_) return npos;
  36. if (s.size_ == 0) return std::min(size_, pos);
  37. const_pointer last = data_ + std::min(size_ - s.size_, pos) + s.size_;
  38. const_pointer result = std::find_end(data_, last, s.data_, s.data_ + s.size_);
  39. return result != last ? result - data_ : npos;
  40. }
  41. StringPiece::size_type StringPiece::rfind(char c, size_type pos) const {
  42. if (size_ <= 0) return npos;
  43. for (size_t i = std::min(pos + 1, size_); i != 0;) {
  44. if (data_[--i] == c) return i;
  45. }
  46. return npos;
  47. }
  48. std::ostream& operator<<(std::ostream& o, const StringPiece& p) {
  49. o.write(p.data(), p.size());
  50. return o;
  51. }
  52. } // namespace re2