TExcelTAD
Home › WebAssembly › Data Segments & Strings

Data Segments & Strings

Writing every byte with i32.store8 would be painful. A data segment copies a block of bytes into memory when the module is instantiated. It's how compilers ship string literals, lookup tables and initialised C arrays.

text
(data (i32.const 16) "hello")            ;; active segment: copied to address 16 at instantiation
(data (i32.const 64) "\01\02\ff")        ;; escapes: \xx is a hex byte
(data $later "bytes for later")          ;; passive segment: copied only with memory.init

Strings are bytes plus a length

The string literal in a data segment is stored as UTF-8 bytes. There is no terminator unless you add one ("\00"). To use a string you need its address and its length:

wat · try it yourself
(module
  (import "console" "str" (func $print (param i32 i32)))
  (memory (export "memory") 1)
  (data (i32.const 0) "Good morning")
  (data (i32.const 32) "Gr\u{fc}\u{df}e, \u{4e16}\u{754c}")   ;; "Grüße, 世界"

  (func (export "main")
    (call $print (i32.const 0) (i32.const 12))
    (call $print (i32.const 0) (i32.const 4))      ;; just "Good"
    (call $print (i32.const 5) (i32.const 7))      ;; "morning"
    (call $print (i32.const 32) (i32.const 15))))  ;; ü, ß are 2 bytes; 世, 界 are 3
Good morning
Good
morning
Grüße, 世界

"Grüße, 世界" has 9 characters but takes 15 bytes in UTF-8. Lengths in Wasm are always byte counts.

Note: The second segment spells its non-ASCII characters with \u{…} escapes. Typing "Grüße, 世界" directly works too and produces exactly the same bytes; escapes just make the byte layout visible in the source.

Escapes

Escape Byte(s)
\n \t \r newline, tab, carriage return
\" \' \\ quote, apostrophe, backslash
\4f the byte 0x4f (two hex digits)
\u{1F600} the UTF-8 encoding of a Unicode code point

Data segments aren't only for text. Any bytes will do, such as a table of values:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (memory 1)
  ;; days in each month (non-leap year), one byte each
  (data (i32.const 100) "\1f\1c\1f\1e\1f\1e\1f\1f\1e\1f\1e\1f")

  (func $days_in (param $month i32) (result i32)       ;; month 1..12
    (i32.load8_u offset=99 (local.get $month)))        ;; 100 + (month - 1)

  (func (export "main")
    (call $log (call $days_in (i32.const 1)))
    (call $log (call $days_in (i32.const 2)))
    (call $log (call $days_in (i32.const 9)))))
31
28
30

Working with a string: length of a C string

C-style strings end with a zero byte. To find the length you scan for it:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (import "console" "str" (func $print (param i32 i32)))
  (memory (export "memory") 1)
  (data (i32.const 0) "WebAssembly\00")
  (data (i32.const 16) "Wasm\00")

  (func $strlen (param $p i32) (result i32)
    (local $start i32)
    (local.set $start (local.get $p))
    (block $done
      (loop $scan
        (br_if $done (i32.eqz (i32.load8_u (local.get $p))))
        (local.set $p (i32.add (local.get $p) (i32.const 1)))
        (br $scan)))
    (i32.sub (local.get $p) (local.get $start)))

  (func $puts (param $p i32)
    (call $print (local.get $p) (call $strlen (local.get $p))))

  (func (export "main")
    (call $log (call $strlen (i32.const 0)))
    (call $log (call $strlen (i32.const 16)))
    (call $puts (i32.const 16))))
11
4
Wasm

Most languages that compile to Wasm (Rust, Go, AssemblyScript) prefer pointer + length pairs over zero-terminated strings: no scanning needed, and strings may contain zero bytes.

Modifying strings in place

Data segments only provide initial content; afterwards the bytes are ordinary memory. Here's an in-place ASCII uppercase conversion:

wat · try it yourself
(module
  (import "console" "str" (func $print (param i32 i32)))
  (memory (export "memory") 1)
  (data (i32.const 0) "hello, wasm world!")

  (func $to_upper (param $p i32) (param $len i32)
    (local $c i32) (local $end i32)
    (local.set $end (i32.add (local.get $p) (local.get $len)))
    (block $done
      (loop $next
        (br_if $done (i32.ge_u (local.get $p) (local.get $end)))
        (local.set $c (i32.load8_u (local.get $p)))
        ;; if 'a' <= c <= 'z' then c -= 32
        (if (i32.le_u (i32.sub (local.get $c) (i32.const 97)) (i32.const 25))
          (then (i32.store8 (local.get $p) (i32.sub (local.get $c) (i32.const 32)))))
        (local.set $p (i32.add (local.get $p) (i32.const 1)))
        (br $next))))

  (func (export "main")
    (call $print (i32.const 0) (i32.const 18))
    (call $to_upper (i32.const 0) (i32.const 18))
    (call $print (i32.const 0) (i32.const 18))))
hello, wasm world!
HELLO, WASM WORLD!

Formatting a number as text

The host printed numbers for us so far. To build text yourself, convert digits into ASCII bytes ('0' is 48). This writes the decimal digits of a non-negative number from right to left into a buffer:

wat · try it yourself
(module
  (import "console" "str" (func $print (param i32 i32)))
  (memory (export "memory") 1)
  (data (i32.const 0) "Score: ")

  ;; writes n's digits so that they END at address $end; returns the start address
  (func $utoa (param $n i32) (param $end i32) (result i32)
    (loop $digit
      (local.set $end (i32.sub (local.get $end) (i32.const 1)))
      (i32.store8 (local.get $end) (i32.add (i32.const 48) (i32.rem_u (local.get $n) (i32.const 10))))
      (local.set $n (i32.div_u (local.get $n) (i32.const 10)))
      (br_if $digit (local.get $n)))
    (local.get $end))

  (func (export "main")
    (local $start i32)
    (call $print (i32.const 0) (i32.const 7))
    (local.set $start (call $utoa (i32.const 90210) (i32.const 100)))
    (call $print (local.get $start) (i32.sub (i32.const 100) (local.get $start)))))
Score:
90210

Test yourself

When is an active data segment copied into memory?

  1. Every time a function is called
  2. At instantiation
  3. Only when memory.init runs
  4. Lazily on first read

How many bytes does the string "é" take in a data segment?

  1. 1
  2. 2
  3. 3
  4. 4

Which is the usual way to pass a string around in Wasm?

  1. A string value type
  2. A pointer and a length (or a pointer to zero-terminated bytes)
  3. A global per character
  4. A table of characters