×


strlen in wast(Read 521 times)
strlen in wast on: October 15, 2017, 03:02:23 pm
Last night I was working on something and needed strlen, I wrote the following, but I am curious if someone knows of a better way. For example would it be worth unrolling offset 1,2,3? Is there a different op code I can use that would be better?

Code: [Select]
(func $strlen (param $s i32) (result i32)
    (local $head i32)
    (set_local $head (get_local $s))
    (loop $done $loop
      (br_if $done (i32.eq (i32.const 0) (i32.load8_u offset=0 (get_local $head))))
      (set_local $head (i32.add (get_local $head) (i32.const 1)))
      (br $loop)
    )
    (return (i32.sub (get_local $head) (get_local $s)))
  )



Re: strlen in wast Reply #1 on: October 15, 2017, 10:14:23 pm
If you don't set $head than it would always load from memory location 0 rather than the location of the string s

Code: [Select]
(i32.load8_u offset=0 (get_local $head))))