Skip to content

Commit

Permalink
feat(stdlib): Implement Char toString (#481)
Browse files Browse the repository at this point in the history
  • Loading branch information
ospencer committed Dec 17, 2020
1 parent 1a4c3b9 commit 37ba683
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
4 changes: 4 additions & 0 deletions compiler/test/stdlib/char.test.gr
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,7 @@ assert Char.code(Char.succ(Char.fromCode(0xD7FF))) == 0xE000
// pred
assert Char.code(Char.pred(Char.fromCode(0x70))) == 0x6F
assert Char.code(Char.pred(Char.fromCode(0xE000))) == 0xD7FF

// toString
assert Char.toString('f') == "f"
assert Char.toString('💯') == "💯"
5 changes: 5 additions & 0 deletions stdlib/char.gr
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,8 @@ let pred = (c) => {
fromCode(codePoint - 1)
}
}

// Creates a new string containing the character.
// @param char: Char - the character to convert
// @returns String
import foreign wasm toString : Char -> String from "stdlib-external/char"
20 changes: 19 additions & 1 deletion stdlib/stdlib-external/char.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { throwError } from './ascutils/grainRuntime'
import { GRAIN_ERR_MALFORMED_UTF8 } from './ascutils/errors'
import { GRAIN_GENERIC_HEAP_TAG_TYPE } from './ascutils/tags'
import { allocateChar } from './ascutils/dataStructures'
import { allocateChar, allocateString } from './ascutils/dataStructures'

// Algorithm from https://encoding.spec.whatwg.org/#utf-8-decoder
export function code(c: u32): u32 {
Expand Down Expand Up @@ -85,3 +85,21 @@ export function fromCode(code: u32): u32 {

return char ^ GRAIN_GENERIC_HEAP_TAG_TYPE
}

export function toString(c: u32): u32 {
c = c ^ GRAIN_GENERIC_HEAP_TAG_TYPE
let byte = load<u8>(c, 4)
let n: u32
if ((byte & 0x80) === 0x00) {
n = 1
} else if ((byte & 0xF0) === 0xF0) {
n = 4
} else if ((byte & 0xE0) === 0xE0) {
n = 3
} else {
n = 2
}
let str = allocateString(n)
memory.copy(str + 8, c + 4, n)
return str ^ GRAIN_GENERIC_HEAP_TAG_TYPE
}

0 comments on commit 37ba683

Please sign in to comment.