Skip to content

Commit b7e7be2

Browse files
committed
Add String.fromUTF8 helper (see AssemblyScript#291); Update dist files
1 parent 53b030f commit b7e7be2

File tree

9 files changed

+5344
-15
lines changed

9 files changed

+5344
-15
lines changed

dist/asc.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

dist/asc.js.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

std/assembly/index.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,7 @@ declare class String {
490490
padEnd(targetLength: i32, padString?: string): string;
491491
repeat(count?: i32): string;
492492
toString(): string;
493+
static fromUTF8(ptr: usize, len: usize): string;
493494
toUTF8(): usize;
494495
}
495496

std/assembly/string.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,49 @@ export class String {
436436
return len;
437437
}
438438

439+
static fromUTF8(ptr: usize, len: usize): String {
440+
if (len < 1) return changetype<String>("");
441+
var ptrPos = <usize>0;
442+
var buf = memory.allocate(<usize>len << 1);
443+
var bufPos = <usize>0;
444+
while (ptrPos < len) {
445+
let cp = <u32>load<u8>(ptr + ptrPos++);
446+
if (cp < 128) {
447+
store<u16>(buf + bufPos, cp);
448+
bufPos += 2;
449+
} else if (cp > 191 && cp < 224) {
450+
assert(ptrPos + 1 <= len);
451+
store<u16>(buf + bufPos, (cp & 31) << 6 | load<u8>(ptr + ptrPos++) & 63);
452+
bufPos += 2;
453+
} else if (cp > 239 && cp < 365) {
454+
assert(ptrPos + 3 <= len);
455+
cp = (
456+
(cp & 7) << 18 |
457+
(load<u8>(ptr + ptrPos++) & 63) << 12 |
458+
(load<u8>(ptr + ptrPos++) & 63) << 6 |
459+
load<u8>(ptr + ptrPos++) & 63
460+
) - 0x10000;
461+
store<u16>(buf + bufPos, 0xD800 + (cp >> 10));
462+
bufPos += 2;
463+
store<u16>(buf + bufPos, 0xDC00 + (cp & 1023));
464+
bufPos += 2;
465+
} else {
466+
assert(ptrPos + 2 <= len);
467+
store<u16>(buf + bufPos,
468+
(cp & 15) << 12 |
469+
(load<u8>(ptr + ptrPos++) & 63) << 6 |
470+
load<u8>(ptr + ptrPos++) & 63
471+
);
472+
bufPos += 2;
473+
}
474+
}
475+
assert(ptrPos == len);
476+
var str = allocateUnsafe(<u32>(bufPos >> 1));
477+
memory.copy(changetype<usize>(str) + HEADER_SIZE, buf, bufPos);
478+
memory.free(buf);
479+
return str;
480+
}
481+
439482
toUTF8(): usize {
440483
var buf = memory.allocate(<usize>this.lengthUTF8);
441484
var pos: usize = 0;

0 commit comments

Comments
 (0)