Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use strtoll() to parse ints #360

Merged
merged 2 commits into from Sep 8, 2017
Merged

Use strtoll() to parse ints #360

merged 2 commits into from Sep 8, 2017

Conversation

jasonbking
Copy link

Instead of using sscanf() (whose behavior is surprisingly underspecified) to parse integer values, use strtoll() instead. It turns out to be much simpler, and hopefully is more portable.

@jasonbking
Copy link
Author

It's not obvious what the AppVeyor failures were -- nothing I pushed should have touched any VS project files. Is there something more specific someone can point me at?

@hawicz
Copy link
Member

hawicz commented Sep 8, 2017

So how do we know sizeof(long long) == sizeof(int64_t) ?

(the AppVeyor build is probably because I removed the VS project files, and didn't do anything to make it use cmake instead)

@jasonbking
Copy link
Author

jasonbking commented Sep 8, 2017

https://en.wikipedia.org/wiki/C_data_types has the (likely) more digestible version, but includes a link to the relevant standards. tl;dr -- C99 requires that long long can hold at least a 64-bit signed integer. No implementation I'm aware of today uses any integer size larger than that for long long (it'd likely break a lot of stuff), though if there are concerns of that happening, I could have it do something like:

char *end = NULL;
long long val;
errno = 0;
val = stroll(buf, &end, 10);
if (end != buf) {
    if (val > INT64_MAX)
        *retval = INT64_MAX;
   else if (val < INT64_MIN)
       *retval = INT64_MIN;
   else
        *retval = val;
}
return ((val == 0 && errno != 0) || (end == buf)) ? 1 : 0;

or even put the bits capping the value inside a #if sizeof (long long) > sizeof (int64_t) block

@hawicz
Copy link
Member

hawicz commented Sep 8, 2017

You're right, it's pretty unlikely. Enough so that I'd say instead of code to handle it let's just do a preprocessor check like:

#if SIZEOF_LONG_LONG != SIZEOF_INT64_T
#error The long long type isn't 64-bits
#endif

@hawicz hawicz merged commit 5454c4e into json-c:master Sep 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants