豆豆友情提示:这是一个非官方 GitHub 代理镜像,主要用于网络测试或访问加速。请勿在此进行登录、注册或处理任何敏感信息。进行这些操作请务必访问官方网站 github.com。 Raw 内容也通过此代理提供。
Skip to content

Commit 5cb5367

Browse files
committed
Add bounded StringWriter
1 parent 07e9fc5 commit 5cb5367

File tree

2 files changed

+29
-10
lines changed

2 files changed

+29
-10
lines changed

src/StringWriter.ts

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,28 @@ import { StringEncoding } from "./StringEncoding"
33

44
export class StringWriter extends Writable {
55

6-
protected buf = Buffer.alloc(0)
6+
protected byteLength = 0
7+
protected bufs: Buffer<ArrayBuffer>[] = []
8+
9+
constructor(protected maxByteLength: number = 1 * 1024 * 1024) {
10+
super()
11+
}
712

813
_write(chunk: Buffer | string | any, _: string, callback: (error: Error | null) => void) {
9-
if (chunk instanceof Buffer) {
10-
this.buf = Buffer.concat([this.buf, chunk])
11-
callback(null)
12-
}
13-
else {
14-
callback(new Error("StringWriter expects chunks of type 'Buffer'."))
14+
if (!(chunk instanceof Buffer)) {
15+
callback(new Error("StringWriter: expects chunks of type 'Buffer'."))
16+
return
17+
}
18+
if (this.byteLength + chunk.byteLength > this.maxByteLength) {
19+
callback(new Error(`StringWriter: Out of bounds. (maxByteLength=${this.maxByteLength})`))
20+
return
1521
}
22+
this.byteLength += chunk.byteLength
23+
this.bufs.push(chunk)
24+
callback(null)
1625
}
1726

1827
getText(encoding: StringEncoding) {
19-
return this.buf.toString(encoding)
28+
return Buffer.concat(this.bufs).toString(encoding);
2029
}
2130
}

test/stringWriterSpec.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,27 @@ const { StringWriter } = require("../dist/StringWriter")
33

44
describe("StringWriter", function() {
55
it("can run write string result", function() {
6-
const w = new StringWriter()
6+
const w = new StringWriter(10000)
77
w.write(Buffer.from("hello"))
88
w.write(Buffer.from("world"))
99
w.end()
1010
assert.equal(w.getText("utf-8"), "helloworld")
1111
})
1212

1313
it("can handle chunked multi-byte unicode codepoints", function() {
14-
const w = new StringWriter()
14+
const w = new StringWriter(10000)
1515
w.write(Buffer.from([0xE2, 0x82]))
1616
w.end(Buffer.from([0xAC]))
1717
assert.equal(w.getText("utf-8"), "€")
1818
})
19+
20+
it("fails if out of bounds", function(done) {
21+
const w = new StringWriter(10)
22+
w.once("error", (err) => {
23+
assert.match(err.message, /out of bounds/i)
24+
done()
25+
})
26+
w.write(Buffer.from("hello"))
27+
w.write(Buffer.from("worldworldworld"))
28+
})
1929
});

0 commit comments

Comments
 (0)