25
25
#include " utilities/utf8.hpp"
26
26
#include " unittest.hpp"
27
27
28
- TEST (utf8, length) {
28
+ static void stamp (char * p, size_t len) {
29
+ if (len > 0 ) {
30
+ ::memset (p, ' A' , len);
31
+ }
32
+ }
33
+
34
+ static bool test_stamp (const char * p, size_t len) {
35
+ for (const char * q = p; q < p + len; q++) {
36
+ if (*q != ' A' ) {
37
+ return false ;
38
+ }
39
+ }
40
+ return true ;
41
+ }
42
+
43
+ TEST_VM (utf8, jchar_length) {
29
44
char res[60 ];
30
45
jchar str[20 ];
31
46
@@ -35,16 +50,56 @@ TEST(utf8, length) {
35
50
str[19 ] = (jchar) ' \0 ' ;
36
51
37
52
// The resulting string in UTF-8 is 3*19 bytes long, but should be truncated
53
+ stamp (res, sizeof (res));
38
54
UNICODE::as_utf8 (str, 19 , res, 10 );
39
55
ASSERT_EQ (strlen (res), (size_t ) 9 ) << " string should be truncated here" ;
56
+ ASSERT_TRUE (test_stamp (res + 10 , sizeof (res) - 10 ));
40
57
58
+ stamp (res, sizeof (res));
41
59
UNICODE::as_utf8 (str, 19 , res, 18 );
42
60
ASSERT_EQ (strlen (res), (size_t ) 15 ) << " string should be truncated here" ;
61
+ ASSERT_TRUE (test_stamp (res + 18 , sizeof (res) - 18 ));
43
62
63
+ stamp (res, sizeof (res));
44
64
UNICODE::as_utf8 (str, 19 , res, 20 );
45
65
ASSERT_EQ (strlen (res), (size_t ) 18 ) << " string should be truncated here" ;
66
+ ASSERT_TRUE (test_stamp (res + 20 , sizeof (res) - 20 ));
46
67
47
68
// Test with an "unbounded" buffer
48
69
UNICODE::as_utf8 (str, 19 , res, INT_MAX);
49
70
ASSERT_EQ (strlen (res), (size_t ) 3 * 19 ) << " string should end here" ;
71
+
72
+ // Test that we do not overflow the output buffer
73
+ for (int i = 1 ; i < 5 ; i ++) {
74
+ stamp (res, sizeof (res));
75
+ UNICODE::as_utf8 (str, 19 , res, i);
76
+ EXPECT_TRUE (test_stamp (res + i, sizeof (res) - i));
77
+ }
78
+
79
+ }
80
+
81
+ TEST_VM (utf8, jbyte_length) {
82
+ char res[60 ];
83
+ jbyte str[20 ];
84
+
85
+ for (int i = 0 ; i < 19 ; i++) {
86
+ str[i] = 0x42 ;
87
+ }
88
+ str[19 ] = ' \0 ' ;
89
+
90
+ stamp (res, sizeof (res));
91
+ UNICODE::as_utf8 (str, 19 , res, 10 );
92
+ ASSERT_EQ (strlen (res), (size_t ) 9 ) << " string should be truncated here" ;
93
+ ASSERT_TRUE (test_stamp (res + 10 , sizeof (res) - 10 ));
94
+
95
+ UNICODE::as_utf8 (str, 19 , res, INT_MAX);
96
+ ASSERT_EQ (strlen (res), (size_t ) 19 ) << " string should end here" ;
97
+
98
+ // Test that we do not overflow the output buffer
99
+ for (int i = 1 ; i < 5 ; i ++) {
100
+ stamp (res, sizeof (res));
101
+ UNICODE::as_utf8 (str, 19 , res, i);
102
+ EXPECT_TRUE (test_stamp (res + i, sizeof (res) - i));
103
+ }
104
+
50
105
}
0 commit comments