omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / substitution-cipher / substitution-cipher.om
| 1 | note Rosetta Code task "Substitution cipher": https://rosettacode.org/wiki/Substitution_cipher |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | note key: plain letter a..z maps to the letter at the same place here |
| 6 | text key "phqgiumeaylnofdxjkrcvstzwb" |
| 7 | text msg "the quick brown fox jumps over the lazy dog, 42 times" |
| 8 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 9 | fn emit a view uchar * to void |
| 10 | o = ulong 0 |
| 11 | while lt o len a bound 4096 |
| 12 | k = write 1 a o sub len a o |
| 13 | if le k 0 |
| 14 | exit 1 |
| 15 | end |
| 16 | o = add o ulong k |
| 17 | end |
| 18 | end |
| 19 | note enc maps each lower-case letter through key; other bytes are copied |
| 20 | fn enc a view uchar * r edit uchar * to void |
| 21 | for i ulong len a |
| 22 | c = get a i |
| 23 | if and ge c 97 le c 122 |
| 24 | c = get key sub c 97 |
| 25 | end |
| 26 | put r i c |
| 27 | end |
| 28 | end |
| 29 | note dec builds the inverse table first, then maps through it |
| 30 | fn dec a view uchar * r edit uchar * to void |
| 31 | inv = new uchar 26 0 |
| 32 | for j ulong 26 |
| 33 | put inv sub get key j 97 add uchar j 97 |
| 34 | end |
| 35 | for i ulong len a |
| 36 | c = get a i |
| 37 | if and ge c 97 le c 122 |
| 38 | c = get inv sub c 97 |
| 39 | end |
| 40 | put r i c |
| 41 | end |
| 42 | end |
| 43 | fn main to int |
| 44 | n = len msg |
| 45 | e = new uchar 256 0 |
| 46 | d = new uchar 256 0 |
| 47 | emit msg |
| 48 | emit nl |
| 49 | enc msg part e 0 n |
| 50 | emit part e 0 n |
| 51 | emit nl |
| 52 | dec part e 0 n part d 0 n |
| 53 | emit part d 0 n |
| 54 | emit nl |
| 55 | ret 0 |
| 56 | end |