https://github.com/akkartik/mu/blob/main/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 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 in an emulator, either Qemu or Bochs.
    12 #       qemu-system-i386 -hda code.img -hdb data.img
    13 #       bochs -f bochsrc.2disks
    14 #   5. Exit the emulator.
    15 #   6. Notice that the data disk now contains the word count of the original text.
    16 #       xxd data.img |head
    17
    18 fn main screen: (addr screen), keyboard: (addr keyboard), data-disk: (addr disk) {
    19   var text-storage: (stream byte 0x200)
    20   var text/esi: (addr stream byte) <- address text-storage
    21   load-sectors data-disk, 0/lba, 1/num-sectors, text
    22
    23   var word-count/eax: int <- word-count text
    24
    25   var result-storage: (stream byte 0x10)
    26   var result/edi: (addr stream byte) <- address result-storage
    27   write-int32-decimal result, word-count
    28   store-sectors data-disk, 0/lba, 1/num-sectors, result
    29 }
    30
    31 fn word-count in: (addr stream byte) -> _/eax: int {
    32   var result/edi: int <- copy 0
    33   {
    34     var done?/eax: boolean <- stream-empty? in
    35     compare done?, 0/false
    36     break-if-!=
    37     var g/eax: grapheme <- read-grapheme in
    38     {
    39       compare g, 0x20/space
    40       break-if-!=
    41       result <- increment
    42     }
    43     {
    44       compare g, 0xa/newline
    45       break-if-!=
    46       result <- increment
    47     }
    48     loop
    49   }
    50   return result
    51 }