summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--doc/manual.rst1
-rw-r--r--doc/sets_fragment.txt37
2 files changed, 35 insertions, 3 deletions
diff --git a/doc/manual.rst b/doc/manual.rst
index d4d2aae91..d7d50d2aa 100644
--- a/doc/manual.rst
+++ b/doc/manual.rst
@@ -1126,6 +1126,7 @@ as ``MyEnum.value``:
   echo amb    # Error: Unclear whether it's MyEnum.amb or OtherEnum.amb
   echo MyEnum.amb # OK.
 
+To implement bit fields with enums see `Bit fields <#set-type-bit-fields>`_
 
 String type
 -----------
diff --git a/doc/sets_fragment.txt b/doc/sets_fragment.txt
index 7e53f15f1..e9cb4fa90 100644
--- a/doc/sets_fragment.txt
+++ b/doc/sets_fragment.txt
@@ -49,6 +49,37 @@ operation             meaning
 ``excl(A, elem)``     same as ``A = A - {elem}``
 ==================    ========================================================
 
-Sets are often used to define a type for the *flags* of a procedure. This is
-a much cleaner (and type safe) solution than just defining integer
-constants that should be ``or``'ed together.
+Bit fields
+~~~~~~~~~~
+
+Sets are often used to define a type for the *flags* of a procedure.
+This is a cleaner (and type safe) solution than defining integer
+constants that have to be ``or``'ed together.
+
+Enum, sets and casting can be used together as in:
+
+.. code-block:: nim
+
+  type
+    MyFlag* {.size: sizeof(cint).} = enum
+      A
+      B
+      C
+      D
+    MyFlags = set[MyFlag]
+
+  proc toNum(f: MyFlags): int = cast[cint](f)
+  proc toFlags(v: int): MyFlags = cast[MyFlags](v)
+
+  assert toNum({}) == 0
+  assert toNum({A}) == 1
+  assert toNum({D}) == 8
+  assert toNum({A, C}) == 5
+  assert toFlags(0) == {}
+  assert toFlags(7) == {A, B, C}
+
+Note how the set turns enum values into powers of 2.
+
+For interoperability with C see the `bitsize pragma <#implementation-specific-pragmas-bitsize-pragma>`_ instead.
+
+If using enums and sets with C, use distinct cint.