diff --git a/src/pyson.js b/src/pyson.js index 331173854a..1c8130e1b5 100644 --- a/src/pyson.js +++ b/src/pyson.js @@ -799,6 +799,55 @@ obj.ms, obj.dy, obj.dM, obj.dd, obj.dh, obj.dm, obj.ds, obj.dms); }; + Sao.PYSON.eval.TimeDelta = function(days, seconds, microseconds) { + return new Sao.PYSON.TimeDelta(days, seconds, microseconds); + }; + Sao.PYSON.TimeDelta = Sao.class_(Sao.PYSON.PYSON, { + init: function(days, seconds, microseconds) { + Sao.PYSON.TimeDelta._super.init.call(this); + if (days === undefined) days = 0; + if (seconds === undefined) seconds = 0; + if (microseconds === undefined) microseconds = 0; + + function test(value, name) { + if (value instanceof Sao.PYSON.TimeDelta) { + if (jQuery(value.types()).not(['number']).length) + { + throw name + ' must be an integer'; + } + } else { + if (typeof value != 'number') { + throw name + ' must be an integer'; + } + } + return value; + } + this._days = test(days, 'days'); + this._seconds = test(seconds, 'seconds'); + this._microseconds = test(microseconds, 'microseconds'); + }, + pyson: function() { + return { + '__class__': 'TimeDelta', + 'd': this._days, + 's': this._seconds, + 'm': this._microseconds, + }; + }, + types: function() { + return ['object']; + }, + __string_params__: function() { + return [this._days, this._seconds, this._microseconds]; + }, + }); + Sao.PYSON.TimeDelta.eval_ = function(value, context) { + return Sao.TimeDelta(value.d, value.s, value.m / 1000); + }; + Sao.PYSON.TimeDelta.init_from_object = function(obj) { + return new Sao.PYSON.TimeDelta(obj.d, obj.s, obj.microseconds); + }; + Sao.PYSON.eval.Len = function(value) { return new Sao.PYSON.Len(value); }; diff --git a/tests/sao.js b/tests/sao.js index 26841a352c..b970becfbc 100644 --- a/tests/sao.js +++ b/tests/sao.js @@ -877,6 +877,36 @@ 'DateTime(2010, 1, 12, 10, 30, 20, 0, -1, 12, -7, 2, 15, 30, 1)'); }); + QUnit.test('PYSON TimeDelta', function() { + var value = new Sao.PYSON.TimeDelta(1, 2, 3).pyson(); + QUnit.strictEqual(value.__class__, 'TimeDelta', + 'TimeDelta(1, 2, 3).pyson()'); + QUnit.strictEqual(value.d, 1, + 'TimeDelta(1, 2, 3).pyson()'); + QUnit.strictEqual(value.s, 2, + 'TimeDelta(1, 2, 3).pyson()'); + QUnit.strictEqual(value.m, 3, + 'TimeDelta(1, 2, 3).pyson()'); + + QUnit.throws(function() { + new Sao.PYSON.TimeDelta('test'); + }, 'days must be integer'); + + QUnit.ok(Sao.common.compare( + new Sao.PYSON.TimeDelta(1, 2, 3).types(), ['object']), + 'TimeDelta(1, 2, 3).types()'); + + var eval_ = new Sao.PYSON.Encoder().encode( + new Sao.PYSON.TimeDelta(1, 2, 3)); + QUnit.strictEqual( + new Sao.PYSON.Decoder().decode(eval_).valueOf(), + Sao.TimeDelta(1, 2, 3 / 1000).valueOf()); + + QUnit.strictEqual( + new Sao.PYSON.TimeDelta(1, 2, 3).toString(), + 'TimeDelta(1, 2, 3)'); + }); + QUnit.test('PYSON Len', function() { var value = new Sao.PYSON.Len([1, 2, 3]).pyson(); QUnit.strictEqual(value.__class__, 'Len', 'Len([1, 2, 3]).pyson()');