forked from dawidd6/action-download-artifact
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutf8-decoder.js
More file actions
104 lines (82 loc) · 2.47 KB
/
Copy pathutf8-decoder.js
File metadata and controls
104 lines (82 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const b4a = require('b4a')
/**
* https://encoding.spec.whatwg.org/#utf-8-decoder
*/
module.exports = class UTF8Decoder {
constructor () {
this.codePoint = 0
this.bytesSeen = 0
this.bytesNeeded = 0
this.lowerBoundary = 0x80
this.upperBoundary = 0xbf
}
get remaining () {
return this.bytesSeen
}
decode (data) {
// If we have a fast path, just sniff if the last part is a boundary
if (this.bytesNeeded === 0) {
let isBoundary = true
for (let i = Math.max(0, data.byteLength - 4), n = data.byteLength; i < n && isBoundary; i++) {
isBoundary = data[i] <= 0x7f
}
if (isBoundary) return b4a.toString(data, 'utf8')
}
let result = ''
for (let i = 0, n = data.byteLength; i < n; i++) {
const byte = data[i]
if (this.bytesNeeded === 0) {
if (byte <= 0x7f) {
result += String.fromCharCode(byte)
} else {
this.bytesSeen = 1
if (byte >= 0xc2 && byte <= 0xdf) {
this.bytesNeeded = 2
this.codePoint = byte & 0x1f
} else if (byte >= 0xe0 && byte <= 0xef) {
if (byte === 0xe0) this.lowerBoundary = 0xa0
else if (byte === 0xed) this.upperBoundary = 0x9f
this.bytesNeeded = 3
this.codePoint = byte & 0xf
} else if (byte >= 0xf0 && byte <= 0xf4) {
if (byte === 0xf0) this.lowerBoundary = 0x90
if (byte === 0xf4) this.upperBoundary = 0x8f
this.bytesNeeded = 4
this.codePoint = byte & 0x7
} else {
result += '\ufffd'
}
}
continue
}
if (byte < this.lowerBoundary || byte > this.upperBoundary) {
this.codePoint = 0
this.bytesNeeded = 0
this.bytesSeen = 0
this.lowerBoundary = 0x80
this.upperBoundary = 0xbf
result += '\ufffd'
continue
}
this.lowerBoundary = 0x80
this.upperBoundary = 0xbf
this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
this.bytesSeen++
if (this.bytesSeen !== this.bytesNeeded) continue
result += String.fromCodePoint(this.codePoint)
this.codePoint = 0
this.bytesNeeded = 0
this.bytesSeen = 0
}
return result
}
flush () {
const result = this.bytesNeeded > 0 ? '\ufffd' : ''
this.codePoint = 0
this.bytesNeeded = 0
this.bytesSeen = 0
this.lowerBoundary = 0x80
this.upperBoundary = 0xbf
return result
}
}