4 // A trick for browserified version.
5 // Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined
6 var NodeBuffer = require('buffer').Buffer;
7 var Type = require('../type');
10 // [ 64, 65, 66 ] -> [ padding, CR, LF ]
11 var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
14 function resolveYamlBinary(data) {
19 var code, idx, bitlen = 0, len = 0, max = data.length, map = BASE64_MAP;
21 // Convert one by one.
22 for (idx = 0; idx < max; idx ++) {
23 code = map.indexOf(data.charAt(idx));
26 if (code > 64) { continue; }
28 // Fail on illegal characters
29 if (code < 0) { return false; }
34 // If there are any bits left, source was corrupted
35 return (bitlen % 8) === 0;
38 function constructYamlBinary(data) {
39 var code, idx, tailbits,
40 input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
46 // Collect by 6*4 bits (3 bytes)
48 for (idx = 0; idx < max; idx++) {
49 if ((idx % 4 === 0) && idx) {
50 result.push((bits >> 16) & 0xFF);
51 result.push((bits >> 8) & 0xFF);
52 result.push(bits & 0xFF);
55 bits = (bits << 6) | map.indexOf(input.charAt(idx));
60 tailbits = (max % 4)*6;
63 result.push((bits >> 16) & 0xFF);
64 result.push((bits >> 8) & 0xFF);
65 result.push(bits & 0xFF);
66 } else if (tailbits === 18) {
67 result.push((bits >> 10) & 0xFF);
68 result.push((bits >> 2) & 0xFF);
69 } else if (tailbits === 12) {
70 result.push((bits >> 4) & 0xFF);
73 // Wrap into Buffer for NodeJS and leave Array for browser
75 return new NodeBuffer(result);
81 function representYamlBinary(object /*, style*/) {
82 var result = '', bits = 0, idx, tail,
86 // Convert every three bytes to 4 ASCII characters.
88 for (idx = 0; idx < max; idx++) {
89 if ((idx % 3 === 0) && idx) {
90 result += map[(bits >> 18) & 0x3F];
91 result += map[(bits >> 12) & 0x3F];
92 result += map[(bits >> 6) & 0x3F];
93 result += map[bits & 0x3F];
96 bits = (bits << 8) + object[idx];
104 result += map[(bits >> 18) & 0x3F];
105 result += map[(bits >> 12) & 0x3F];
106 result += map[(bits >> 6) & 0x3F];
107 result += map[bits & 0x3F];
108 } else if (tail === 2) {
109 result += map[(bits >> 10) & 0x3F];
110 result += map[(bits >> 4) & 0x3F];
111 result += map[(bits << 2) & 0x3F];
113 } else if (tail === 1) {
114 result += map[(bits >> 2) & 0x3F];
115 result += map[(bits << 4) & 0x3F];
123 function isBinary(object) {
124 return NodeBuffer && NodeBuffer.isBuffer(object);
127 module.exports = new Type('tag:yaml.org,2002:binary', {
129 resolve: resolveYamlBinary,
130 construct: constructYamlBinary,
132 represent: representYamlBinary