3 /*eslint-disable no-bitwise*/
5 // A trick for browserified version.
6 // Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined
7 var NodeBuffer = require('buffer').Buffer;
8 var Type = require('../type');
11 // [ 64, 65, 66 ] -> [ padding, CR, LF ]
12 var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
15 function resolveYamlBinary(data) {
16 if (data === null) return false;
18 var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
20 // Convert one by one.
21 for (idx = 0; idx < max; idx++) {
22 code = map.indexOf(data.charAt(idx));
25 if (code > 64) continue;
27 // Fail on illegal characters
28 if (code < 0) return false;
33 // If there are any bits left, source was corrupted
34 return (bitlen % 8) === 0;
37 function constructYamlBinary(data) {
39 input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
45 // Collect by 6*4 bits (3 bytes)
47 for (idx = 0; idx < max; idx++) {
48 if ((idx % 4 === 0) && idx) {
49 result.push((bits >> 16) & 0xFF);
50 result.push((bits >> 8) & 0xFF);
51 result.push(bits & 0xFF);
54 bits = (bits << 6) | map.indexOf(input.charAt(idx));
59 tailbits = (max % 4) * 6;
62 result.push((bits >> 16) & 0xFF);
63 result.push((bits >> 8) & 0xFF);
64 result.push(bits & 0xFF);
65 } else if (tailbits === 18) {
66 result.push((bits >> 10) & 0xFF);
67 result.push((bits >> 2) & 0xFF);
68 } else if (tailbits === 12) {
69 result.push((bits >> 4) & 0xFF);
72 // Wrap into Buffer for NodeJS and leave Array for browser
73 if (NodeBuffer) return new NodeBuffer(result);
78 function representYamlBinary(object /*, style*/) {
79 var result = '', bits = 0, idx, tail,
83 // Convert every three bytes to 4 ASCII characters.
85 for (idx = 0; idx < max; idx++) {
86 if ((idx % 3 === 0) && idx) {
87 result += map[(bits >> 18) & 0x3F];
88 result += map[(bits >> 12) & 0x3F];
89 result += map[(bits >> 6) & 0x3F];
90 result += map[bits & 0x3F];
93 bits = (bits << 8) + object[idx];
101 result += map[(bits >> 18) & 0x3F];
102 result += map[(bits >> 12) & 0x3F];
103 result += map[(bits >> 6) & 0x3F];
104 result += map[bits & 0x3F];
105 } else if (tail === 2) {
106 result += map[(bits >> 10) & 0x3F];
107 result += map[(bits >> 4) & 0x3F];
108 result += map[(bits << 2) & 0x3F];
110 } else if (tail === 1) {
111 result += map[(bits >> 2) & 0x3F];
112 result += map[(bits << 4) & 0x3F];
120 function isBinary(object) {
121 return NodeBuffer && NodeBuffer.isBuffer(object);
124 module.exports = new Type('tag:yaml.org,2002:binary', {
126 resolve: resolveYamlBinary,
127 construct: constructYamlBinary,
129 represent: representYamlBinary