omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / queue-usage / queue-usage.om
| 1 | note Rosetta Code task "Queue/Usage": https://rosettacode.org/wiki/Queue/Usage |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text minus "-" |
| 7 | text tpush "push " |
| 8 | text tpop "pop " |
| 9 | text tempty "empty: " |
| 10 | text tyes "yes" |
| 11 | text tno "no" |
| 12 | text terr "pop from an empty queue: error" |
| 13 | global ring long 8 |
| 14 | global head ulong 1 |
| 15 | global cnt ulong 1 |
| 16 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 17 | fn emit a view uchar * to void |
| 18 | o = ulong 0 |
| 19 | while lt o len a bound 4096 |
| 20 | k = write 1 a o sub len a o |
| 21 | if le k 0 |
| 22 | exit 1 |
| 23 | end |
| 24 | o = add o ulong k |
| 25 | end |
| 26 | end |
| 27 | note emitu writes n in decimal; 20 digits hold every ulong |
| 28 | fn emitu n ulong to void |
| 29 | d = new uchar 20 0 |
| 30 | i = ulong 20 |
| 31 | v = n |
| 32 | while true bound 20 |
| 33 | i = sub i 1 |
| 34 | put d i uchar add rem v 10 48 |
| 35 | v = div v 10 |
| 36 | if eq v 0 |
| 37 | break |
| 38 | end |
| 39 | end |
| 40 | emit part d i sub 20 i |
| 41 | end |
| 42 | note emiti writes a signed n; the magnitude is taken as a ulong so the minimum long cannot overflow |
| 43 | fn emiti n long to void |
| 44 | if lt n 0 |
| 45 | emit minus |
| 46 | emitu add bitcast ulong not n 1 |
| 47 | else |
| 48 | emitu ulong n |
| 49 | end |
| 50 | end |
| 51 | note a FIFO queue in a ring of 8 slots: cnt elements starting at ring[head]; push writes behind the |
| 52 | note last one, pop takes ring[head]; a full ring stops the program (exit 2) |
| 53 | fn push v long to void |
| 54 | c = get cnt 0 |
| 55 | if eq c 8 |
| 56 | exit 2 |
| 57 | end |
| 58 | put ring rem add get head 0 c 8 v |
| 59 | put cnt 0 add c 1 |
| 60 | emit tpush |
| 61 | emiti v |
| 62 | emit nl |
| 63 | end |
| 64 | note pop returns false, and prints the error, when the queue is empty |
| 65 | fn pop to bool |
| 66 | c = get cnt 0 |
| 67 | if eq c 0 |
| 68 | emit terr |
| 69 | emit nl |
| 70 | ret false |
| 71 | end |
| 72 | h = get head 0 |
| 73 | emit tpop |
| 74 | emiti get ring h |
| 75 | emit nl |
| 76 | put head 0 rem add h 1 8 |
| 77 | put cnt 0 sub c 1 |
| 78 | ret true |
| 79 | end |
| 80 | fn empty to void |
| 81 | emit tempty |
| 82 | if eq get cnt 0 0 |
| 83 | emit tyes |
| 84 | else |
| 85 | emit tno |
| 86 | end |
| 87 | emit nl |
| 88 | end |
| 89 | fn main to int |
| 90 | empty |
| 91 | push 1 |
| 92 | push 2 |
| 93 | push 3 |
| 94 | ok = pop |
| 95 | empty |
| 96 | push 4 |
| 97 | ok = pop |
| 98 | ok = pop |
| 99 | ok = pop |
| 100 | empty |
| 101 | ok = pop |
| 102 | ret 0 |
| 103 | end |