michael@0: // Copyright (C) 2009-2013, International Business Machines michael@0: // Corporation and others. All Rights Reserved. michael@0: // michael@0: // Copyright 2004 and onwards Google Inc. michael@0: // michael@0: // Author: wilsonh@google.com (Wilson Hsieh) michael@0: // michael@0: michael@0: #include "unicode/utypes.h" michael@0: #include "unicode/stringpiece.h" michael@0: #include "cstring.h" michael@0: #include "cmemory.h" michael@0: michael@0: U_NAMESPACE_BEGIN michael@0: michael@0: StringPiece::StringPiece(const char* str) michael@0: : ptr_(str), length_((str == NULL) ? 0 : static_cast(uprv_strlen(str))) { } michael@0: michael@0: StringPiece::StringPiece(const StringPiece& x, int32_t pos) { michael@0: if (pos < 0) { michael@0: pos = 0; michael@0: } else if (pos > x.length_) { michael@0: pos = x.length_; michael@0: } michael@0: ptr_ = x.ptr_ + pos; michael@0: length_ = x.length_ - pos; michael@0: } michael@0: michael@0: StringPiece::StringPiece(const StringPiece& x, int32_t pos, int32_t len) { michael@0: if (pos < 0) { michael@0: pos = 0; michael@0: } else if (pos > x.length_) { michael@0: pos = x.length_; michael@0: } michael@0: if (len < 0) { michael@0: len = 0; michael@0: } else if (len > x.length_ - pos) { michael@0: len = x.length_ - pos; michael@0: } michael@0: ptr_ = x.ptr_ + pos; michael@0: length_ = len; michael@0: } michael@0: michael@0: void StringPiece::set(const char* str) { michael@0: ptr_ = str; michael@0: if (str != NULL) michael@0: length_ = static_cast(uprv_strlen(str)); michael@0: else michael@0: length_ = 0; michael@0: } michael@0: michael@0: U_EXPORT UBool U_EXPORT2 michael@0: operator==(const StringPiece& x, const StringPiece& y) { michael@0: int32_t len = x.size(); michael@0: if (len != y.size()) { michael@0: return false; michael@0: } michael@0: if (len == 0) { michael@0: return true; michael@0: } michael@0: const char* p = x.data(); michael@0: const char* p2 = y.data(); michael@0: // Test last byte in case strings share large common prefix michael@0: --len; michael@0: if (p[len] != p2[len]) return false; michael@0: // At this point we can, but don't have to, ignore the last byte. michael@0: return uprv_memcmp(p, p2, len) == 0; michael@0: } michael@0: michael@0: michael@0: const int32_t StringPiece::npos = 0x7fffffff; michael@0: michael@0: U_NAMESPACE_END