Skip to content

Instantly share code, notes, and snippets.

@dominictarr
Created April 26, 2020 20:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dominictarr/98a4a5bf551dd4c9b255db8e2377fb51 to your computer and use it in GitHub Desktop.
Save dominictarr/98a4a5bf551dd4c9b255db8e2377fb51 to your computer and use it in GitHub Desktop.
(module
(def ints (import "acid-ints"))
(def mem (import "acid-memory"))
(def strings (import "acid-strings"))
(def read_request (system "system" "read_request" (id start bytes)))
(def write_ready (system "system" "write_ready" (id start bytes)))
(def open_request (system "system" "open_request" (id start bytes)))
;;HACK: global in main mem, TODO global vars
(def total (mem.alloc 4))
(def lines (mem.alloc 4))
(def words (mem.alloc 4))
(def was_ws (mem.alloc 4))
(def input_len 1024)
(def input (mem.alloc input_len))
(def incrs_mem (mac (ptr amt)
&(i32_store $ptr (add (i32_load $ptr) $amt))
))
[def count (fun count (start bytes) {block
(def end (add start bytes))
[loop (lte start end)
{block
(def char (i32_load8 start))
{if (eq char 10) ;;newline
(block
(incrs_mem lines 1)
(i32_store was_ws 1))
(if (eq char 32) ;; space
(i32_store was_ws 1)
;;neither newline or space
(if (neq 0 (i32_load was_ws)) {block
(incrs_mem words 1)
(i32_store was_ws 0)
})
)
}
(set start (add start 1))
}]
})]
[export read_ready (fun (id start bytes) (block
(incrs_mem total bytes)
(count start bytes)
(loop (set bytes (read_request 0 input input_len))
(block
(incrs_mem total bytes)
(count start bytes)
))
))]
;; the file read can error at anytime.
;; if it ends normally, read_ready length is zero?
[export read_end (fun (id code)
(if code
(log "ERROR!\n") ;;ah yeah this doesn't happen
[block
(def output
;;this could be more efficient...
;; it copies the strings each concat call
;; but varargs isn't implemented yet.
;; if it was, strings.concat could just be a macro
;; and then this would just be one copy
(strings.concat
(strings.concat (ints.encode (i32_load lines)) " ")
(strings.concat
(strings.concat (ints.encode (i32_load words)) " ")
(strings.concat (ints.encode (i32_load total)) "\n")
) ))
;;normally
(write_ready 1 (add output 4) (strings.length output))
]
)
)]
(export ready (fun () (block
;;start as if there has been whitespace
;;so word count counts the first word
(i32_store was_ws 1)
(read_request 0 input input_len)
)))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment