Skip to content

Commit 40eabfa

Browse files
committed
Added codec: cow
1 parent 5ea0098 commit 40eabfa

6 files changed

Lines changed: 205 additions & 4 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
392392
#### [Esoteric](https://python-codext.readthedocs.io/en/latest/enc/esoteric.html)
393393

394394
- [X] `brainfuck`: well-known esoteric programming language (encoding generates a program printing the text)
395+
- [X] `cow`: esoteric language made of variations of "moo" (Brainfuck-like, with a register and integer output)
395396
- [X] `ook`: Brainfuck derivative for orang-utans (`Ook.`, `Ook?` and `Ook!`), also in its short form
396397
- [X] `pikalang`: Brainfuck derivative using Pikachu's vocabulary
397398

‎docs/pages/enc/esoteric.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,23 @@
2121

2222
-----
2323

24+
### COW
25+
26+
COW is made of 12 variations of the word "moo". Its memory is a tape of integer cells with a register, and its instructions include those of Brainfuck (`MoO`, `MOo`, `moO`, `mOo`, `MOO`, `moo`, `Moo`), plus integer output and input (`OOM`, `oom`), reset (`OOO`), copy and paste through the register (`MMM`) and the execution of the value of the cell as an instruction (`mOO`). Programs are run as with the reference interpreter, including the quirks of its loops: when searching for their match, `MOO` skips the instruction that follows it and `moo` the one that precedes it.
27+
28+
**Codec** | **Conversions** | **Aliases** | **Comment**
29+
:---: | :---: | --- | ---
30+
`cow` | text <-> COW program | | instructions are case-sensitive ; whitespace ignored ; other characters (comments) only accepted with a non-strict errors handling ; programs that do not halt within 1000 steps per instruction (with a minimum of 1 million) are stopped
31+
32+
```python
33+
>>> codext.encode("A", "cow")
34+
'moO MoO MoO MoO MoO MoO MoO MoO MoO MOO mOo MoO MoO MoO MoO MoO MoO MoO MoO moO MOo moo mOo MoO Moo'
35+
>>> codext.decode("MoO MoO MOO MOo moO MoO mOo moo moO OOM", "cow")
36+
'2\n'
37+
```
38+
39+
-----
40+
2441
### Ook!
2542

2643
[Ook!](https://www.dangermouse.net/esoteric/ook.html) is an esoteric programming language derived from Brainfuck, designed to be read and written by orang-utans: each Brainfuck command is a pair of the words `Ook.`, `Ook?` and `Ook!` (e.g. `Ook. Ook?` for `>` and `Ook! Ook.` for `.`). Short Ook! only keeps the punctuation marks (e.g. `.?` for `>`). Encoding generates a program that prints the text (as UTF-8), while decoding runs the program (with 8-bit cells and no input) and returns its output.

‎src/codext/esoteric/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# -*- coding: UTF-8 -*-
22
from .brainfuck import *
3+
from .cow import *
34
from .ook import *
45
from .pikalang import *

‎src/codext/esoteric/_brainfuck.py‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# -*- coding: UTF-8 -*-
2-
"""Brainfuck core, shared by the codecs of Brainfuck and of the esoteric languages derived from it (e.g. Pikalang).
2+
"""Brainfuck core, shared by the codecs of Brainfuck and of the esoteric languages derived from it (e.g. Pikalang,
3+
COW).
34
45
Brainfuck works on a tape of 8-bit cells (wrapping around) with a data pointer, using 8 commands: "+" and "-"
56
(increment and decrement the cell), ">" and "<" (move the pointer), "[" and "]" (loop while the cell is not null), "."
@@ -10,12 +11,19 @@
1011
MIN_STEPS, STEPS_PER_COMMAND = 10 ** 6, 1000
1112

1213

13-
def bf_program(data):
14+
def bf_program(data, nonzero=False):
1415
""" Generate a Brainfuck program that prints the given bytes. It uses the first cell for the output and, for large
15-
differences between successive bytes, the second one as the counter of a multiplication loop. """
16+
differences between successive bytes, the second one as the counter of a multiplication loop.
17+
18+
:param data: bytes to be printed
19+
:param nonzero: for languages whose cells are not reduced modulo 256 and that cannot print a null cell (e.g. COW),
20+
the first cell is kept away from 0 (a null byte being printed from 256 or -256)
21+
"""
1622
code, v = [], 0
1723
for t in data:
1824
d = (t - v + 128) % 256 - 128
25+
if nonzero and v + d == 0:
26+
d += 256 if d <= 0 else -256
1927
op, n = "+-"[d < 0], abs(d)
2028
# either add the difference directly, or as a * b + c with a loop of a iterations adding b
2129
best = op * n
@@ -26,7 +34,7 @@ def bf_program(data):
2634
if b > 0 and a + b + abs(c) + 7 < len(best):
2735
best = ">" + "+" * a + "[<" + op * b + ">-]<" + ("+-"[(op == "-") != (c < 0)]) * abs(c)
2836
code.append(best + ".")
29-
v = t
37+
v = v + d if nonzero else t
3038
return "".join(code)
3139

3240

‎src/codext/esoteric/cow.py‎

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
# -*- coding: UTF-8 -*-
2+
"""COW Codec - COW content encoding.
3+
4+
COW is an esoteric programming language created by Sean Heber in 2003, made of 12 variations of the word "moo". Its
5+
memory is a tape of integer cells, as in Brainfuck, with a register, and its instructions are: "MoO" and "MOo"
6+
(increment and decrement the cell), "moO" and "mOo" (move the pointer), "MOO" and "moo" (loop while the cell is not
7+
null), "Moo" (print the cell as a character, or read a character when it is null), "OOM" and "oom" (print or read the
8+
cell as an integer), "OOO" (reset the cell), "MMM" (copy the cell to the register, or the register to the cell) and
9+
"mOO" (execute the value of the cell as an instruction, 3 or an invalid one ending the program). Encoding generates a
10+
program that prints the text (as UTF-8), while decoding runs the program and returns its output.
11+
12+
The program is run as with the reference interpreter, including the quirks of its loops ("MOO" skips the instruction
13+
that follows it, "moo" the one that precedes it, when searching for their match). No input is available, cells being
14+
left unchanged by "Moo" and set to 0 by "oom". When decoding, instructions may be separated by whitespace ; other
15+
characters, ignored by the language as comments, are only accepted with a non-strict errors handling. A program that
16+
does not halt within 1000 steps per instruction (with a minimum of 1 million) is stopped.
17+
18+
This codec:
19+
- en/decodes strings from str to str
20+
- en/decodes strings from bytes to bytes
21+
- decodes file content to str (read)
22+
- encodes file content from str to bytes (write)
23+
24+
Reference: https://bigzaphod.github.io/COW/
25+
"""
26+
from ._brainfuck import *
27+
from ..__common__ import *
28+
29+
30+
__examples__ = {
31+
'enc(cow)': {'': "", 'A': "moO MoO MoO MoO MoO MoO MoO MoO MoO MOO mOo MoO MoO MoO MoO MoO MoO MoO MoO moO MOo "
32+
"moo mOo MoO Moo"},
33+
'dec(cow)': {
34+
'MoO OOM': "1\n",
35+
'MoO\nMMM moO MMM OOM': "1\n",
36+
'MoO MoO MOO MOo moO MoO mOo moo moO OOM': "2\n",
37+
# "MOO" skips the instruction that follows it, hence matching the second "moo"
38+
'OOO MOO moo moo MoO OOM': "1\n",
39+
'MOO MoO MOO MoO moo moo MoO OOM': "1\n",
40+
# a "moo" right after a "MOO" counts twice when searching forward
41+
'MOO MoO MOO moo MoO OOM': "1\n",
42+
'MoO MoO MoO MoO MoO MoO mOO OOM': "7\n",
43+
'MoO MoO MoO mOO OOM': "",
44+
'OOO MOo mOO OOM': "",
45+
'Moo oom OOM': "0\n",
46+
'MOO': "",
47+
'mOo': None,
48+
'moo': None,
49+
'MoO moo': None,
50+
'MOO MoO': None,
51+
'MoO OOM moo!': None,
52+
},
53+
'enc-dec(cow)': ["", "Hello World!", "@random{256}", "Café, ñandú & 10€", "\x00a\x00"],
54+
}
55+
__guess__ = ["cow"]
56+
57+
58+
COW = ["moo", "mOo", "moO", "mOO", "Moo", "MOo", "MoO", "MOO", "OOO", "MMM", "OOM", "oom"]
59+
CODES = {w: i for i, w in enumerate(COW)}
60+
# Brainfuck commands as COW instructions (without input, as "Moo" with a null cell reads a character)
61+
BF2COW = {'+': "MoO", '-': "MOo", '>': "moO", '<': "mOo", '.': "Moo", '[': "MOO", ']': "moo"}
62+
63+
64+
def cow_run(program, max_steps=None):
65+
""" Run a COW program (as a list of instruction codes) like the reference interpreter and return its output as
66+
bytes with the index of the failing instruction (None if the program ended normally). """
67+
mem, p, pc, reg, out, steps, n = [0], 0, 0, None, bytearray(), 0, len(program)
68+
max_steps = max_steps or max(MIN_STEPS, STEPS_PER_COMMAND * n)
69+
while pc < n:
70+
if (steps := steps + 1) > max_steps:
71+
raise ValueError(f"program did not halt within {max_steps} steps")
72+
i = program[pc]
73+
# mOO executes the value of the cell, 3 (itself) or an invalid instruction ending the program
74+
if i == 3:
75+
if mem[p] == 3 or mem[p] not in range(12):
76+
break
77+
i = mem[p]
78+
if i == 0:
79+
# moo searches backward for its MOO, skipping the previous instruction, then executes it
80+
if pc == 0:
81+
return bytes(out), pc
82+
q, level = pc - 1, 1
83+
while level > 0 and q > 0:
84+
q -= 1
85+
level += (program[q] == 0) - (program[q] == 7)
86+
if level != 0:
87+
return bytes(out), pc
88+
pc, i = q, 7
89+
if i == 1:
90+
if p == 0:
91+
return bytes(out), pc
92+
p -= 1
93+
elif i == 2:
94+
if (p := p + 1) == len(mem):
95+
mem.append(0)
96+
elif i == 4:
97+
# without input, a null cell is left unchanged
98+
if mem[p] != 0:
99+
out.append(mem[p] & 0xff)
100+
elif i == 5:
101+
mem[p] -= 1
102+
elif i == 6:
103+
mem[p] += 1
104+
elif i == 7 and mem[p] == 0:
105+
# MOO searches forward for its moo, skipping the next instruction ; a moo right after a MOO counts twice
106+
q, level = pc + 1, 1
107+
if q == n:
108+
break
109+
while level > 0:
110+
prev, q = program[q], q + 1
111+
if q == n:
112+
break
113+
if program[q] == 7:
114+
level += 1
115+
elif program[q] == 0:
116+
level -= 1 + (prev == 7)
117+
if level != 0:
118+
return bytes(out), pc
119+
pc = q
120+
elif i == 8:
121+
mem[p] = 0
122+
elif i == 9:
123+
if reg is None:
124+
reg = mem[p]
125+
else:
126+
mem[p], reg = reg, None
127+
elif i == 10:
128+
out.extend(f"{mem[p]}\n".encode())
129+
elif i == 11:
130+
# without input, the integer read is 0
131+
mem[p] = 0
132+
pc += 1
133+
return bytes(out), None
134+
135+
136+
def cow_encode(text, errors="strict"):
137+
return (r := " ".join(BF2COW[c] for c in bf_program(text.encode("utf-8"), True))), len(r)
138+
139+
140+
def cow_decode(text, errors="strict"):
141+
_h, program, pos, i = handle_error("cow", errors, decode=True), [], [], 0
142+
while i < len(text):
143+
if text[i].isspace():
144+
i += 1
145+
elif (w := text[i:i+3]) in CODES:
146+
program.append(CODES[w])
147+
pos.append(i)
148+
i += 3
149+
else:
150+
# with a non-strict errors handling, other characters are ignored (as comments)
151+
_h(text[i], i)
152+
i += 1
153+
out, k = cow_run(program)
154+
if k is not None:
155+
# with a non-strict errors handling, the program stops at the failing instruction
156+
handle_error("cow", errors, decode=True, kind="instruction")(COW[program[k]], pos[k])
157+
return (r := ensure_str(out)), len(r)
158+
159+
160+
add("cow", cow_encode, cow_decode, r"^cow$", printables_rate=1., expansion_factor=(40., .05))

‎tests/test_manual.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,20 @@ def test_codec_binhex(self):
2424
self.assertEqual(codecs.decode("This is a test", "binhex", "ignore"), "")
2525
self.assertEqual(codecs.decode(":N!8:", "binhex", "ignore"), "")
2626

27+
def test_codec_cow(self):
28+
# with a non-strict errors handling, other characters are comments and the program stops at a failing
29+
# instruction
30+
for e in ["ignore", "replace", "leave"]:
31+
self.assertEqual(codecs.decode("Comment: MoO OOM then moo OOM", "cow", e), "1\n")
32+
self.assertEqual(codecs.decode("MoO Moo mOo Moo", "cow", e), "\x01")
33+
self.assertRaises(ValueError, codecs.decode, "MoO OOM comment", "cow")
34+
self.assertRaises(ValueError, codecs.decode, "MoO OOM comment", "cow", "BAD_ERRORS")
35+
from codext.esoteric.cow import cow_run
36+
# "MOO" with a non-null cell continues, then "moo" goes back to it forever (it skips the previous instruction,
37+
# hence the "MMM" in the loop)
38+
self.assertRaises(ValueError, cow_run, [6, 7, 9, 0], max_steps=100)
39+
self.assertEqual(cow_run([6, 10, 4], max_steps=100), (b"1\n\x01", None))
40+
2741
def test_codec_dna(self):
2842
self.assertEqual(codecs.decode("ABC", "dna-1", errors="ignore"), "\x02")
2943
self.assertEqual(codecs.decode("ABC", "dna-2", errors="replace"), "[00??01]")

0 commit comments

Comments
 (0)