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

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