1// UTF-8, the text the program sees, and UTF-16, Windows' and Cocoa's,2// both ways; positions in one counted in the other.34import std::vector;5import std::string;6import std::ffi;78// How many bytes the character starting with the byte takes.9pub fn utf8_length(lead: u8) -> u64 {10 return if (lead >= 0xF0) 4 else if (lead >= 0xE0) 3 else if (lead >= 0xC0) 2 else 1;11}1213// The code point of the character starting at `at`, its bytes past the14// text's end read as missing.15pub fn code_at(text: &[u8], at: u64) -> u32 {16 const length = utf8_length(text[at]);17 const lead: u32 = match (length) {18 2 0x1F;19 3 0x0F;20 4 0x07;21 else 0xFF;22 };23 var code = text[at] to u32 & lead;24 for ([1..length]) |k| {25 if (at + k < text.length()) {26 code = (code << 6) | (text[at + k] & 0x3F) to u32;27 }28 }29 return code;30}3132// Writes the code point in UTF-8.33pub fn utf8(code: u32, out: &var String) {34 if (code < 0x80) {35 out.push(code to u8);36 } else if (code < 0x800) {37 out.push((0xC0 | (code >> 6)) to u8);38 out.push((0x80 | (code & 0x3F)) to u8);39 } else if (code < 0x10000) {40 out.push((0xE0 | (code >> 12)) to u8);41 out.push((0x80 | ((code >> 6) & 0x3F)) to u8);42 out.push((0x80 | (code & 0x3F)) to u8);43 } else {44 out.push((0xF0 | (code >> 18)) to u8);45 out.push((0x80 | ((code >> 12) & 0x3F)) to u8);46 out.push((0x80 | ((code >> 6) & 0x3F)) to u8);47 out.push((0x80 | (code & 0x3F)) to u8);48 }49}5051// The byte offset in UTF-8 text of an offset in its UTF-16 units.52pub fn utf8_offset(text: &[u8], units: u64) -> u64 {53 var at: u64 = 0;54 var counted: u64 = 0;55 while (at < text.length() && counted < units) {56 const length = utf8_length(text[at]);57 counted += if (length == 4) 2 else 1;58 at += length;59 }60 return if (at > text.length()) text.length() else at;61}6263// The UTF-16 units the first `bytes` bytes of UTF-8 text make.64pub fn utf16_offset(text: &[u8], bytes: u64) -> u64 {65 var at: u64 = 0;66 var units: u64 = 0;67 while (at < text.length() && at < bytes) {68 const length = utf8_length(text[at]);69 units += if (length == 4) 2 else 1;70 at += length;71 }72 return units;73}7475// How many characters (code points) the text holds.76pub fn characters(text: &[u8]) -> u64 {77 var count: u64 = 0;78 for (text) |b| {79 if ((b & 0xC0) != 0x80) {80 count += 1;81 }82 }83 return count;84}8586// The byte where the character `index` starts, the text's length past87// its end or before its start.88pub fn byte_of(text: &[u8], index: i64) -> u64 {89 var count: i64 = 0;90 for ([..text.length()]) |k| {91 if ((text[k] & 0xC0) != 0x80) {92 if (count == index) {93 return k;94 }95 count += 1;96 }97 }98 return text.length();99}