xpcom/tests/TestCRT.cpp

branch
TOR_BUG_3246
changeset 7
129ffea94266
equal deleted inserted replaced
-1:000000000000 0:8efd6f1ab906
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6 #include "nsCRT.h"
7 #include "nsString.h"
8 #include "plstr.h"
9 #include <stdlib.h>
10
11 namespace TestCRT {
12
13 // The return from strcmp etc is only defined to be postive, zero or
14 // negative. The magnitude of a non-zero return is irrelevant.
15 int sign(int val) {
16 if (val == 0)
17 return 0;
18 else {
19 if (val > 0)
20 return 1;
21 else
22 return -1;
23 }
24 }
25
26
27 // Verify that nsCRT versions of string comparison routines get the
28 // same answers as the native non-unicode versions. We only pass in
29 // iso-latin-1 strings, so the comparison must be valid.
30 static void Check(const char* s1, const char* s2, int n)
31 {
32 #ifdef DEBUG
33 int clib =
34 #endif
35 PL_strcmp(s1, s2);
36
37 #ifdef DEBUG
38 int clib_n =
39 #endif
40 PL_strncmp(s1, s2, n);
41
42 nsAutoString t1,t2;
43 t1.AssignWithConversion(s1);
44 t2.AssignWithConversion(s2);
45 const char16_t* us1 = t1.get();
46 const char16_t* us2 = t2.get();
47
48 #ifdef DEBUG
49 int u2 =
50 #endif
51 nsCRT::strcmp(us1, us2);
52
53 #ifdef DEBUG
54 int u2_n =
55 #endif
56 nsCRT::strncmp(us1, us2, n);
57
58 NS_ASSERTION(sign(clib) == sign(u2), "strcmp");
59 NS_ASSERTION(sign(clib_n) == sign(u2_n), "strncmp");
60 }
61
62 struct Test {
63 const char* s1;
64 const char* s2;
65 int n;
66 };
67
68 static Test tests[] = {
69 { "foo", "foo", 3 },
70 { "foo", "fo", 3 },
71
72 { "foo", "bar", 3 },
73 { "foo", "ba", 3 },
74
75 { "foo", "zap", 3 },
76 { "foo", "za", 3 },
77
78 { "bar", "foo", 3 },
79 { "bar", "fo", 3 },
80
81 { "bar", "foo", 3 },
82 { "bar", "fo", 3 },
83 };
84 #define NUM_TESTS int((sizeof(tests) / sizeof(tests[0])))
85
86 }
87
88 using namespace TestCRT;
89
90 int main()
91 {
92 Test* tp = tests;
93 for (int i = 0; i < NUM_TESTS; i++, tp++) {
94 Check(tp->s1, tp->s2, tp->n);
95 }
96
97 return 0;
98 }

mercurial