Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions src/CharStreams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,23 +233,22 @@ export namespace CharStreams {
// }

/**
* Creates a {@link CharStream} given a {@link String}.
*/
export function fromString(s: string): CodePointCharStream;

/**
* Creates a {@link CharStream} given a {@link String} and the {@code sourceName}
* Creates a {@link CharStream} given a {@link String} and the optional {@code sourceName}
* from which it came.
*/
export function fromString(s: string, sourceName: string): CodePointCharStream;
export function fromString(s: string, sourceName?: string): CodePointCharStream {
export function fromString(
s: string,
sourceName?: string,
): CodePointCharStream {
if (sourceName === undefined || sourceName.length === 0) {
sourceName = IntStream.UNKNOWN_SOURCE_NAME;
}

// Initial guess assumes no code points > U+FFFF: one code
// point for each code unit in the string
let codePointBufferBuilder: CodePointBuffer.Builder = CodePointBuffer.builder(s.length);
let codePointBufferBuilder: CodePointBuffer.Builder = CodePointBuffer.builder(
s.length,
);

// TODO: CharBuffer.wrap(String) rightfully returns a read-only buffer
// which doesn't expose its array, so we make a copy.
Expand All @@ -259,7 +258,10 @@ export namespace CharStreams {
}

codePointBufferBuilder.append(cb);
return CodePointCharStream.fromBuffer(codePointBufferBuilder.build(), sourceName);
return CodePointCharStream.fromBuffer(
codePointBufferBuilder.build(),
sourceName,
);
}

// export function bufferFromChannel(
Expand Down
9 changes: 9 additions & 0 deletions test/tool/TestCharStreams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ export class TestCharStreams {
assert.strictEqual("hello", s.toString());
}

@test
public fromStringSupportsOptionalName(): void {
let s: CharStream = CharStreams.fromString("hello", "embeddedString");
assert.strictEqual(5, s.size);
assert.strictEqual(0, s.index);
assert.strictEqual("hello", s.toString());
assert.strictEqual("embeddedString", s.sourceName);
}

@test
public fromSMPStringHasExpectedSize(): void {
let s: CharStream = CharStreams.fromString("hello 🌎");
Expand Down