1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // String manipulation functions used in the RLZ library.
7 #include "rlz/lib/string_utils.h"
9 #include "rlz/lib/assert.h"
13 bool IsAscii(unsigned char letter
) {
17 bool GetHexValue(char letter
, int* value
) {
19 ASSERT_STRING("GetHexValue: Invalid output paramter");
24 if (letter
>= '0' && letter
<= '9')
25 *value
= letter
- '0';
26 else if (letter
>= 'a' && letter
<= 'f')
27 *value
= (letter
- 'a') + 0xA;
28 else if (letter
>= 'A' && letter
<= 'F')
29 *value
= (letter
- 'A') + 0xA;
36 int HexStringToInteger(const char* text
) {
38 ASSERT_STRING("HexStringToInteger: text is NULL.");
43 // Ignore leading whitespace.
44 while (text
[idx
] == '\t' || text
[idx
] == ' ')
47 if ((text
[idx
] == '0') &&
48 (text
[idx
+ 1] == 'X' || text
[idx
+ 1] == 'x'))
49 idx
+=2; // String is of the form 0x...
53 for (; text
[idx
] != '\0'; idx
++) {
54 if (!GetHexValue(text
[idx
], &digit
)) {
55 // Ignore trailing whitespaces, but assert on other trailing characters.
56 bool only_whitespaces
= true;
57 while (only_whitespaces
&& text
[idx
])
58 only_whitespaces
= (text
[idx
++] == ' ');
59 if (!only_whitespaces
)
60 ASSERT_STRING("HexStringToInteger: text contains non-hex characters.");
63 number
= (number
<< 4) | digit
;
69 bool BytesToString(const unsigned char* data
,
71 std::string
* string
) {
76 if (data_len
< 1 || !data
)
79 static const char kHex
[] = "0123456789ABCDEF";
81 // Fix the buffer size to begin with to avoid repeated re-allocation.
82 string
->resize(data_len
* 2);
85 string
->at(2 * index
) = kHex
[data
[index
] >> 4]; // high digit
86 string
->at(2 * index
+ 1) = kHex
[data
[index
] & 0x0F]; // low digit
92 } // namespace rlz_lib