Backed out changeset 2450366cf7ca (bug 1891629) for causing win msix mochitest failures
[gecko.git] / intl / icu / source / common / stringpiece.cpp
blobeb9766c01803d603a9a4332d447f20a63273c1c0
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 // Copyright (C) 2009-2013, International Business Machines
4 // Corporation and others. All Rights Reserved.
5 //
6 // Copyright 2004 and onwards Google Inc.
7 //
8 // Author: wilsonh@google.com (Wilson Hsieh)
9 //
11 #include "unicode/utypes.h"
12 #include "unicode/stringpiece.h"
13 #include "cstring.h"
14 #include "cmemory.h"
16 U_NAMESPACE_BEGIN
18 StringPiece::StringPiece(const char* str)
19 : ptr_(str), length_((str == nullptr) ? 0 : static_cast<int32_t>(uprv_strlen(str))) { }
21 StringPiece::StringPiece(const StringPiece& x, int32_t pos) {
22 if (pos < 0) {
23 pos = 0;
24 } else if (pos > x.length_) {
25 pos = x.length_;
27 ptr_ = x.ptr_ + pos;
28 length_ = x.length_ - pos;
31 StringPiece::StringPiece(const StringPiece& x, int32_t pos, int32_t len) {
32 if (pos < 0) {
33 pos = 0;
34 } else if (pos > x.length_) {
35 pos = x.length_;
37 if (len < 0) {
38 len = 0;
39 } else if (len > x.length_ - pos) {
40 len = x.length_ - pos;
42 ptr_ = x.ptr_ + pos;
43 length_ = len;
46 void StringPiece::set(const char* str) {
47 ptr_ = str;
48 if (str != nullptr)
49 length_ = static_cast<int32_t>(uprv_strlen(str));
50 else
51 length_ = 0;
54 int32_t StringPiece::find(StringPiece needle, int32_t offset) {
55 if (length() == 0 && needle.length() == 0) {
56 return 0;
58 // TODO: Improve to be better than O(N^2)?
59 for (int32_t i = offset; i < length(); i++) {
60 int32_t j = 0;
61 for (; j < needle.length(); i++, j++) {
62 if (data()[i] != needle.data()[j]) {
63 i -= j;
64 goto outer_end;
67 return i - j;
68 outer_end: void();
70 return -1;
73 int32_t StringPiece::compare(StringPiece other) {
74 int32_t i = 0;
75 for (; i < length(); i++) {
76 if (i == other.length()) {
77 // this is longer
78 return 1;
80 char a = data()[i];
81 char b = other.data()[i];
82 if (a < b) {
83 return -1;
84 } else if (a > b) {
85 return 1;
88 if (i < other.length()) {
89 // other is longer
90 return -1;
92 return 0;
95 U_EXPORT UBool U_EXPORT2
96 operator==(const StringPiece& x, const StringPiece& y) {
97 int32_t len = x.size();
98 if (len != y.size()) {
99 return false;
101 if (len == 0) {
102 return true;
104 const char* p = x.data();
105 const char* p2 = y.data();
106 // Test last byte in case strings share large common prefix
107 --len;
108 if (p[len] != p2[len]) return false;
109 // At this point we can, but don't have to, ignore the last byte.
110 return uprv_memcmp(p, p2, len) == 0;
114 const int32_t StringPiece::npos = 0x7fffffff;
116 U_NAMESPACE_END