Add String.fromUTF8 helper (see #291); Update dist files

This commit is contained in:
dcodeIO 2018-10-03 00:49:56 +02:00
parent 53b030fed5
commit b7e7be20cf
9 changed files with 5344 additions and 15 deletions

2
dist/asc.js vendored

File diff suppressed because one or more lines are too long

2
dist/asc.js.map vendored

File diff suppressed because one or more lines are too long

View File

@ -490,6 +490,7 @@ declare class String {
padEnd(targetLength: i32, padString?: string): string;
repeat(count?: i32): string;
toString(): string;
static fromUTF8(ptr: usize, len: usize): string;
toUTF8(): usize;
}

View File

@ -436,6 +436,49 @@ export class String {
return len;
}
static fromUTF8(ptr: usize, len: usize): String {
if (len < 1) return changetype<String>("");
var ptrPos = <usize>0;
var buf = memory.allocate(<usize>len << 1);
var bufPos = <usize>0;
while (ptrPos < len) {
let cp = <u32>load<u8>(ptr + ptrPos++);
if (cp < 128) {
store<u16>(buf + bufPos, cp);
bufPos += 2;
} else if (cp > 191 && cp < 224) {
assert(ptrPos + 1 <= len);
store<u16>(buf + bufPos, (cp & 31) << 6 | load<u8>(ptr + ptrPos++) & 63);
bufPos += 2;
} else if (cp > 239 && cp < 365) {
assert(ptrPos + 3 <= len);
cp = (
(cp & 7) << 18 |
(load<u8>(ptr + ptrPos++) & 63) << 12 |
(load<u8>(ptr + ptrPos++) & 63) << 6 |
load<u8>(ptr + ptrPos++) & 63
) - 0x10000;
store<u16>(buf + bufPos, 0xD800 + (cp >> 10));
bufPos += 2;
store<u16>(buf + bufPos, 0xDC00 + (cp & 1023));
bufPos += 2;
} else {
assert(ptrPos + 2 <= len);
store<u16>(buf + bufPos,
(cp & 15) << 12 |
(load<u8>(ptr + ptrPos++) & 63) << 6 |
load<u8>(ptr + ptrPos++) & 63
);
bufPos += 2;
}
}
assert(ptrPos == len);
var str = allocateUnsafe(<u32>(bufPos >> 1));
memory.copy(changetype<usize>(str) + HEADER_SIZE, buf, bufPos);
memory.free(buf);
return str;
}
toUTF8(): usize {
var buf = memory.allocate(<usize>this.lengthUTF8);
var pos: usize = 0;

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@ var len = str.lengthUTF8;
assert(len == 11);
var ptr = str.toUTF8();
var ptr = str.toUTF8(); // toUTF8 is zero-terminated
assert(load<u8>(ptr, 0) == 0xf0);
assert(load<u8>(ptr, 1) == 0x90);
@ -20,4 +20,11 @@ assert(load<u8>(ptr, 8) == 0xad);
assert(load<u8>(ptr, 9) == 0xa2);
assert(load<u8>(ptr, 10) == 0);
assert(String.fromUTF8(ptr, 0) == ""); // fromUTF8 is not zero-terminated
assert(String.fromUTF8(ptr, len - 1) == str);
assert(String.fromUTF8(ptr, 4) == "𐐷");
assert(String.fromUTF8(ptr + 4, 2) == "hi");
assert(String.fromUTF8(ptr + 6, 4) == "𤭢");
assert(String.fromUTF8(ptr + 10, 1) == "\0");
memory.free(ptr);

File diff suppressed because it is too large Load Diff

View File

@ -3749,7 +3749,7 @@
(call $~lib/env/abort
(i32.const 0)
(i32.const 80)
(i32.const 523)
(i32.const 566)
(i32.const 10)
)
(unreachable)

View File

@ -4536,7 +4536,7 @@
(call $~lib/env/abort
(i32.const 0)
(i32.const 80)
(i32.const 523)
(i32.const 566)
(i32.const 10)
)
(unreachable)