Enigma, & Fast, C-Style Monads w/ Dotty
I found this video of Tim Perrett building an Enigma machine with the State monad and lenses (code). Quite a bit more stylish than the one I built last year.
BUT, the trick of this post is that now with Dotty you can keep that State interface and have the monad compile
away entirely, leaving Int arithmetic and one tuple per keypress.
The three rotor positions fit in 5 bits each (feel free to read more about Enigma internals proper), so the whole machine state is one Int wrapped in an opaque type (SIP-35) so it can't be mixed up with any other Int:
opaque type Rotors = Int
object Rotors:
inline def apply(l: Int, m: Int, r: Int): Rotors =
(l << 10) | (m << 5) | r
extension (p: Rotors)
inline def left: Int = (p >>> 10) & 31
inline def mid: Int = (p >>> 5) & 31
inline def right: Int = p & 31
p.left reads like a case class field, but it's a shift and a mask.
Letters get the same treatment:
opaque type Letter = Int
object Letter:
inline def apply(c: Char): Letter = c - 'A'
extension (l: Letter)
inline def toChar: Char = ('A' + l).toChar
Then State itself: a plain alias, with flatMap + map as inline extensions taking inline params
type State[S, +A] = S => (S, A)
extension [S, A](inline st: State[S, A])
inline def flatMap[B](inline f: A => State[S, B]): State[S, B] =
s => { val (s1, a) = st(s); f(a)(s1) }
inline def map[B](inline f: A => B): State[S, B] =
s => { val (s1, a) = st(s); (s1, f(a)) }
A keypress steps the rotors, then sends the letter through them. press is inline too:
inline def press(inline c: Letter): State[Rotors, Letter] =
p =>
val p1 = step(p)
(p1, encipher(p1, c))
step and encipher are table lookups and modular arithmetic on Int's. You can find the tables on wikipedia or anywhere listing the different Enigma wheels/models the Germans used during the War.
With Dotty an inline def is always copied into its call site, or
compilation fails. inline parameters are pasted in as written, so the lambdas a for
comprehension desugars into end up applied directly, and the compiler beta-reduces them.
So you write this:
def hi(start: Rotors): (Rotors, String) =
(for
a <- press(Letter('H'))
b <- press(Letter('I'))
yield s"${a.toChar}${b.toChar}")(start)
…and javap on hi shows no closures and no Function1.apply. Each keypress is just:
invokevirtual Machine$.step:(I)I
invokestatic BoxesRunTime.boxToInteger
invokevirtual Machine$.encipher:(II)I
invokestatic BoxesRunTime.boxToInteger
invokevirtual Tuple2$.apply
invokevirtual Tuple2._1$mcI$sp:()I
invokevirtual Tuple2._2$mcI$sp:()I
Remaining are a Tuple2 and two boxed Integers per keypress, because (S, A) is generic.
So not 100% C-style.
One somewhat odd thing: State has to be a plain type alias. If we make it opqaue, the lambdas survive as real
closures (I checked). Rotors and Letter can stay opaque, since they're just Ints.
Some numbers. JMH, typing HELLOWORLD as a ten-step for comprehension, against the
same thing written as a case-class State, as cats.data.State, and as a plain while loop
with no monad at all:
| version | ns / word | bytes / word | vs inline |
|---|---|---|---|
inline State |
322 | 136 | 1.0x |
case class State |
409 | 1,328 | 1.3x |
cats.data.State |
1,076 | 5,144 | 3.3x |
while loop |
274 | 56 | 0.85x |
So within ~15% of the hand-written loop, with a tenth of the case class's allocations. The JIT's escape analysis removes most of those leftover tuples and boxes, but not all of them.
Nonetheless, cool right?