s LearnSqueak.com

DATA · REVERSIBLE REPRESENTATIONS

Run-length encoding: compress consecutive symbols

Build a native Squeak run-length encoder and decoder, step through repeated symbols, test round trips and discover when count pairs make data larger.

8 native experiments18 SUnit testsOriginal source kit

Install the complete native lab

A paint row, a monochrome scan line or a repeated symbol sequence can often be described by runs. Build and inspect a small reversible encoder, then use counterexamples to learn when it helps. This original Smalltalk implementation is about adjacency and representation, not the site’s Huffman coding tree.

  1. Use a copy of native Squeak 6.1 with its matching changes and sources files. This lab is not installed in the SqueakJS playground.
  2. Download run-length.st. In Squeak’s File List, select that file and choose fileIn. Do not paste chunk-format class source into a Workspace.
  3. Open a Workspace for the numbered commands. Keep a Browser beside it to read the methods. The file installs the complete model and view first; the steps explain the implementation and exercise its behavior.

Prerequisites: classes and objects, ordered collections and blocks and loops. New to testing? Read SUnit basics.

18 SUnit tests · Complete source kit

Keep the fixed-layout native window at least 980 × 620 pixels. Use Next experiment once per step after opening, or run the matching Workspace command. The replay starts from Reset. No timers, network access or file saving are used by the app; close its window when finished.

01 · Separate the input, cursor and runs

A run is a stretch of the same symbol with no different symbol in between. AAAABBBCCAAAA has four runs, not three: the final A letters do not touch the first A letters. Our model keeps a copied input String, a cursor saying how many letters have been consumed, and an OrderedCollection of pairs. Each pair stores a Character first and a positive Integer second. The picture is only a view of that model; it does not perform the encoding itself.

LSRLEEncoder method · read in Browser
resetOn: aString
 aString isString ifFalse: [self error: 'Use a String'].
 input := aString copy. cursor := 0. runs := OrderedCollection new.
 ^ self
Same Workspace · select and Do it
view := LSRLEView open.

Expected: The window shows 13 gray letters and no runs. The independent model query answers 0.

NATIVE SQUEAK CAPTURE
Native Squeak run-length encoding step 1: Separate the input, cursor and runs
Genuine Squeak Morphic window after experiment 1.
Separate model query · select the whole block and Print it
model := LSRLEEncoder new resetOn: 'AAB'.
model cursor

Read resetOn: in the Browser. copy prevents a caller from changing the model’s input later by editing the same mutable String. A cursor of zero means no character has been consumed; it is not a valid String index, because Squeak collections start at one. The first step increments the cursor before reading. The model example here is separate from view model, so it does not change the screenshot. Keep it in the same Workspace for steps 2–4.

02 · Start a run with the first character

step consumes exactly one character. Before it reads the input, finished prevents an out-of-bounds access. With no existing runs, the and: block is not evaluated, so runs last is never sent to an empty collection. That short-circuit behavior is essential. The false branch adds a fresh two-item Array using the brace syntax {letter. 1}. The Character $A and the String 'A' are different objects; this format deliberately uses the former.

LSRLEEncoder method · read in Browser
step
 | letter last |
 self finished ifTrue: [^ false].
 cursor := cursor + 1. letter := input at: cursor.
 (runs notEmpty and: [runs last first = letter])
  ifTrue: [last := runs last. last at: 2 put: last second + 1]
  ifFalse: [runs add: {letter. 1}].
 ^ true
Same Workspace · select and Do it
view next.

Expected: Only the first A cell turns blue. The independent query prints one pair: #(#($A 1)).

NATIVE SQUEAK CAPTURE
Native Squeak run-length encoding step 2: Start a run with the first character
Genuine Squeak Morphic window after experiment 2.
Separate model query · select the whole block and Print it
model step.
model runs

Follow the two return paths. A successful step answers true, while a call after the input ends answers false. Those Booleans let the finishing loop ask for another character without keeping its own cursor. Use Print it on the whole two-line model query if you want to see its final result; Do it executes without inserting the answer. Delete any inserted printed answer before re-running that code.

03 · Extend only the current run

The visual experiment takes three more successful steps. Each sees A equal to the symbol in the last pair, so it replaces that pair’s second element with the old count plus one. It does not add a new pair. A reference named last points to the existing Array, so at:put: updates the pair already held in runs. The public runs accessor will return copies to keep callers from accidentally breaking those counts.

LSRLEEncoder method · read in Browser
step
 | letter last |
 self finished ifTrue: [^ false].
 cursor := cursor + 1. letter := input at: cursor.
 (runs notEmpty and: [runs last first = letter])
  ifTrue: [last := runs last. last at: 2 put: last second + 1]
  ifFalse: [runs add: {letter. 1}].
 ^ true
Same Workspace · select and Do it
view next.

Expected: Four A cells are blue and the first run says A × 4. The independent three-letter model now answers #(#($A 2)).

NATIVE SQUEAK CAPTURE
Native Squeak run-length encoding step 3: Extend only the current run
Genuine Squeak Morphic window after experiment 3.
Separate model query · select the whole block and Print it
model step.
model runs

Notice why we compare with runs last first, not with every previous symbol. The algorithm groups adjacent values, rather than making a frequency table. A frequency dictionary for AABAA would report four As and one B and lose the original order. Our sequence must retain the separate A runs so the decoder can reproduce exactly what was given. Run-length encoding is lossless only when its representation preserves that ordering.

04 · Start a new pair at the boundary

A different letter closes the current run implicitly: we stop editing it and append a new pair. There is no separate final-run flush in this design, because the current run has been stored and updated from its first character onward. That choice makes stepping particularly easy to visualize. Other encoders hold a pending symbol and count and emit them only at a boundary; such implementations must remember to flush at end of input.

LSRLEEncoder method · read in Browser
runs
 ^ (runs collect: [:pair | pair copy]) asArray
Same Workspace · select and Do it
view next.

Expected: The first B becomes blue. The picture has A × 4 then B × 1; the independent query answers #(#($A 2) #($B 1)).

NATIVE SQUEAK CAPTURE
Native Squeak run-length encoding step 4: Start a new pair at the boundary
Genuine Squeak Morphic window after experiment 4.
Separate model query · select the whole block and Print it
model step.
model runs

Read the runs method. It copies each pair and then returns an Array of those copies. Copying only the outer collection would leave the inner pairs shared, allowing a caller to change a count behind the model’s back. Characters and Integers are safe values to share here. The unit tests deliberately mutate a returned pair and check that the model still decodes its original text.

05 · Finish the remaining input

finish repeatedly asks step for its Boolean result. When there are no characters left, step answers false without changing anything, and the loop ends. An empty input is already finished, so the same code naturally produces an empty Array. The class-side encode: convenience method constructs a model, resets it to the supplied text, and finishes it. It is useful when you want the result without opening a window.

LSRLEEncoder method · read in Browser
finish
 [self step] whileTrue.
 ^ self runs
Same Workspace · select and Do it
view next.

Expected: All 13 cells are blue. The answer contains A × 4, B × 3, C × 2, A × 4, in that order.

NATIVE SQUEAK CAPTURE
Native Squeak run-length encoding step 5: Finish the remaining input
Genuine Squeak Morphic window after experiment 5.
Separate model query · select the whole block and Print it
LSRLEEncoder encode: 'AAAABBBCCAAAA'

The cursor moves forward once per input character. With an amortized constant-time append to OrderedCollection, the encoder takes linear time in the number of input characters. It retains the input and the runs, so this implementation is not a streaming file compressor. Counts are ordinary Smalltalk Integers, not fixed eight-bit fields. Reading beyond the end is avoided, and another Next experiment after stage 8 is deliberately a no-op.

06 · Find when run-length encoding loses

Alternating symbols have no long stretches to collapse. Representing each as a symbol and count introduces more fields than there were input symbols. By contrast, the previous 13-letter input used four pairs, or eight fields. This is an explanation of representation structure, not a measurement of serialized bytes or Squeak memory. Arrays, collections, Characters, Integers and headers have costs; an actual file format also needs an agreed way to write them.

LSRLEEncoder method · read in Browser
finished
 ^ cursor = input size
Same Workspace · select and Do it
view next.

Expected: There are six input letters, six runs and twelve pair fields. The query answers 6.

NATIVE SQUEAK CAPTURE
Native Squeak run-length encoding step 6: Find when run-length encoding loses
Genuine Squeak Morphic window after experiment 6.
Separate model query · select the whole block and Print it
(LSRLEEncoder encode: 'ABABAB') size

Do not call eight fields an eight-byte compressed file. To compare real compression, first specify an encoding for symbols and counts, serialize both alternatives, and measure the actual output sizes. You might decide to store raw blocks when run encoding would grow them. For this lesson, keep the simpler invariant: one pair represents one consecutive stretch. Unlike the Huffman lesson, there is no frequency-derived code tree or variable-length bit code.

07 · Keep digits unambiguous

Writing A4B3 looks compact on a slide, but it is not our stored format. If source symbols can themselves be digits, a bare concatenated text format quickly becomes ambiguous. Explicit Arrays keep each Character separate from its count, so the digit-one Character $1 cannot be confused with the Integer 1. No string parser or escaping rule is needed for these in-memory pairs.

LSRLEEncoder class method · read in Browser
encode: aString
 ^ (self new resetOn: aString) finish
Same Workspace · select and Do it
view next.

Expected: The two pairs are #(#($1 3) #($2 2)), meaning three digit-one characters and two digit-two characters.

NATIVE SQUEAK CAPTURE
Native Squeak run-length encoding step 7: Keep digits unambiguous
Genuine Squeak Morphic window after experiment 7.
Separate model query · select the whole block and Print it
LSRLEEncoder encode: '11122'

The encoder is case-sensitive and preserves spaces. For example, AaA has three runs, not one. A production format would need to define the unit being repeated: bytes, Unicode code points, or grapheme clusters that people perceive as characters. Our model repeats Squeak Character values from a String. It makes no claims about Unicode normalization or visually equivalent text. You can inspect the returned arrays directly instead of guessing their structure from a compressed label.

08 · Decode and verify the round trip

Decoding traverses the ordered pairs and writes each Character count times into a String stream. Before allocating the expanded result, it checks pair shape, symbol type and a strictly positive Integer count. It also sums the requested output length and rejects anything over 10,000 characters. This explicit teaching limit helps prevent a tiny malformed or hostile input from asking the example to allocate an enormous String. It is not a general-purpose security boundary.

LSRLEEncoder class method · read in Browser
decode: pairs
 | total |
 total := 0.
 pairs do: [:pair |
  (pair isArray and: [pair size = 2])
   ifFalse: [self error: 'Each run needs {Character. positiveInteger}'].
  (pair first isCharacter and: [pair second isInteger and: [pair second > 0]])
   ifFalse: [self error: 'Invalid run symbol or count'].
  total := total + pair second.
  total > 10000 ifTrue: [self error: 'Teaching decoder limit: 10000 characters']].
 ^ String streamContents: [:stream |
  pairs do: [:pair | pair second timesRepeat: [stream nextPut: pair first]]]
Same Workspace · select and Do it
view next.

Expected: The answer is 'AAABCCCC'. The decoded line matches the complete input shown above it.

NATIVE SQUEAK CAPTURE
Native Squeak run-length encoding step 8: Decode and verify the round trip
Genuine Squeak Morphic window after experiment 8.
Separate model query · select the whole block and Print it
LSRLEEncoder decode: { {$A. 3}. {$B. 1}. {$C. 4} }

Encoding accepts longer strings, but this teaching decoder intentionally refuses expansions beyond its limit; keep round-trip exercises at or below 10,000 characters. It accepts adjacent equal-symbol pairs even though the encoder produces a canonical merged run: both still decode correctly. Validate any real file format before using it, including delimiters, truncation, counts and resource limits. The model does not read or write files, and these pairs are not compatible with ZIP, PNG or an external RLE codec.

Replay the eight native states

NATIVE SQUEAK CAPTURE
Run-length encoding before consuming its first character
Eight genuine native imageForm captures after the scripted lesson commands. This GIF is a sequence of actual application states, not a recording of mouse gestures.

Try your own small input

Same Workspace · select and Do it
view load: 'AABBAA'.

The view shows three runs: A × 2, B × 2, A × 2. Its custom-input helper accepts at most eight characters so even eight separate run cards fit in this fixed teaching window. The model itself has no eight-character input restriction. Reset returns the guided example to step 1. Longer model-only experiments belong in a Workspace or Inspector.

Same Workspace · select the whole block and Print it
pairs := LSRLEEncoder encode: 'AAABCCCC'.
LSRLEEncoder decode: pairs

Expected: 'AAABCCCC'. Then try the empty String and alternating uppercase/lowercase text. Predict the number of runs before executing. What changes if you reverse the input? The total number of runs stays the same, but their order reverses. Prove that with a test rather than relying only on a picture.

Run the checks and understand the limits

File in run-length-tests.st through the File List, then evaluate this expression with Print it:

Workspace · select and Print it
LSRLETest suite run

Expected: 18 tests, 18 passes, 0 failures and 0 errors. Tested in native Squeak 6.1 build 23976. The tests cover empty/single/repeated input, separated runs, alternation, digit symbols, round trips, stepping, reset, defensive copying, whitespace, malformed runs and the expansion limit. The distributed verification record also covers all eight view states and the printed queries. Tests are evidence for these cases, not proof of every possible input.

The decoder’s work is proportional to the expanded output size, plus the number of pairs. The encoder stores the input and result in memory. This is a teaching model, not a file codec, streaming implementation, benchmark or replacement for a compression library.

For background, MIT OpenCourseWare’s run-length tutorial illustrates ordered values and lengths. Our code, UI, examples and tests are original. Compare with Huffman coding, where symbol frequency determines a code, or explore the sprite editor and consider whether a row contains enough repetition to benefit from runs.