forked from Level/level-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeserialize.js
More file actions
44 lines (39 loc) · 1.02 KB
/
deserialize.js
File metadata and controls
44 lines (39 loc) · 1.02 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
'use strict'
var Buffer = require('buffer').Buffer
var ta2str = (function () {
if (global.TextDecoder) {
var decoder = new TextDecoder('utf-8')
return decoder.decode.bind(decoder)
} else {
return function ta2str (ta) {
return ta2buf(ta).toString()
}
}
})()
var ab2str = (function () {
if (global.TextDecoder) {
var decoder = new TextDecoder('utf-8')
return decoder.decode.bind(decoder)
} else {
return function ab2str (ab) {
return Buffer.from(ab).toString()
}
}
})()
function ta2buf (ta) {
var buf = Buffer.from(ta.buffer)
if (ta.byteLength === ta.buffer.byteLength) {
return buf
} else {
return buf.slice(ta.byteOffset, ta.byteOffset + ta.byteLength)
}
}
module.exports = function (data, asBuffer) {
if (data instanceof Uint8Array) {
return asBuffer ? ta2buf(data) : ta2str(data)
} else if (data instanceof ArrayBuffer) {
return asBuffer ? Buffer.from(data) : ab2str(data)
} else {
return asBuffer ? Buffer.from(String(data)) : String(data)
}
}