https://github.com/akkartik/mu/blob/main/apps/ex9.mu
 1 # Demo of reading and writing to disk.
 2 #
 3 # Steps for trying it out:
 4 #   1. Translate this example into a disk image code.img.
 5 #       ./translate apps/ex9.mu
 6 #   2. Build a second disk image data.img containing some text.
 7 #       dd if=/dev/zero of=data.img count=20160
 8 #       echo 'abc def ghi' |dd of=data.img conv=notrunc
 9 #   3. Familiarize yourself with how the data disk looks within xxd:
10 #       xxd data.img |head
11 #   4. Run:
12 #       qemu-system-i386 -hda code.img -hdb data.img
13 #   5. Exit the emulator.
14 #   6. Notice that the data disk now contains the word count of the original text.
15 #       xxd data.img |head
16 
17 fn main screen: (addr screen), keyboard: (addr keyboard), data-disk: (addr disk) {
18   var text-storage: (stream byte 0x200)
19   var text/esi: (addr stream byte) <- address text-storage
20   load-sectors data-disk, 0/lba, 1/num-sectors, text
21 
22   var word-count/eax: int <- word-count text
23 
24   var result-storage: (stream byte 0x10)
25   var result/edi: (addr stream byte) <- address result-storage
26   write-int32-decimal result, word-count
27   store-sectors data-disk, 0/lba, 1/num-sectors, result
28 }
29 
30 fn word-count in: (addr stream byte) -> _/eax: int {
31   var result/edi: int <- copy 0
32   {
33     var done?/eax: boolean <- stream-empty? in
34     compare done?, 0/false
35     break-if-!=
36     var g/eax: code-point-utf8 <- read-code-point-utf8 in
37     {
38       compare g, 0x20/space
39       break-if-!=
40       result <- increment
41     }
42     {
43       compare g, 0xa/newline
44       break-if-!=
45       result <- increment
46     }
47     loop
48   }
49   return result
50 }