]>
Commit | Line | Data |
---|---|---|
729e4ab9 A |
1 | // Copyright (C) 2009-2010, International Business Machines |
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 | ||
14 | U_NAMESPACE_BEGIN | |
15 | ||
16 | StringPiece::StringPiece(const char* str) | |
17 | : ptr_(str), length_((str == NULL) ? 0 : static_cast<int32_t>(uprv_strlen(str))) { } | |
18 | ||
19 | StringPiece::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 | ||
29 | StringPiece::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 | ||
44 | void 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 | ||
52 | U_EXPORT UBool U_EXPORT2 | |
53 | operator==(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 | ||
71 | /* Microsft Visual Studios <= 8.0 complains about redefinition of this | |
72 | * static const class variable. However, the C++ standard states that this | |
73 | * definition is correct. Perhaps there is a bug in the Microsoft compiler. | |
74 | * This is not an issue on any other compilers (that we know of) including | |
75 | * Visual Studios 9.0. | |
76 | * Cygwin with MSVC 9.0 also complains here about redefinition. | |
77 | */ | |
78 | #if (!defined(_MSC_VER) || (_MSC_VER > 1500)) && !defined(CYGWINMSVC) | |
79 | const int32_t StringPiece::npos; | |
80 | #endif | |
81 | ||
82 | U_NAMESPACE_END |