omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / string-matching / string-matching.om
| 1 | note Rosetta Code task "String matching": https://rosettacode.org/wiki/String_matching |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text hay "tacoloco" |
| 7 | text nd "co" |
| 8 | text tst "starts with: " |
| 9 | text tct "found at:" |
| 10 | text ten "ends with: " |
| 11 | text tyes "yes" |
| 12 | text tno "no" |
| 13 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 14 | fn emit a view uchar * to void |
| 15 | o = ulong 0 |
| 16 | while lt o len a bound 4096 |
| 17 | k = write 1 a o sub len a o |
| 18 | if le k 0 |
| 19 | exit 1 |
| 20 | end |
| 21 | o = add o ulong k |
| 22 | end |
| 23 | end |
| 24 | note emitu writes n in decimal; 20 digits hold every ulong |
| 25 | fn emitu n ulong to void |
| 26 | d = new uchar 20 0 |
| 27 | i = ulong 20 |
| 28 | v = n |
| 29 | while true bound 20 |
| 30 | i = sub i 1 |
| 31 | put d i uchar add rem v 10 48 |
| 32 | v = div v 10 |
| 33 | if eq v 0 |
| 34 | break |
| 35 | end |
| 36 | end |
| 37 | emit part d i sub 20 i |
| 38 | end |
| 39 | fn emitb b bool to void |
| 40 | if b |
| 41 | emit tyes |
| 42 | else |
| 43 | emit tno |
| 44 | end |
| 45 | end |
| 46 | note at tells whether t occurs in s at offset i (false when it would run past the end) |
| 47 | fn at2 s view uchar * t view uchar * i ulong to bool |
| 48 | if gt add i len t len s |
| 49 | ret false |
| 50 | end |
| 51 | for j ulong len t |
| 52 | if ne get s add i j get t j |
| 53 | ret false |
| 54 | end |
| 55 | end |
| 56 | ret true |
| 57 | end |
| 58 | fn main to int |
| 59 | emit tst |
| 60 | emitb at2 hay nd 0 |
| 61 | emit nl |
| 62 | emit tct |
| 63 | for i ulong len hay |
| 64 | if at2 hay nd i |
| 65 | emit sp |
| 66 | emitu i |
| 67 | end |
| 68 | end |
| 69 | emit nl |
| 70 | emit ten |
| 71 | emitb at2 hay nd sub len hay len nd |
| 72 | emit nl |
| 73 | ret 0 |
| 74 | end |