Add efficient bit-fields manipulations.
[apps/madmutt.git] / lib-lib / bits.c
diff --git a/lib-lib/bits.c b/lib-lib/bits.c
new file mode 100644 (file)
index 0000000..1cd09ef
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or (at
+ *  your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful, but
+ *  WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ *  MA 02110-1301, USA.
+ */
+/*
+ * Copyright © 2007 Pierre Habouzit
+ */
+
+#include "lib-lib.h"
+
+#define UPPER_32(x)  (((x) + 31) & ~31)
+#define LOWER_32(x)  ((x) & ~31)
+
+void bits_extend(bits_t *bits, int pos)
+{
+    if (bits->size == 0) {
+        bits->start = LOWER_32(pos >> 3);
+    }
+
+    if (pos >> 3 > bits->start + bits->size) {
+        int newsize = UPPER_32((pos >> 3) - bits->start + 1);
+        p_realloc(&bits->bits, bits->size = newsize);
+        return;
+    }
+
+    if (pos >> 3 < bits->start) {
+        unsigned char *tmp = bits->bits;
+        int prepend = LOWER_32(bits->start - (pos >> 3));
+
+        bits->bits   = p_new(unsigned char, bits->size + prepend);
+        memcpy(bits->bits + prepend, tmp, bits->size);
+        bits->size  += prepend;
+        bits->start -= prepend;
+        p_delete(&tmp);
+    }
+}