1// The owned, growable byte string.2//3// A String owns a heap buffer of UTF-8 bytes and a count of the bytes in4// use. Growth follows the manual pattern of LANGUAGE_SPEC.md section 5.25// with a doubling buffer, so appends are amortized constant. `view`6// borrows the contents in place as a plain `&[u8]` slice, the type every7// text-taking function (and string literal) already uses.89import std::option;10import std::iterable;11import std::hash;12import std::equal;13import std::format;1415exp type String : Iterable<u8, StringCursor> + Key + Equal + Format = struct {16 storage: Option<*var [u8]>,17 count: u64,18};1920// A string with no bytes and no allocation.21exp fn String::empty() -> String {22 return String { .storage = ::None, .count = 0 };23}2425// An owned copy of the given text.26exp fn String::from(text: &[u8]) -> String {27 var result = String::empty();28 result.append(&text);29 return move result;30}3132// String representation of the given integer.33exp fn String::from(number: i64) -> String {34 var digits: u64 = 1;35 var remaining = number / 10;36 while (remaining != 0) {37 digits += 1;38 remaining /= 10;39 }40 if (number < 0) {41 digits += 1;42 }43 var result = String::with_capacity(digits);44 result.append(number);45 return move result;46}4748// Allocates a string able to hold at least `capacity` bytes before growing.49exp fn String::with_capacity(capacity: u64) -> String {50 var result = String { .storage = ::None, .count = 0 };51 result.ensure_capacity(capacity);52 return move result;53}5455// The number of bytes in use.56exp fn length(self string: &String) -> u64 {57 return string.count;58}5960// The cursor behind `for (string) |byte|` (section 5.3): it borrows the61// contents once and hands out references to the bytes in place.62exp type StringCursor : Iterator<u8> = struct {63 bytes: &[u8],64 index: u64,65};6667exp fn iterator(self string: &String) -> StringCursor {68 return StringCursor { .bytes = &string.view(), .index = 0 };69}7071exp fn next(self cursor: &var StringCursor) -> Option<&u8> {72 if (cursor.index >= cursor.bytes.length()) {73 return ::None;74 }75 cursor.index += 1;76 return ::Some(&cursor.bytes[cursor.index - 1]);77}7879// Borrows the contents in place. The view is invalidated by the next80// mutation (growth may reallocate), like any Alloy reference.81exp fn view(self string: &String) -> &[u8] {82 if (string.storage is ::Some |&buffer|) {83 return &buffer[..string.count];84 }85 return &"";86}8788// The byte at the index, in place; a fault past the end.89exp fn get(self string: &String, index: u64) -> &u8 {90 return &string.view()[index];91}9293// Appends one byte.94exp fn push(self string: &var String, byte: u8) {95 string.ensure_capacity(string.count + 1);96 if (string.storage is ::Some |&var buffer|) {97 buffer[string.count] = byte;98 }99 string.count += 1;100}101102// Appends every byte of the given text.103exp fn append(self string: &var String, text: &[u8]) {104 string.ensure_capacity(string.count + text.length());105 if (string.storage is ::Some |&var buffer|) {106 buffer[string.count..string.count + text.length()] = text;107 }108 string.count += text.length();109}110111// Appends the decimal digits of the value, written backwards into a112// local buffer first.113exp fn append(self string: &var String, value: i64) {114 // the magnitude as u64, which holds even the most negative value's115 var magnitude = value as u64;116 if (value < 0) {117 magnitude = (-(value + 1)) as u64 + 1;118 }119 var digits: [u8 : 20] = [0 : 20];120 var start: u64 = 20;121 while (true) {122 start -= 1;123 digits[start] = '0' + (magnitude % 10) to u8;124 magnitude /= 10;125 if (magnitude == 0) {126 break;127 }128 }129 if (value < 0) {130 string.push('-');131 }132 string.append(&digits[start..]);133}134135// Makes room for at least `additional` more bytes, so the appends up to136// it do not grow the buffer.137exp fn reserve(self string: &var String, additional: u64) {138 string.ensure_capacity(string.count + additional);139}140141// Empties the string; the buffer is kept for future appends.142exp fn clear(self string: &var String) {143 string.count = 0;144}145146// Keeps the first `length` bytes, if there are more.147exp fn truncate(self string: &var String, length: u64) {148 if (length < string.count) {149 string.count = length;150 }151}152153// Writes the contents as they are (std::format).154exp fn format(self string: &String, out: &var String) {155 out.append(&string.view());156}157158// Hashes the contents, as hash_bytes does the same text (std::hash).159exp fn hash(self string: &String) -> u64 {160 return hash_bytes(&string.view());161}162163// True when the contents are the same, whatever the capacities.164exp fn same(self string: &String, other: &String) -> bool {165 return string.view() == other.view();166}167168// What `==` compares: the contents, whatever the capacities.169exp fn equals(self string: &String, other: &String) -> bool {170 return string.view() == other.view();171}172173// True when the contents equal the given text byte for byte.174exp fn equals(self string: &String, text: &[u8]) -> bool {175 return string.view() == text;176}177178// Makes room for `needed` bytes; short, so it can be inlined where the179// room is usually there already.180fn ensure_capacity(self string: &var String, needed: u64) {181 if (string.storage is ::Some |&buffer| && needed <= buffer.length()) {182 return;183 }184 string.grow(needed);185}186187// Grows the buffer to hold at least `needed` bytes, copying the bytes188// in use across; reassigning the owning field reclaims the old buffer.189fn grow(self string: &var String, needed: u64) {190 var current: u64 = 0;191 if (string.storage is ::Some |&buffer|) {192 current = buffer.length();193 }194 var grown_capacity = current * 2;195 if (grown_capacity < 16) {196 grown_capacity = 16;197 }198 if (grown_capacity < needed) {199 grown_capacity = needed;200 }201 var grown: *var [u8] = new [0 : grown_capacity];202 if (string.storage is ::Some |&buffer|) {203 grown[..string.count] = buffer[..string.count];204 }205 string.storage = ::Some(move grown);206}