3 var common = require('../common');
4 var Type = require('../type');
6 function isHexCode(c) {
7 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
8 ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
9 ((0x61/* a */ <= c) && (c <= 0x66/* f */));
12 function isOctCode(c) {
13 return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
16 function isDecCode(c) {
17 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
20 function resolveYamlInteger(data) {
25 var max = data.length,
30 if (!max) { return false; }
35 if (ch === '-' || ch === '+') {
41 if (index+1 === max) { return true; }
44 // base 2, base 8, base 16
50 for (; index < max; index++) {
52 if (ch === '_') { continue; }
53 if (ch !== '0' && ch !== '1') {
66 for (; index < max; index++) {
68 if (ch === '_') { continue; }
69 if (!isHexCode(data.charCodeAt(index))) {
78 for (; index < max; index++) {
80 if (ch === '_') { continue; }
81 if (!isOctCode(data.charCodeAt(index))) {
89 // base 10 (except 0) or base 60
91 for (; index < max; index++) {
93 if (ch === '_') { continue; }
94 if (ch === ':') { break; }
95 if (!isDecCode(data.charCodeAt(index))) {
101 if (!hasDigits) { return false; }
103 // if !base60 - done;
104 if (ch !== ':') { return true; }
106 // base60 almost not used, no needs to optimize
107 return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
110 function constructYamlInteger(data) {
111 var value = data, sign = 1, ch, base, digits = [];
113 if (value.indexOf('_') !== -1) {
114 value = value.replace(/_/g, '');
119 if (ch === '-' || ch === '+') {
120 if (ch === '-') { sign = -1; }
121 value = value.slice(1);
130 if (value[1] === 'b') {
131 return sign * parseInt(value.slice(2), 2);
133 if (value[1] === 'x') {
134 return sign * parseInt(value, 16);
136 return sign * parseInt(value, 8);
140 if (value.indexOf(':') !== -1) {
141 value.split(':').forEach(function (v) {
142 digits.unshift(parseInt(v, 10));
148 digits.forEach(function (d) {
157 return sign * parseInt(value, 10);
160 function isInteger(object) {
161 return ('[object Number]' === Object.prototype.toString.call(object)) &&
162 (0 === object % 1 && !common.isNegativeZero(object));
165 module.exports = new Type('tag:yaml.org,2002:int', {
167 resolve: resolveYamlInteger,
168 construct: constructYamlInteger,
169 predicate: isInteger,
171 binary: function (object) { return '0b' + object.toString(2); },
172 octal: function (object) { return '0' + object.toString(8); },
173 decimal: function (object) { return object.toString(10); },
174 hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); }
176 defaultStyle: 'decimal',
178 binary: [ 2, 'bin' ],
180 decimal: [ 10, 'dec' ],
181 hexadecimal: [ 16, 'hex' ]