Skip to content

Commit

Permalink
writer: if string starts with '-' followed by digit, write in quotes
Browse files Browse the repository at this point in the history
to distinguish unquoted `23` (an int) or `-3.45` (float) from quoted strings `"23"` and `"-3.45"`
  • Loading branch information
anthrotype committed Sep 29, 2018
1 parent ea8e215 commit 39d1db5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/openstep_plist/writer.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,19 @@ cdef Py_UNICODE *DICT_ITEM_SEP_NO_INDENT = [c';', c' ']


cdef inline bint is_valid_unquoted_string(const Py_UNICODE *a, Py_ssize_t length):
cdef Py_ssize_t i

# if string starts with digit, always write it within quotes
# to distinguish it from an actual integer or float number,
# which are always written without quotes
if c'0' <= a[0] <= c'9':
cdef Py_UNICODE ch = a[0]
# if string starts with digit, or with a '-' followed by a digit, always
# write it within quotes to distinguish it from an actual (signed) integer
# or float number, which are always written without quotes
if c'0' <= ch <= c'9':
return False
elif ch == c'-':
if length > 1:
ch = a[1]
if c'0' <= ch <= c'9':
return False

cdef Py_ssize_t i
for i in range(length):
if not is_valid_unquoted_string_char(a[i]):
return False
Expand Down
2 changes: 2 additions & 0 deletions tests/test_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ def test_unquoted_string(self):
# if string starts with digit, always quote it to distinguish from number
("1", '"1"'),
("1.1", '"1.1"'),
("-23", '"-23"'),
("1zzz", '"1zzz"'), # ... even if it's not actually a number
("-23yyy", '"-23yyy"'),
],
)
def test_quoted_string(self, string, expected):
Expand Down

0 comments on commit 39d1db5

Please sign in to comment.