Meki Cherkaoui | f441d3a | 2012-04-22 15:17:52 -0700 | [diff] [blame] | 1 | /* |
| 2 | * @author: ucla-cs |
| 3 | * This class represents CCNTime Objects |
| 4 | */ |
| 5 | |
| 6 | var CCNTime = function CCNTime( |
| 7 | //long |
| 8 | msec) { |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | this.NANOS_MAX = 999877929; |
| 14 | |
| 15 | this.date = new Date(msec); |
| 16 | }; |
| 17 | |
| 18 | |
| 19 | /** |
| 20 | * Create a CCNTime |
| 21 | * @param timestamp source timestamp to initialize from, some precision will be lost |
| 22 | */ |
| 23 | |
| 24 | /** |
| 25 | * Create a CCNTime |
| 26 | * @param time source Date to initialize from, some precision will be lost |
| 27 | * as CCNTime does not round to unitary milliseconds |
| 28 | */ |
| 29 | CCNTime.prototype.setDate = function( |
| 30 | //Date |
| 31 | date) { |
| 32 | |
| 33 | this.date = date; |
| 34 | }; |
| 35 | |
| 36 | /** |
| 37 | * Create a CCNTime from its binary encoding |
| 38 | * @param binaryTime12 the binary representation of a CCNTime |
| 39 | */ |
| 40 | CCNTime.prototype.setDateBinary = function( |
| 41 | //byte [] |
| 42 | binaryTime12) { |
| 43 | |
| 44 | |
| 45 | if ((null == binaryTime12) || (binaryTime12.length == 0)) { |
| 46 | throw new IllegalArgumentException("Invalid binary time!"); |
| 47 | } |
| 48 | |
| 49 | |
| 50 | value = 0; |
| 51 | for(i = 0; i < binaryTime12.length; i++) { |
| 52 | value = value << 8; |
| 53 | // Java will assume the byte is signed, so extend it and trim it. |
| 54 | b = (binaryTime12[i]) & 0xFF; |
| 55 | value |= b; |
| 56 | } |
| 57 | |
| 58 | this.date = new Date(value); |
| 59 | |
| 60 | }; |
| 61 | |
| 62 | //byte[] |
| 63 | CCNTime.prototype.toBinaryTime = function() { |
| 64 | |
| 65 | |
| 66 | |
| 67 | return unsignedLongToByteArray(this.date.getTime()); |
| 68 | |
| 69 | } |
| 70 | |
| 71 | unsignedLongToByteArray= function( value) { |
| 72 | if( 0 == value ) |
| 73 | return [0]; |
| 74 | |
| 75 | if( 0 <= value && value <= 0x00FF ) { |
| 76 | //byte [] |
| 77 | bb = new Array[1]; |
| 78 | bb[0] = (value & 0x00FF); |
| 79 | return bb; |
| 80 | } |
| 81 | |
| 82 | |
| 83 | //byte [] |
| 84 | out = null; |
| 85 | //int |
| 86 | offset = -1; |
| 87 | for(var i = 7; i >=0; --i) { |
| 88 | //byte |
| 89 | b = ((value >> (i * 8)) & 0xFF); |
| 90 | if( out == null && b != 0 ) { |
| 91 | out = new Array(i+1);//byte[i+1]; |
| 92 | offset = i; |
| 93 | } |
| 94 | if( out != null ) |
| 95 | out[ offset - i ] = b; |
| 96 | } |
| 97 | return out; |
| 98 | } |
| 99 | |