interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / queue-definition / queue-definition.om

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