• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 //
10 
11 #include "unicode/utypes.h"
12 #include "unicode/stringpiece.h"
13 #include "cstring.h"
14 #include "cmemory.h"
15 
16 U_NAMESPACE_BEGIN
17 
StringPiece(const char * str)18 StringPiece::StringPiece(const char* str)
19     : ptr_(str), length_((str == NULL) ? 0 : static_cast<int32_t>(uprv_strlen(str))) { }
20 
StringPiece(const StringPiece & x,int32_t pos)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_;
26   }
27   ptr_ = x.ptr_ + pos;
28   length_ = x.length_ - pos;
29 }
30 
StringPiece(const StringPiece & x,int32_t pos,int32_t len)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_;
36   }
37   if (len < 0) {
38     len = 0;
39   } else if (len > x.length_ - pos) {
40     len = x.length_ - pos;
41   }
42   ptr_ = x.ptr_ + pos;
43   length_ = len;
44 }
45 
set(const char * str)46 void StringPiece::set(const char* str) {
47   ptr_ = str;
48   if (str != NULL)
49     length_ = static_cast<int32_t>(uprv_strlen(str));
50   else
51     length_ = 0;
52 }
53 
54 U_EXPORT UBool U_EXPORT2
operator ==(const StringPiece & x,const StringPiece & y)55 operator==(const StringPiece& x, const StringPiece& y) {
56   int32_t len = x.size();
57   if (len != y.size()) {
58     return false;
59   }
60   if (len == 0) {
61     return true;
62   }
63   const char* p = x.data();
64   const char* p2 = y.data();
65   // Test last byte in case strings share large common prefix
66   --len;
67   if (p[len] != p2[len]) return false;
68   // At this point we can, but don't have to, ignore the last byte.
69   return uprv_memcmp(p, p2, len) == 0;
70 }
71 
72 
73 const int32_t StringPiece::npos = 0x7fffffff;
74 
75 U_NAMESPACE_END
76