field

String.bytes

Returns the number of bytes a string has.

Strings in Nara are just raw sequences of bytes, without concern for any text encoding. So this field returns just the number of bytes in memory this string has, not the number of "characters" of the string.

Source code representation

When you write code to a .nara file, that code is encoded as UTF-8. This establishes how the bytes are arranged in disk. So a string like "hi" would be encoded as the bytes 0x68 0x69. These are the bytes that are loaded when the program runs, and it's what .bytes returns.

val greeting = "hi"  // encoded in UTF-8 as "0x68 0x69"
greeting.bytes       // Returns 2, since there's 2 bytes

However, in UTF-8 a single "character" can take multiple bytes. Take a emoji "💜", in UTF-8 is encoded as 4 bytes: 0xf0 0x9f 0x92 0x9c. So .bytes returns 4, the number of bytes.

val heart = "💜"    // encoded as "0xf0 0x9f 0x92 0x9c"
heart.bytes         // Returns 4

Examples

val name       = "George"
val name_bytes = name.bytes()
expect_equal(name_bytes, 6)

val text       = "💔"
val text_bytes = text.bytes()
expect_equal(text_bytes, 4)

SEE ALSO

Internals

Internally a nara String is just a slice of bytes stored on the heap, as []u8. This method just returns the slice's bytes field:

pub const ObjectString = struct {
    // ...

    pub fn string_bytes(self: *const Self) usize {
      return self.bytes.len;
    }
}

Settings

Regular