omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / bacon-cipher / bacon-cipher.om
| 1 | note Rosetta Code task "Bacon cipher": https://rosettacode.org/wiki/Bacon_cipher |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text secret "rosetta code" |
| 6 | text cover "bacon's cipher is a method of steganography devised by francis bacon. a message is concealed in the presentation of text rather than its content." |
| 7 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 8 | fn emit a view uchar * to void |
| 9 | o = ulong 0 |
| 10 | while lt o len a bound 4096 |
| 11 | k = write 1 a o sub len a o |
| 12 | if le k 0 |
| 13 | exit 1 |
| 14 | end |
| 15 | o = add o ulong k |
| 16 | end |
| 17 | end |
| 18 | note emitc writes one byte |
| 19 | fn emitc c uchar to void |
| 20 | b = new uchar 1 0 |
| 21 | put b 0 c |
| 22 | emit b |
| 23 | end |
| 24 | note 26-letter variant: letter n (a = 0) is 5 bits, most significant first; a space is 26 (11010). |
| 25 | note The bits ride on the cover text's letters: 0 lower case, 1 upper case; other bytes are copied, |
| 26 | note letters after the last bit stay lower case. Decoding reads the case of the letters 5 at a time. |
| 27 | fn code c uchar to ulong |
| 28 | if eq c 32 |
| 29 | ret 26 |
| 30 | end |
| 31 | ret ulong sub c 97 |
| 32 | end |
| 33 | fn isl c uchar to bool |
| 34 | ret and ge c 97 le c 122 |
| 35 | end |
| 36 | fn enc o edit uchar * to void |
| 37 | nb = mul len secret 5 |
| 38 | b = ulong 0 |
| 39 | for i ulong len cover |
| 40 | c = get cover i |
| 41 | if and isl c lt b nb |
| 42 | v = code get secret div b 5 |
| 43 | if eq and shr v sub 4 rem b 5 1 1 |
| 44 | c = sub c 32 |
| 45 | end |
| 46 | b = add b 1 |
| 47 | end |
| 48 | put o i c |
| 49 | end |
| 50 | end |
| 51 | fn dec e view uchar * n ulong to void |
| 52 | v = ulong 0 |
| 53 | k = ulong 0 |
| 54 | m = ulong 0 |
| 55 | for i ulong len e |
| 56 | c = get e i |
| 57 | if and lt m n or isl c and ge c 65 le c 90 |
| 58 | v = shl v 1 |
| 59 | if le c 90 |
| 60 | v = or v 1 |
| 61 | end |
| 62 | k = add k 1 |
| 63 | if eq k 5 |
| 64 | if eq v 26 |
| 65 | emitc 32 |
| 66 | else |
| 67 | emitc add uchar v 97 |
| 68 | end |
| 69 | v = 0 |
| 70 | k = 0 |
| 71 | m = add m 1 |
| 72 | end |
| 73 | end |
| 74 | end |
| 75 | emit nl |
| 76 | end |
| 77 | fn main to int |
| 78 | o = new uchar 256 0 |
| 79 | n = len cover |
| 80 | enc part o 0 n |
| 81 | emit part o 0 n |
| 82 | emit nl |
| 83 | dec part o 0 n len secret |
| 84 | ret 0 |
| 85 | end |