s LearnSqueak.com

DATA REPRESENTATION · BOUNDED SETS

Integer bitsets: store a small set in a number

Build bounded bitsets in Squeak Smalltalk: represent membership, combine sets, mask complements, validate slots and test the result against ordinary collections.

8 Workspace checkpoints1311 native assertionsNative set-operation replay

Before you start

Open a Workspace in native Squeak 6.1. Select each complete expression, including the temporary variables between vertical bars, and choose Print it. The eight checkpoints are independent: they repeat their own inputs so that you can run one without the previous steps. Do not concatenate the checkpoint file or file it in as a package.

Review blocks, collections and Booleans first if these are unfamiliar. A bitset represents membership in a known universe; it is not a list with duplicates, a Dictionary with arbitrary keys, or a security permission system.

Download the eight checkpoint expressions, the standalone assertion expression, or the complete source kit. Nothing accesses the network or changes saved application data. The visual replay below is native-only, not a new SqueakJS playground mode.

01 · Give every member a bit

Suppose a tiny scheduling board has eight numbered slots, 0 through 7. A set answers which slots are occupied, not how many times each slot was added. Assign slot zero the value 1, slot one the value 2, slot two the value 4, and so on. A left shift creates one selected bit. Our domain uses zero-based slot numbers deliberately; this does not change Smalltalk array indexing, which starts at one.

Independent Workspace expression · select all, then Print it
| slots |
slots := (0 to: 7) collect: [:slot | 1 bitShift: slot].
slots asArray

Check: Print it should show eight powers of two. The leftmost array entry describes slot zero. A bitset value of zero means the empty set, not a set containing slot zero.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 1: Give every member a bit, with evaluated result highlighted
Genuine Squeak Workspace after Print it. Blue selected text is the evaluated result.

02 · Add members without counting duplicates

Start from zero, then combine each one-bit mask with bitOr:. Setting a bit that is already set leaves it set. This is why adding the same member twice does not increase its weight. Adding numeric masks with + would be wrong when duplicates occur: two copies of 1 carry into the next bit. Integer operations return a new value, so assign the result back to the variable.

Independent Workspace expression · select all, then Print it
| occupied |
occupied := 0.
#(1 3 5 3) do: [:slot |
 occupied := occupied bitOr: (1 bitShift: slot)].
occupied

Check: Expect 42, meaning slots 1, 3 and 5. Slot 3 occurs twice in the input but only once in the represented set.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 2: Add members without counting duplicates, with evaluated result highlighted
Genuine Squeak Workspace after Print it. Blue selected text is the evaluated result.

03 · Ask whether a slot is present

bitAnd: preserves only bits present in both operands. Intersecting a bitset with a one-bit mask produces that mask if the member exists and zero otherwise. Compare with zero to obtain a Boolean. For display, enumerate the bounded universe and select the occupied slots. This scan is a convenient decoder, not a claim that membership itself requires scanning all slots.

Independent Workspace expression · select all, then Print it
| occupied hasSlot members |
occupied := 42.
hasSlot := [:slot |
 (occupied bitAnd: (1 bitShift: slot)) ~= 0].
members := (0 to: 7) select: hasSlot.
{hasSlot value: 3. hasSlot value: 2. members asArray}

Check: Expect true for slot 3, false for slot 2 and the decoded members #(1 3 5). Later we add bounds checks before accepting a caller-supplied slot.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 3: Ask whether a slot is present, with evaluated result highlighted
Genuine Squeak Workspace after Print it. Blue selected text is the evaluated result.

04 · Combine two sets

Use bitOr: for union and bitAnd: for intersection. XOR, written bitXor:, keeps members that appear in exactly one operand: the symmetric difference. It is not ordinary subtraction. Here A occupies slots 1, 3, 5 and B occupies 3, 4, 5. Their overlap is 3 and 5. Decode every result rather than trying to infer a set solely from its decimal representation.

Independent Workspace expression · select all, then Print it
| a b decode |
a := 42. b := 56.
decode := [:bits |
 ((0 to: 7) select: [:slot |
  (bits bitAnd: (1 bitShift: slot)) ~= 0]) asArray].
{decode value: (a bitOr: b).
 decode value: (a bitAnd: b).
 decode value: (a bitXor: b)}

Check: The three results are union #(1 3 4 5), intersection #(3 5) and symmetric difference #(1 4). XOR toggles overlapping bits off; OR does not.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 4: Combine two sets, with evaluated result highlighted
Genuine Squeak Workspace after Print it. Blue selected text is the evaluated result.

Watch set operations change the cells

NATIVE SQUEAK CAPTURE
Native Squeak eight-slot board showing slots 1, 3 and 5 selected in green
Four genuine native Morphic states replay A, union, intersection and the bounded complement. This is a captured-state animation, not mouse footage.

The display orders slot numbers from 0 on the left to 7 on the right to match a scheduling board. This is the reverse of the usual written binary-digit order; labels and powers of two make that convention explicit. Download the complete visual expression, open as text, select all and Do it. Change stage := 0. to 1, 2 or 3, and close the old window before opening the next. The fixed-layout window uses 1000 × 410 pixels, with no timer or background process.

05 · Define the universe before complementing

A complement needs a universe: which members are even allowed? For eight slots, shift 1 by eight then subtract 1 to obtain 255, whose eight low bits are set. XOR with this full mask gives the bounded complement when the input is already a valid subset. Squeak also has bitInvert, but applying it without a width mask produces a negative integer rather than the desired eight-slot set. Keep values nonnegative and explicitly bounded throughout this lesson.

Independent Workspace expression · select all, then Print it
| width full occupied free alsoFree |
width := 8.
full := (1 bitShift: width) - 1.
occupied := 42.
free := full bitXor: occupied.
alsoFree := occupied bitInvert bitAnd: full.
{full. free. free = alsoFree}

Check: Expect #(255 213 true). Free slots are 0, 2, 4, 6 and 7. Do not drop the bitAnd: full when using bitInvert.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 5: Define the universe before complementing, with evaluated result highlighted
Genuine Squeak Workspace after Print it. Blue selected text is the evaluated result.

06 · Remove members and subtract another set

To remove one member, AND with its bounded complement. Removing an absent member leaves the set unchanged. The same recipe computes A minus B by clearing every bit selected in B. Using XOR directly with B would toggle absent members on, so it is not a removal operation. These operations retain the invariant that every result lies between zero and the full universe mask.

Independent Workspace expression · select all, then Print it
| full a b withoutThree difference unchanged |
full := 255. a := 42. b := 56.
withoutThree := a bitAnd: (full bitXor: (1 bitShift: 3)).
difference := a bitAnd: (full bitXor: b).
unchanged := a bitAnd: (full bitXor: (1 bitShift: 2)).
{withoutThree. difference. unchanged = a}

Check: Expect #(34 2 true): removing slot 3 leaves slots 1 and 5; A minus B leaves only slot 1; removing the absent slot 2 changes nothing.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 6: Remove members and subtract another set, with evaluated result highlighted
Genuine Squeak Workspace after Print it. Blue selected text is the evaluated result.

07 · Guard the boundary before shifting

Shifting is a numeric operation, not an application-level bounds check. A negative slot could shift right instead of identifying a valid member. A huge positive index could allocate a large integer unnecessarily. Define a deliberately modest API limit, here widths 1 through 256, and reject fractional or out-of-range slots before constructing a mask. This limit is our application contract, not a Squeak integer limit.

Independent Workspace expression · select all, then Print it
| maskFor rejected |
maskFor := [:slot :width |
 ((width isInteger and: [width between: 1 and: 256])
  and: [slot isInteger and: [slot between: 0 and: width - 1]])
 ifFalse: [Error signal: 'Expected an integer slot inside width 1..256'].
 1 bitShift: slot].
rejected := [maskFor value: 8 value: 8. false]
 on: Error do: [:error | true].
{maskFor value: 7 value: 8. rejected}

Check: Expect #(128 true). Slot 7 is the highest valid slot in width 8. The code catches Error solely to demonstrate rejection; a real UI should show a useful validation message.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 7: Guard the boundary before shifting, with evaluated result highlighted
Genuine Squeak Workspace after Print it. Blue selected text is the evaluated result.

08 · Validate whole bitsets and keep the width

If an API accepts an already encoded integer, validate that value too. Requiring an integer in 0..full rejects negative values and bits beyond the chosen universe. Do not silently truncate invalid input unless that is the documented contract. A bitset value does not carry its own width: store or pass the universe size with it. This example also demonstrates a slot beyond the ordinary machine-word boundary without assuming a particular tagged-integer layout.

Independent Workspace expression · select all, then Print it
| width full valid high |
width := 80. full := (1 bitShift: width) - 1.
valid := [:bits | bits isInteger and: [bits between: 0 and: full]].
high := 1 bitShift: 79.
{valid value: high. valid value: -1.
 valid value: (1 bitShift: 80).
 (high bitAnd: high) = high}

Check: Expect #(true false false true). Width 80 is supported here, but larger integers can cost more memory and work. Do not describe these operations as constant-time for arbitrarily large universes.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 8: Validate whole bitsets and keep the width, with evaluated result highlighted
Genuine Squeak Workspace after Print it. Blue selected text is the evaluated result.

Check against an ordinary collection model

The downloadable test expression runs all eight published checkpoints, then checks every pair of four-slot bitsets: 16 × 16 input pairs. An independently expressed collection model uses includes:, select: and reject: to define union, intersection, symmetric difference and subtraction. Each integer operation is decoded and compared with that model. Every four-slot bitset also round-trips through decode and encode. Boundary tests reject invalid slots and widths, and accept the top slot of width 256.

Open the test file as text, select the entire expression and Print it. Expect 1311, the number of successful assertions. A failure signals Error. These are direct assertions rather than a claimed SUnit suite. The small exhaustive universe is deliberate: it covers all combinations cheaply while the large-width boundary checks exercise integer growth separately.

When a bitset helps, and when it does not

Bitsets are useful when identifiers already map to compact slots: selected days, a small board, a fixed group of flags, or a dense bounded membership table. Combining whole sets becomes a bitwise operation. You still need a separate stable mapping from names to slots. Changing that mapping after saving a mask would change its meaning, so serialize the width and mapping version with application data.

A huge mostly empty universe wastes bits. An ordinary Set is often clearer for sparse arbitrary objects, while a Dictionary is more appropriate for associated values. Integer bitsets do not record multiplicity, order or insertion history. Clearing one bit discards membership entirely; it cannot represent decrementing a count.

Do not promise constant-time operations for arbitrarily large integers, or claim a speed advantage without measuring representative workloads. This tutorial scans the entire width when decoding for display. That is linear in the universe size and is separate from the bitwise operation itself. Consider the existing measurement workshop before optimizing an application.

Extend the model carefully

  1. Use width seven for weekdays. Keep zero-based slot numbers internally, but map them to weekday names for display. Verify that the full set decodes to all seven names.
  2. Write a subset check by comparing a bitAnd: b with a. Test the empty set, equal sets and a counterexample. Validate both operands against the same universe first.
  3. Wrap the integer and width in a small class, exposing add, remove and includes operations. Add SUnit tests for invalid input before connecting it to Morphic controls.

The central invariant is simple: each stored mask is an integer between zero and the full universe mask. Enforce it at public boundaries rather than scattering defensive truncation throughout the code. Continue with classes, SUnit or the Eight Queens visualizer for applications of compact state.

Sources and verification

The official Squeak Terse Guide, Bitwise Manipulation lists the integer messages used here. Source reviewed 27 October 2026. Our bounded-universe convention, scheduling examples, collection oracle and native visual board are original; all published expressions were evaluated in Squeak 6.1 build 23976. The screenshots show that runtime, not a different Smalltalk dialect.

Use the Browser to inspect Integer and its subclasses when investigating implementation details. Keep this lesson’s zero-based slot convention distinct from any method’s own indexing contract; our code constructs masks with shifts rather than relying on bitAt: indexing.