]> granicus.if.org Git - flex/commitdiff
scanner: compute powers of two faster.
authorExplorer09 <explorer09@gmail.com>
Sun, 12 Feb 2017 11:59:52 +0000 (19:59 +0800)
committerWill Estes <westes575@gmail.com>
Thu, 16 Feb 2017 18:26:21 +0000 (13:26 -0500)
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.

src/dfa.c
src/flexdef.h

index 0fcc5b33ead029dd97f33f9a01a5ce213b5844cb..ab103143c0f07fb16646818604626ac547c214c2 100644 (file)
--- 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)
index 97aec14a24b8d9f532087a3f993fb11212d4cf82..e5ab8e025127cbeb2b951ed262157b7d0620d186 100644 (file)
 #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