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) {
21 if (data === null) return false;
23 var max = data.length,
28 if (!max) return false;
33 if (ch === '-' || ch === '+') {
39 if (index + 1 === max) return true;
42 // base 2, base 8, base 16
48 for (; index < max; index++) {
50 if (ch === '_') continue;
51 if (ch !== '0' && ch !== '1') return false;
62 for (; index < max; index++) {
64 if (ch === '_') continue;
65 if (!isHexCode(data.charCodeAt(index))) return false;
72 for (; index < max; index++) {
74 if (ch === '_') continue;
75 if (!isOctCode(data.charCodeAt(index))) return false;
81 // base 10 (except 0) or base 60
83 for (; index < max; index++) {
85 if (ch === '_') continue;
86 if (ch === ':') break;
87 if (!isDecCode(data.charCodeAt(index))) {
93 if (!hasDigits) return false;
96 if (ch !== ':') return true;
98 // base60 almost not used, no needs to optimize
99 return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
102 function constructYamlInteger(data) {
103 var value = data, sign = 1, ch, base, digits = [];
105 if (value.indexOf('_') !== -1) {
106 value = value.replace(/_/g, '');
111 if (ch === '-' || ch === '+') {
112 if (ch === '-') sign = -1;
113 value = value.slice(1);
117 if (value === '0') return 0;
120 if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
121 if (value[1] === 'x') return sign * parseInt(value, 16);
122 return sign * parseInt(value, 8);
125 if (value.indexOf(':') !== -1) {
126 value.split(':').forEach(function (v) {
127 digits.unshift(parseInt(v, 10));
133 digits.forEach(function (d) {
142 return sign * parseInt(value, 10);
145 function isInteger(object) {
146 return (Object.prototype.toString.call(object)) === '[object Number]' &&
147 (object % 1 === 0 && !common.isNegativeZero(object));
150 module.exports = new Type('tag:yaml.org,2002:int', {
152 resolve: resolveYamlInteger,
153 construct: constructYamlInteger,
154 predicate: isInteger,
156 binary: function (object) { return '0b' + object.toString(2); },
157 octal: function (object) { return '0' + object.toString(8); },
158 decimal: function (object) { return object.toString(10); },
159 hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); }
161 defaultStyle: 'decimal',
163 binary: [ 2, 'bin' ],
165 decimal: [ 10, 'dec' ],
166 hexadecimal: [ 16, 'hex' ]