]> git.saurik.com Git - apple/icu.git/blame - icuSources/common/stringpiece.cpp
ICU-57163.0.1.tar.gz
[apple/icu.git] / icuSources / common / stringpiece.cpp
CommitLineData
57a6839d 1// Copyright (C) 2009-2013, International Business Machines
729e4ab9
A
2// Corporation and others. All Rights Reserved.
3//
4// Copyright 2004 and onwards Google Inc.
5//
6// Author: wilsonh@google.com (Wilson Hsieh)
7//
8
9#include "unicode/utypes.h"
10#include "unicode/stringpiece.h"
11#include "cstring.h"
12#include "cmemory.h"
13
14U_NAMESPACE_BEGIN
15
16StringPiece::StringPiece(const char* str)
17 : ptr_(str), length_((str == NULL) ? 0 : static_cast<int32_t>(uprv_strlen(str))) { }
18
19StringPiece::StringPiece(const StringPiece& x, int32_t pos) {
20 if (pos < 0) {
21 pos = 0;
22 } else if (pos > x.length_) {
23 pos = x.length_;
24 }
25 ptr_ = x.ptr_ + pos;
26 length_ = x.length_ - pos;
27}
28
29StringPiece::StringPiece(const StringPiece& x, int32_t pos, int32_t len) {
30 if (pos < 0) {
31 pos = 0;
32 } else if (pos > x.length_) {
33 pos = x.length_;
34 }
35 if (len < 0) {
36 len = 0;
37 } else if (len > x.length_ - pos) {
38 len = x.length_ - pos;
39 }
40 ptr_ = x.ptr_ + pos;
41 length_ = len;
42}
43
44void StringPiece::set(const char* str) {
45 ptr_ = str;
46 if (str != NULL)
47 length_ = static_cast<int32_t>(uprv_strlen(str));
48 else
49 length_ = 0;
50}
51
52U_EXPORT UBool U_EXPORT2
53operator==(const StringPiece& x, const StringPiece& y) {
54 int32_t len = x.size();
55 if (len != y.size()) {
56 return false;
57 }
58 if (len == 0) {
59 return true;
60 }
61 const char* p = x.data();
62 const char* p2 = y.data();
63 // Test last byte in case strings share large common prefix
64 --len;
65 if (p[len] != p2[len]) return false;
66 // At this point we can, but don't have to, ignore the last byte.
67 return uprv_memcmp(p, p2, len) == 0;
68}
69
70
57a6839d 71const int32_t StringPiece::npos = 0x7fffffff;
729e4ab9
A
72
73U_NAMESPACE_END