llvm.org GIT mirror llvm / 437ef0c
Implements StringRef::compare with bounds. It is behaves similarly to strncmp(). Unit tests also included. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@129582 91177308-0d34-0410-b5e6-96231b3b80d8 Lenny Maiorani 9 years ago
3 changed file(s) with 40 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
124124 return Length < RHS.Length ? -1 : 1;
125125 }
126126
127 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
128 /// is lexicographically less than, equal to, or greater than the \arg RHS.
129 /// This is different than compare with no size specified as it only
130 /// compares at most the first n bytes.
131 int compare(StringRef RHS, size_t n) const;
132
127133 /// compare_lower - Compare two strings, ignoring case.
128134 int compare_lower(StringRef RHS) const;
129135
2626
2727 static bool ascii_isdigit(char x) {
2828 return x >= '0' && x <= '9';
29 }
30
31 /// compare - Compare two strings; the result is -1, 0, or 1 if this string
32 /// is lexicographically less than, equal to, or greater than the \arg RHS.
33 /// This is different than compare with no size specified as it only
34 /// compares at most the first n bytes.
35 int StringRef::compare(StringRef RHS, size_t n) const {
36 // Check the prefix for a mismatch.
37 size_t maxToCmp = min(Length, RHS.Length);
38 maxToCmp = min(maxToCmp, n);
39 if (int Res = memcmp(Data, RHS.Data, maxToCmp))
40 return Res < 0 ? -1 : 1;
41
42 // Otherwise the prefixes match, so we only need to check the lengths.
43 // Be mindful that if the n is less than or equal to the length of either
44 // string, that is the same as the strings matching because in that case
45 // we only care about the prefix.
46 if (((n <= Length) && (n <= RHS.Length)) ||
47 (Length == RHS.Length))
48 return 0;
49 return Length < RHS.Length ? -1 : 1;
2950 }
3051
3152 /// compare_lower - Compare strings, ignoring case.
5353 EXPECT_EQ(-1, StringRef("aab").compare("aabb"));
5454 EXPECT_EQ( 1, StringRef("aab").compare("aa"));
5555 EXPECT_EQ( 1, StringRef("\xFF").compare("\1"));
56
57 EXPECT_EQ(-1, StringRef("aab").compare("aad", 3));
58 EXPECT_EQ( 0, StringRef("aab").compare("aab", 3));
59 EXPECT_EQ( 1, StringRef("aab").compare("aaa", 3));
60 EXPECT_EQ(-1, StringRef("aab").compare("aabb", 4));
61 EXPECT_EQ( 1, StringRef("aab").compare("aa", 3));
62 EXPECT_EQ( 1, StringRef("\xFF").compare("\1", 3));
63 EXPECT_EQ( 0, StringRef("aab").compare("aad", 2));
64 EXPECT_EQ( 0, StringRef("aab").compare("aab", 2));
65 EXPECT_EQ( 0, StringRef("aab").compare("aab", 4));
66 EXPECT_EQ( 0, StringRef("aab").compare("aaa", 2));
67 EXPECT_EQ( 0, StringRef("aab").compare("aabb", 3));
68 EXPECT_EQ( 0, StringRef("aab").compare("aa", 2));
5669
5770 EXPECT_EQ(-1, StringRef("AaB").compare_lower("aAd"));
5871 EXPECT_EQ( 0, StringRef("AaB").compare_lower("aab"));