Skip to content

Commit 8ec5d23

Browse files
authored
Merge pull request #395 from sahvx655-wq/is-space-signed-compare
guard is_space against negative signed code units
2 parents 34164f5 + c539b53 commit 8ec5d23

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

include/fast_float/float_common.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1223,7 +1223,11 @@ template <typename T> constexpr bool space_lut<T>::value[];
12231223
#endif
12241224

12251225
template <typename UC> constexpr bool is_space(UC c) {
1226-
return c < 256 && space_lut<>::value[uint8_t(c)];
1226+
// wchar_t and char can be signed, so a negative code unit slips past a plain
1227+
// `c < 256` and then indexes the table by its truncated low byte. Compare as
1228+
// unsigned, matching the care taken in ch_to_digit.
1229+
using UnsignedUC = typename std::make_unsigned<UC>::type;
1230+
return static_cast<UnsignedUC>(c) < 256 && space_lut<>::value[uint8_t(c)];
12271231
}
12281232

12291233
template <typename UC> static constexpr uint64_t int_cmp_zeros() {

tests/wide_char_test.cpp

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include <iostream>
33
#include <string>
44
#include <system_error>
5+
#include <type_traits>
56

67
bool tester(std::string s, double expected,
78
fast_float::chars_format fmt = fast_float::chars_format::general) {
@@ -46,8 +47,32 @@ bool test_nan() {
4647
return tester("nan", std::numeric_limits<double>::quiet_NaN());
4748
}
4849

50+
// A wide code unit whose low byte is an ASCII space (0x20) but whose full value
51+
// is not whitespace must not be skipped by skip_white_space. When wchar_t is
52+
// signed such a unit can be negative, which used to slip past the range guard
53+
// in is_space and get treated as a space.
54+
bool test_non_space_with_space_low_byte() {
55+
if (!std::is_signed<wchar_t>::value) {
56+
return true; // only reproducible where wchar_t is signed
57+
}
58+
std::wstring input = L" 42";
59+
// 0x...FF20: low byte 0x20, high bits set, so the value is negative.
60+
input[0] = static_cast<wchar_t>(~static_cast<unsigned int>(0xFF) | 0x20u);
61+
double result;
62+
auto answer =
63+
fast_float::from_chars(input.data(), input.data() + input.size(), result,
64+
fast_float::chars_format::general |
65+
fast_float::chars_format::skip_white_space);
66+
if (answer.ec == std::errc()) {
67+
std::cerr << "leading non-space code unit must not be skipped\n";
68+
return false;
69+
}
70+
return true;
71+
}
72+
4973
int main() {
50-
if (test_minus() && test_plus() && test_space() && test_nan()) {
74+
if (test_minus() && test_plus() && test_space() && test_nan() &&
75+
test_non_space_with_space_low_byte()) {
5176
std::cout << "all ok" << std::endl;
5277
return EXIT_SUCCESS;
5378
}

0 commit comments

Comments
 (0)