Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

objectid.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. // Custom inspect property name / symbol.
  2. var inspect = 'inspect';
  3. /**
  4. * Machine id.
  5. *
  6. * Create a random 3-byte value (i.e. unique for this
  7. * process). Other drivers use a md5 of the machine id here, but
  8. * that would mean an asyc call to gethostname, so we don't bother.
  9. * @ignore
  10. */
  11. var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10);
  12. // Regular expression that checks for hex value
  13. var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
  14. // Check if buffer exists
  15. try {
  16. if (Buffer && Buffer.from) {
  17. var hasBufferType = true;
  18. inspect = require('util').inspect.custom || 'inspect';
  19. }
  20. } catch (err) {
  21. hasBufferType = false;
  22. }
  23. /**
  24. * Create a new ObjectID instance
  25. *
  26. * @class
  27. * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
  28. * @property {number} generationTime The generation time of this ObjectId instance
  29. * @return {ObjectID} instance of ObjectID.
  30. */
  31. var ObjectID = function ObjectID(id) {
  32. // Duck-typing to support ObjectId from different npm packages
  33. if (id instanceof ObjectID) return id;
  34. if (!(this instanceof ObjectID)) return new ObjectID(id);
  35. this._bsontype = 'ObjectID';
  36. // The most common usecase (blank id, new objectId instance)
  37. if (id == null || typeof id === 'number') {
  38. // Generate a new id
  39. this.id = this.generate(id);
  40. // If we are caching the hex string
  41. if (ObjectID.cacheHexString) this.__id = this.toString('hex');
  42. // Return the object
  43. return;
  44. }
  45. // Check if the passed in id is valid
  46. var valid = ObjectID.isValid(id);
  47. // Throw an error if it's not a valid setup
  48. if (!valid && id != null) {
  49. throw new Error(
  50. 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
  51. );
  52. } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {
  53. return new ObjectID(new Buffer(id, 'hex'));
  54. } else if (valid && typeof id === 'string' && id.length === 24) {
  55. return ObjectID.createFromHexString(id);
  56. } else if (id != null && id.length === 12) {
  57. // assume 12 byte string
  58. this.id = id;
  59. } else if (id != null && id.toHexString) {
  60. // Duck-typing to support ObjectId from different npm packages
  61. return id;
  62. } else {
  63. throw new Error(
  64. 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
  65. );
  66. }
  67. if (ObjectID.cacheHexString) this.__id = this.toString('hex');
  68. };
  69. // Allow usage of ObjectId as well as ObjectID
  70. // var ObjectId = ObjectID;
  71. // Precomputed hex table enables speedy hex string conversion
  72. var hexTable = [];
  73. for (var i = 0; i < 256; i++) {
  74. hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16);
  75. }
  76. /**
  77. * Return the ObjectID id as a 24 byte hex string representation
  78. *
  79. * @method
  80. * @return {string} return the 24 byte hex string representation.
  81. */
  82. ObjectID.prototype.toHexString = function() {
  83. if (ObjectID.cacheHexString && this.__id) return this.__id;
  84. var hexString = '';
  85. if (!this.id || !this.id.length) {
  86. throw new Error(
  87. 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' +
  88. JSON.stringify(this.id) +
  89. ']'
  90. );
  91. }
  92. if (this.id instanceof _Buffer) {
  93. hexString = convertToHex(this.id);
  94. if (ObjectID.cacheHexString) this.__id = hexString;
  95. return hexString;
  96. }
  97. for (var i = 0; i < this.id.length; i++) {
  98. hexString += hexTable[this.id.charCodeAt(i)];
  99. }
  100. if (ObjectID.cacheHexString) this.__id = hexString;
  101. return hexString;
  102. };
  103. /**
  104. * Update the ObjectID index used in generating new ObjectID's on the driver
  105. *
  106. * @method
  107. * @return {number} returns next index value.
  108. * @ignore
  109. */
  110. ObjectID.prototype.get_inc = function() {
  111. return (ObjectID.index = (ObjectID.index + 1) % 0xffffff);
  112. };
  113. /**
  114. * Update the ObjectID index used in generating new ObjectID's on the driver
  115. *
  116. * @method
  117. * @return {number} returns next index value.
  118. * @ignore
  119. */
  120. ObjectID.prototype.getInc = function() {
  121. return this.get_inc();
  122. };
  123. /**
  124. * Generate a 12 byte id buffer used in ObjectID's
  125. *
  126. * @method
  127. * @param {number} [time] optional parameter allowing to pass in a second based timestamp.
  128. * @return {Buffer} return the 12 byte id buffer string.
  129. */
  130. ObjectID.prototype.generate = function(time) {
  131. if ('number' !== typeof time) {
  132. time = ~~(Date.now() / 1000);
  133. }
  134. // Use pid
  135. var pid =
  136. (typeof process === 'undefined' || process.pid === 1
  137. ? Math.floor(Math.random() * 100000)
  138. : process.pid) % 0xffff;
  139. var inc = this.get_inc();
  140. // Buffer used
  141. var buffer = new Buffer(12);
  142. // Encode time
  143. buffer[3] = time & 0xff;
  144. buffer[2] = (time >> 8) & 0xff;
  145. buffer[1] = (time >> 16) & 0xff;
  146. buffer[0] = (time >> 24) & 0xff;
  147. // Encode machine
  148. buffer[6] = MACHINE_ID & 0xff;
  149. buffer[5] = (MACHINE_ID >> 8) & 0xff;
  150. buffer[4] = (MACHINE_ID >> 16) & 0xff;
  151. // Encode pid
  152. buffer[8] = pid & 0xff;
  153. buffer[7] = (pid >> 8) & 0xff;
  154. // Encode index
  155. buffer[11] = inc & 0xff;
  156. buffer[10] = (inc >> 8) & 0xff;
  157. buffer[9] = (inc >> 16) & 0xff;
  158. // Return the buffer
  159. return buffer;
  160. };
  161. /**
  162. * Converts the id into a 24 byte hex string for printing
  163. *
  164. * @param {String} format The Buffer toString format parameter.
  165. * @return {String} return the 24 byte hex string representation.
  166. * @ignore
  167. */
  168. ObjectID.prototype.toString = function(format) {
  169. // Is the id a buffer then use the buffer toString method to return the format
  170. if (this.id && this.id.copy) {
  171. return this.id.toString(typeof format === 'string' ? format : 'hex');
  172. }
  173. // if(this.buffer )
  174. return this.toHexString();
  175. };
  176. /**
  177. * Converts to a string representation of this Id.
  178. *
  179. * @return {String} return the 24 byte hex string representation.
  180. * @ignore
  181. */
  182. ObjectID.prototype[inspect] = ObjectID.prototype.toString;
  183. /**
  184. * Converts to its JSON representation.
  185. *
  186. * @return {String} return the 24 byte hex string representation.
  187. * @ignore
  188. */
  189. ObjectID.prototype.toJSON = function() {
  190. return this.toHexString();
  191. };
  192. /**
  193. * Compares the equality of this ObjectID with `otherID`.
  194. *
  195. * @method
  196. * @param {object} otherID ObjectID instance to compare against.
  197. * @return {boolean} the result of comparing two ObjectID's
  198. */
  199. ObjectID.prototype.equals = function equals(otherId) {
  200. // var id;
  201. if (otherId instanceof ObjectID) {
  202. return this.toString() === otherId.toString();
  203. } else if (
  204. typeof otherId === 'string' &&
  205. ObjectID.isValid(otherId) &&
  206. otherId.length === 12 &&
  207. this.id instanceof _Buffer
  208. ) {
  209. return otherId === this.id.toString('binary');
  210. } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) {
  211. return otherId.toLowerCase() === this.toHexString();
  212. } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) {
  213. return otherId === this.id;
  214. } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) {
  215. return otherId.toHexString() === this.toHexString();
  216. } else {
  217. return false;
  218. }
  219. };
  220. /**
  221. * Returns the generation date (accurate up to the second) that this ID was generated.
  222. *
  223. * @method
  224. * @return {date} the generation date
  225. */
  226. ObjectID.prototype.getTimestamp = function() {
  227. var timestamp = new Date();
  228. var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24);
  229. timestamp.setTime(Math.floor(time) * 1000);
  230. return timestamp;
  231. };
  232. /**
  233. * @ignore
  234. */
  235. ObjectID.index = ~~(Math.random() * 0xffffff);
  236. /**
  237. * @ignore
  238. */
  239. ObjectID.createPk = function createPk() {
  240. return new ObjectID();
  241. };
  242. /**
  243. * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
  244. *
  245. * @method
  246. * @param {number} time an integer number representing a number of seconds.
  247. * @return {ObjectID} return the created ObjectID
  248. */
  249. ObjectID.createFromTime = function createFromTime(time) {
  250. var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  251. // Encode time into first 4 bytes
  252. buffer[3] = time & 0xff;
  253. buffer[2] = (time >> 8) & 0xff;
  254. buffer[1] = (time >> 16) & 0xff;
  255. buffer[0] = (time >> 24) & 0xff;
  256. // Return the new objectId
  257. return new ObjectID(buffer);
  258. };
  259. // Lookup tables
  260. //var encodeLookup = '0123456789abcdef'.split('');
  261. var decodeLookup = [];
  262. i = 0;
  263. while (i < 10) decodeLookup[0x30 + i] = i++;
  264. while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;
  265. var _Buffer = Buffer;
  266. var convertToHex = function(bytes) {
  267. return bytes.toString('hex');
  268. };
  269. /**
  270. * Creates an ObjectID from a hex string representation of an ObjectID.
  271. *
  272. * @method
  273. * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring.
  274. * @return {ObjectID} return the created ObjectID
  275. */
  276. ObjectID.createFromHexString = function createFromHexString(string) {
  277. // Throw an error if it's not a valid setup
  278. if (typeof string === 'undefined' || (string != null && string.length !== 24)) {
  279. throw new Error(
  280. 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
  281. );
  282. }
  283. // Use Buffer.from method if available
  284. if (hasBufferType) return new ObjectID(new Buffer(string, 'hex'));
  285. // Calculate lengths
  286. var array = new _Buffer(12);
  287. var n = 0;
  288. var i = 0;
  289. while (i < 24) {
  290. array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)];
  291. }
  292. return new ObjectID(array);
  293. };
  294. /**
  295. * Checks if a value is a valid bson ObjectId
  296. *
  297. * @method
  298. * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
  299. */
  300. ObjectID.isValid = function isValid(id) {
  301. if (id == null) return false;
  302. if (typeof id === 'number') {
  303. return true;
  304. }
  305. if (typeof id === 'string') {
  306. return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));
  307. }
  308. if (id instanceof ObjectID) {
  309. return true;
  310. }
  311. if (id instanceof _Buffer) {
  312. return true;
  313. }
  314. // Duck-Typing detection of ObjectId like objects
  315. if (id.toHexString) {
  316. return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id));
  317. }
  318. return false;
  319. };
  320. /**
  321. * @ignore
  322. */
  323. Object.defineProperty(ObjectID.prototype, 'generationTime', {
  324. enumerable: true,
  325. get: function() {
  326. return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24);
  327. },
  328. set: function(value) {
  329. // Encode time into first 4 bytes
  330. this.id[3] = value & 0xff;
  331. this.id[2] = (value >> 8) & 0xff;
  332. this.id[1] = (value >> 16) & 0xff;
  333. this.id[0] = (value >> 24) & 0xff;
  334. }
  335. });
  336. /**
  337. * Expose.
  338. */
  339. module.exports = ObjectID;
  340. module.exports.ObjectID = ObjectID;
  341. module.exports.ObjectId = ObjectID;