omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / word-wrap / word-wrap.om
| 1 | note Rosetta Code task "Word wrap": https://rosettacode.org/wiki/Word_wrap |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text rule "----\n" |
| 7 | text para "In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything." |
| 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 greedy wrap: a word goes on the current line when it still fits in width w, else starts a new one |
| 20 | fn wrap a view uchar * w ulong to void |
| 21 | cur = ulong 0 |
| 22 | i = ulong 0 |
| 23 | while lt i len a bound 4096 |
| 24 | if eq get a i 32 |
| 25 | i = add i 1 |
| 26 | else |
| 27 | j = i |
| 28 | while lt j len a bound 4096 |
| 29 | if eq get a j 32 |
| 30 | break |
| 31 | end |
| 32 | j = add j 1 |
| 33 | end |
| 34 | l = sub j i |
| 35 | if eq cur 0 |
| 36 | cur = l |
| 37 | else |
| 38 | if le add add cur 1 l w |
| 39 | emit sp |
| 40 | cur = add add cur 1 l |
| 41 | else |
| 42 | emit nl |
| 43 | cur = l |
| 44 | end |
| 45 | end |
| 46 | emit part a i l |
| 47 | i = j |
| 48 | end |
| 49 | end |
| 50 | emit nl |
| 51 | end |
| 52 | fn main to int |
| 53 | wrap para 72 |
| 54 | emit rule |
| 55 | wrap para 40 |
| 56 | ret 0 |
| 57 | end |