From: Explorer09 Date: Sun, 12 Feb 2017 11:59:52 +0000 (+0800) Subject: scanner: compute powers of two faster. X-Git-Tag: v2.6.4~27 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=c7a545ae0907c81cf52139dd391659586570f60c;p=flex scanner: compute powers of two faster. Replace the naive "for" loop in determining power of two with a clever bitwise solution. This code is around the Internet already and is in Public Domain. --- diff --git a/src/dfa.c b/src/dfa.c index 0fcc5b3..ab10314 100644 --- a/src/dfa.c +++ b/src/dfa.c @@ -463,14 +463,9 @@ void ntod (void) /* We still may want to use the table if numecs * is a power of 2. */ - int power_of_two; - - for (power_of_two = 1; power_of_two <= csize; - power_of_two *= 2) - if (numecs == power_of_two) { - use_NUL_table = true; - break; - } + if (numecs <= csize && is_power_of_2(numecs)) { + use_NUL_table = true; + } } if (use_NUL_table) diff --git a/src/flexdef.h b/src/flexdef.h index 97aec14..e5ab8e0 100644 --- a/src/flexdef.h +++ b/src/flexdef.h @@ -109,6 +109,8 @@ #define ABS(x) ((x) < 0 ? -(x) : (x)) #endif +/* Whether an integer is a power of two */ +#define is_power_of_2(n) ((n) > 0 && ((n) & ((n) - 1)) == 0) #define unspecified -1