Add efficient bit-fields manipulations.
[apps/madmutt.git] / lib-lib / bits.h
diff --git a/lib-lib/bits.h b/lib-lib/bits.h
new file mode 100644 (file)
index 0000000..499189b
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ *  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
+ */
+
+#ifndef MUTT_LIB_LIB_BITS_H
+#define MUTT_LIB_LIB_BITS_H
+
+typedef struct bits_t {
+    int start;
+    int size;
+    unsigned char *bits;
+} bits_t;
+
+void bits_extend(bits_t *bits, int pos);
+
+DO_INIT(bits_t, bits);
+static inline void bits_wipe(bits_t *bits) {
+    p_delete(&bits->bits);
+}
+DO_NEW(bits_t, bits);
+DO_DELETE(bits_t, bits);
+
+static inline void bits_clear(bits_t *bits)
+{
+    bits_wipe(bits);
+    bits_init(bits);
+}
+
+static inline bool bit_isset(const bits_t *bits, int pos)
+{
+    int offs = (pos >> 3) - bits->start;
+    if (offs < 0 || offs > bits->size)
+        return false;
+
+    return (bits->bits[offs] & (1 << (pos & 7))) != 0;
+}
+
+static inline void bit_set(bits_t *bits, int pos)
+{
+    int offs = (pos >> 3) - bits->start;
+    if (offs < 0 || offs > bits->size) {
+        bits_extend(bits, pos);
+        offs = (pos >> 3) - bits->start;
+    }
+    bits->bits[offs] |= 1 << (pos & 7);
+}
+
+static inline void bit_clear(bits_t *bits, int pos)
+{
+    int offs = (pos >> 3) - bits->start;
+    if (offs < 0 || offs > bits->size)
+        return;
+    bits->bits[offs] &= ~(1 << (pos & 7));
+}
+
+static inline void bit_toggle(bits_t *bits, int pos)
+{
+    int offs = (pos >> 3) - bits->start;
+    if (offs < 0 || offs > bits->size) {
+        bits_extend(bits, pos);
+        offs = (pos >> 3) - bits->start;
+    }
+    bits->bits[offs] ^= 1 << (pos & 7);
+}
+
+
+#endif /* MUTT_LIB_LIB_BITS_H */