From 9739ba55df5afef922f96b107f91dbb37128bf5a Mon Sep 17 00:00:00 2001 From: Dmitry Sharshakov Date: Sun, 22 Sep 2019 20:04:46 +0300 Subject: [PATCH] Implement readString (denoland/deno_std#607) Original: https://github.com/denoland/deno_std/commit/20b6408e105f5dd1dbcd0a252d1956b3de1024ca --- io/bufio.ts | 7 +++++-- io/bufio_test.ts | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/io/bufio.ts b/io/bufio.ts index 9a7bf1dc1a..c158e5051f 100644 --- a/io/bufio.ts +++ b/io/bufio.ts @@ -211,8 +211,11 @@ export class BufReader implements Reader { * delim. * For simple uses, a Scanner may be more convenient. */ - async readString(_delim: string): Promise { - throw new Error("Not implemented"); + async readString(delim: string): Promise { + if (delim.length !== 1) + throw new Error("Delimiter should be a single character"); + const buffer = await this.readSlice(delim.charCodeAt(0)); + return new TextDecoder().decode(buffer || undefined); } /** `readLine()` is a low-level line-reading primitive. Most callers should diff --git a/io/bufio_test.ts b/io/bufio_test.ts index 6f50e28765..9d1ffc307e 100644 --- a/io/bufio_test.ts +++ b/io/bufio_test.ts @@ -160,6 +160,23 @@ test(async function bufioBufferFull(): Promise { assertEquals(actual, "world!"); }); +test(async function bufioReadString(): Promise { + const string = "And now, hello, world!"; + const buf = new BufReader(stringsReader(string), MIN_READ_BUFFER_SIZE); + + const line = assertNotEOF(await buf.readString(",")); + assertEquals(line, "And now,"); + assertEquals(line.length, 8); + + try { + await buf.readString("deno"); + + fail("should throw"); + } catch (err) { + assert(err.message, "Delimiter should be a single character"); + } +}); + const testInput = encoder.encode( "012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy" );