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

time comparison flawed #150

Open
dcurrie opened this issue Aug 13, 2016 · 3 comments
Open

time comparison flawed #150

dcurrie opened this issue Aug 13, 2016 · 3 comments

Comments

@dcurrie
Copy link

dcurrie commented Aug 13, 2016

The conversion of unsigned to signed type for TIME_LT() and friends in sys/types.h depends on C compiler implementation-defined behavior.

@travisg
Copy link
Member

travisg commented Aug 13, 2016

Yeah, I've known about that one for a while, though in practice it's been fine. If you can put together a patch with similar semantics and efficiency I'd absolutely take it.

Can probably do it with an inline routine.

@dcurrie
Copy link
Author

dcurrie commented Aug 14, 2016

I believe these are equivalent and do not use signed arithmetic:

#define TIME_GTE(a, b) (((a) - (b)) <= (INFINITE_TIME / 2u))

#define TIME_LTE(a, b) ((((a) - (b)) - 1u) > ((INFINITE_TIME / 2u) - 1u))

#define TIME_GT(a, b) ((((a) - (b)) - 1u) <= ((INFINITE_TIME / 2u) - 1u))

#define TIME_LT(a, b) (((a) - (b)) > (INFINITE_TIME / 2u))

These macros also make it more explicit that times cannot differ by more than UINT32_MAX/2 to be comparable; otherwise the difference overflows an int32_t. This is about 24 days of msec.

The easiest solution is to use 64-bit unsigned integers... these don't overflow for over a half-billion years of msec, and can be compared directly.

@dcurrie
Copy link
Author

dcurrie commented Aug 14, 2016

Here's a unit test for my macros.
test_time_macros.c.txt

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

No branches or pull requests

2 participants