ObjectId.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /* Copyright 2010-2014 MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Diagnostics;
  17. using System.Runtime.CompilerServices;
  18. using System.Security;
  19. using System.Security.Cryptography;
  20. using System.Text;
  21. using System.Threading;
  22. namespace MongoDB.Bson
  23. {
  24. /// <summary>
  25. /// Represents an ObjectId (see also BsonObjectId).
  26. /// </summary>
  27. [Serializable]
  28. public struct ObjectId : IComparable<ObjectId>, IEquatable<ObjectId>, IConvertible
  29. {
  30. // private static fields
  31. private static ObjectId __emptyInstance = default(ObjectId);
  32. private static int __staticMachine;
  33. private static short __staticPid;
  34. private static int __staticIncrement; // high byte will be masked out when generating new ObjectId
  35. // private fields
  36. // we're using 14 bytes instead of 12 to hold the ObjectId in memory but unlike a byte[] there is no additional object on the heap
  37. // the extra two bytes are not visible to anyone outside of this class and they buy us considerable simplification
  38. // an additional advantage of this representation is that it will serialize to JSON without any 64 bit overflow problems
  39. private int _timestamp;
  40. private int _machine;
  41. private short _pid;
  42. private int _increment;
  43. // static constructor
  44. static ObjectId()
  45. {
  46. __staticMachine = (GetMachineHash() + AppDomain.CurrentDomain.Id) & 0x00ffffff; // add AppDomain Id to ensure uniqueness across AppDomains
  47. __staticIncrement = (new Random()).Next();
  48. try
  49. {
  50. __staticPid = (short)GetCurrentProcessId(); // use low order two bytes only
  51. }
  52. catch (SecurityException)
  53. {
  54. __staticPid = 0;
  55. }
  56. }
  57. // constructors
  58. /// <summary>
  59. /// Initializes a new instance of the ObjectId class.
  60. /// </summary>
  61. /// <param name="bytes">The bytes.</param>
  62. public ObjectId(byte[] bytes)
  63. {
  64. if (bytes == null)
  65. {
  66. throw new ArgumentNullException("bytes");
  67. }
  68. Unpack(bytes, out _timestamp, out _machine, out _pid, out _increment);
  69. }
  70. /// <summary>
  71. /// Initializes a new instance of the ObjectId class.
  72. /// </summary>
  73. /// <param name="timestamp">The timestamp (expressed as a DateTime).</param>
  74. /// <param name="machine">The machine hash.</param>
  75. /// <param name="pid">The PID.</param>
  76. /// <param name="increment">The increment.</param>
  77. public ObjectId(DateTime timestamp, int machine, short pid, int increment)
  78. : this(GetTimestampFromDateTime(timestamp), machine, pid, increment)
  79. {
  80. }
  81. /// <summary>
  82. /// Initializes a new instance of the ObjectId class.
  83. /// </summary>
  84. /// <param name="timestamp">The timestamp.</param>
  85. /// <param name="machine">The machine hash.</param>
  86. /// <param name="pid">The PID.</param>
  87. /// <param name="increment">The increment.</param>
  88. public ObjectId(int timestamp, int machine, short pid, int increment)
  89. {
  90. if ((machine & 0xff000000) != 0)
  91. {
  92. throw new ArgumentOutOfRangeException("machine", "The machine value must be between 0 and 16777215 (it must fit in 3 bytes).");
  93. }
  94. if ((increment & 0xff000000) != 0)
  95. {
  96. throw new ArgumentOutOfRangeException("increment", "The increment value must be between 0 and 16777215 (it must fit in 3 bytes).");
  97. }
  98. _timestamp = timestamp;
  99. _machine = machine;
  100. _pid = pid;
  101. _increment = increment;
  102. }
  103. /// <summary>
  104. /// Initializes a new instance of the ObjectId class.
  105. /// </summary>
  106. /// <param name="value">The value.</param>
  107. public ObjectId(string value)
  108. {
  109. if (value == null)
  110. {
  111. throw new ArgumentNullException("value");
  112. }
  113. Unpack(BsonUtils.ParseHexString(value), out _timestamp, out _machine, out _pid, out _increment);
  114. }
  115. // public static properties
  116. /// <summary>
  117. /// Gets an instance of ObjectId where the value is empty.
  118. /// </summary>
  119. public static ObjectId Empty
  120. {
  121. get { return __emptyInstance; }
  122. }
  123. // public properties
  124. /// <summary>
  125. /// Gets the timestamp.
  126. /// </summary>
  127. public int Timestamp
  128. {
  129. get { return _timestamp; }
  130. }
  131. /// <summary>
  132. /// Gets the machine.
  133. /// </summary>
  134. public int Machine
  135. {
  136. get { return _machine; }
  137. }
  138. /// <summary>
  139. /// Gets the PID.
  140. /// </summary>
  141. public short Pid
  142. {
  143. get { return _pid; }
  144. }
  145. /// <summary>
  146. /// Gets the increment.
  147. /// </summary>
  148. public int Increment
  149. {
  150. get { return _increment; }
  151. }
  152. /// <summary>
  153. /// Gets the creation time (derived from the timestamp).
  154. /// </summary>
  155. public DateTime CreationTime
  156. {
  157. get { return BsonConstants.UnixEpoch.AddSeconds(_timestamp); }
  158. }
  159. // public operators
  160. /// <summary>
  161. /// Compares two ObjectIds.
  162. /// </summary>
  163. /// <param name="lhs">The first ObjectId.</param>
  164. /// <param name="rhs">The other ObjectId</param>
  165. /// <returns>True if the first ObjectId is less than the second ObjectId.</returns>
  166. public static bool operator <(ObjectId lhs, ObjectId rhs)
  167. {
  168. return lhs.CompareTo(rhs) < 0;
  169. }
  170. /// <summary>
  171. /// Compares two ObjectIds.
  172. /// </summary>
  173. /// <param name="lhs">The first ObjectId.</param>
  174. /// <param name="rhs">The other ObjectId</param>
  175. /// <returns>True if the first ObjectId is less than or equal to the second ObjectId.</returns>
  176. public static bool operator <=(ObjectId lhs, ObjectId rhs)
  177. {
  178. return lhs.CompareTo(rhs) <= 0;
  179. }
  180. /// <summary>
  181. /// Compares two ObjectIds.
  182. /// </summary>
  183. /// <param name="lhs">The first ObjectId.</param>
  184. /// <param name="rhs">The other ObjectId.</param>
  185. /// <returns>True if the two ObjectIds are equal.</returns>
  186. public static bool operator ==(ObjectId lhs, ObjectId rhs)
  187. {
  188. return lhs.Equals(rhs);
  189. }
  190. /// <summary>
  191. /// Compares two ObjectIds.
  192. /// </summary>
  193. /// <param name="lhs">The first ObjectId.</param>
  194. /// <param name="rhs">The other ObjectId.</param>
  195. /// <returns>True if the two ObjectIds are not equal.</returns>
  196. public static bool operator !=(ObjectId lhs, ObjectId rhs)
  197. {
  198. return !(lhs == rhs);
  199. }
  200. /// <summary>
  201. /// Compares two ObjectIds.
  202. /// </summary>
  203. /// <param name="lhs">The first ObjectId.</param>
  204. /// <param name="rhs">The other ObjectId</param>
  205. /// <returns>True if the first ObjectId is greather than or equal to the second ObjectId.</returns>
  206. public static bool operator >=(ObjectId lhs, ObjectId rhs)
  207. {
  208. return lhs.CompareTo(rhs) >= 0;
  209. }
  210. /// <summary>
  211. /// Compares two ObjectIds.
  212. /// </summary>
  213. /// <param name="lhs">The first ObjectId.</param>
  214. /// <param name="rhs">The other ObjectId</param>
  215. /// <returns>True if the first ObjectId is greather than the second ObjectId.</returns>
  216. public static bool operator >(ObjectId lhs, ObjectId rhs)
  217. {
  218. return lhs.CompareTo(rhs) > 0;
  219. }
  220. // public static methods
  221. /// <summary>
  222. /// Generates a new ObjectId with a unique value.
  223. /// </summary>
  224. /// <returns>An ObjectId.</returns>
  225. public static ObjectId GenerateNewId()
  226. {
  227. return GenerateNewId(GetTimestampFromDateTime(DateTime.UtcNow));
  228. }
  229. /// <summary>
  230. /// Generates a new ObjectId with a unique value (with the timestamp component based on a given DateTime).
  231. /// </summary>
  232. /// <param name="timestamp">The timestamp component (expressed as a DateTime).</param>
  233. /// <returns>An ObjectId.</returns>
  234. public static ObjectId GenerateNewId(DateTime timestamp)
  235. {
  236. return GenerateNewId(GetTimestampFromDateTime(timestamp));
  237. }
  238. /// <summary>
  239. /// Generates a new ObjectId with a unique value (with the given timestamp).
  240. /// </summary>
  241. /// <param name="timestamp">The timestamp component.</param>
  242. /// <returns>An ObjectId.</returns>
  243. public static ObjectId GenerateNewId(int timestamp)
  244. {
  245. int increment = Interlocked.Increment(ref __staticIncrement) & 0x00ffffff; // only use low order 3 bytes
  246. return new ObjectId(timestamp, __staticMachine, __staticPid, increment);
  247. }
  248. /// <summary>
  249. /// Packs the components of an ObjectId into a byte array.
  250. /// </summary>
  251. /// <param name="timestamp">The timestamp.</param>
  252. /// <param name="machine">The machine hash.</param>
  253. /// <param name="pid">The PID.</param>
  254. /// <param name="increment">The increment.</param>
  255. /// <returns>A byte array.</returns>
  256. public static byte[] Pack(int timestamp, int machine, short pid, int increment)
  257. {
  258. if ((machine & 0xff000000) != 0)
  259. {
  260. throw new ArgumentOutOfRangeException("machine", "The machine value must be between 0 and 16777215 (it must fit in 3 bytes).");
  261. }
  262. if ((increment & 0xff000000) != 0)
  263. {
  264. throw new ArgumentOutOfRangeException("increment", "The increment value must be between 0 and 16777215 (it must fit in 3 bytes).");
  265. }
  266. byte[] bytes = new byte[12];
  267. bytes[0] = (byte)(timestamp >> 24);
  268. bytes[1] = (byte)(timestamp >> 16);
  269. bytes[2] = (byte)(timestamp >> 8);
  270. bytes[3] = (byte)(timestamp);
  271. bytes[4] = (byte)(machine >> 16);
  272. bytes[5] = (byte)(machine >> 8);
  273. bytes[6] = (byte)(machine);
  274. bytes[7] = (byte)(pid >> 8);
  275. bytes[8] = (byte)(pid);
  276. bytes[9] = (byte)(increment >> 16);
  277. bytes[10] = (byte)(increment >> 8);
  278. bytes[11] = (byte)(increment);
  279. return bytes;
  280. }
  281. /// <summary>
  282. /// Parses a string and creates a new ObjectId.
  283. /// </summary>
  284. /// <param name="s">The string value.</param>
  285. /// <returns>A ObjectId.</returns>
  286. public static ObjectId Parse(string s)
  287. {
  288. if (s == null)
  289. {
  290. throw new ArgumentNullException("s");
  291. }
  292. ObjectId objectId;
  293. if (TryParse(s, out objectId))
  294. {
  295. return objectId;
  296. }
  297. else
  298. {
  299. var message = string.Format("'{0}' is not a valid 24 digit hex string.", s);
  300. throw new FormatException(message);
  301. }
  302. }
  303. /// <summary>
  304. /// Tries to parse a string and create a new ObjectId.
  305. /// </summary>
  306. /// <param name="s">The string value.</param>
  307. /// <param name="objectId">The new ObjectId.</param>
  308. /// <returns>True if the string was parsed successfully.</returns>
  309. public static bool TryParse(string s, out ObjectId objectId)
  310. {
  311. // don't throw ArgumentNullException if s is null
  312. if (s != null && s.Length == 24)
  313. {
  314. byte[] bytes;
  315. if (BsonUtils.TryParseHexString(s, out bytes))
  316. {
  317. objectId = new ObjectId(bytes);
  318. return true;
  319. }
  320. }
  321. objectId = default(ObjectId);
  322. return false;
  323. }
  324. /// <summary>
  325. /// Unpacks a byte array into the components of an ObjectId.
  326. /// </summary>
  327. /// <param name="bytes">A byte array.</param>
  328. /// <param name="timestamp">The timestamp.</param>
  329. /// <param name="machine">The machine hash.</param>
  330. /// <param name="pid">The PID.</param>
  331. /// <param name="increment">The increment.</param>
  332. public static void Unpack(byte[] bytes, out int timestamp, out int machine, out short pid, out int increment)
  333. {
  334. if (bytes == null)
  335. {
  336. throw new ArgumentNullException("bytes");
  337. }
  338. if (bytes.Length != 12)
  339. {
  340. throw new ArgumentOutOfRangeException("bytes", "Byte array must be 12 bytes long.");
  341. }
  342. timestamp = (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3];
  343. machine = (bytes[4] << 16) + (bytes[5] << 8) + bytes[6];
  344. pid = (short)((bytes[7] << 8) + bytes[8]);
  345. increment = (bytes[9] << 16) + (bytes[10] << 8) + bytes[11];
  346. }
  347. // private static methods
  348. /// <summary>
  349. /// Gets the current process id. This method exists because of how CAS operates on the call stack, checking
  350. /// for permissions before executing the method. Hence, if we inlined this call, the calling method would not execute
  351. /// before throwing an exception requiring the try/catch at an even higher level that we don't necessarily control.
  352. /// </summary>
  353. [MethodImpl(MethodImplOptions.NoInlining)]
  354. private static int GetCurrentProcessId()
  355. {
  356. return Process.GetCurrentProcess().Id;
  357. }
  358. private static int GetMachineHash()
  359. {
  360. var hostName = Environment.MachineName; // use instead of Dns.HostName so it will work offline
  361. var md5 = MD5.Create();
  362. var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(hostName));
  363. return (hash[0] << 16) + (hash[1] << 8) + hash[2]; // use first 3 bytes of hash
  364. }
  365. private static int GetTimestampFromDateTime(DateTime timestamp)
  366. {
  367. return (int)Math.Floor((BsonUtils.ToUniversalTime(timestamp) - BsonConstants.UnixEpoch).TotalSeconds);
  368. }
  369. // public methods
  370. /// <summary>
  371. /// Compares this ObjectId to another ObjectId.
  372. /// </summary>
  373. /// <param name="other">The other ObjectId.</param>
  374. /// <returns>A 32-bit signed integer that indicates whether this ObjectId is less than, equal to, or greather than the other.</returns>
  375. public int CompareTo(ObjectId other)
  376. {
  377. int r = _timestamp.CompareTo(other._timestamp);
  378. if (r != 0) { return r; }
  379. r = _machine.CompareTo(other._machine);
  380. if (r != 0) { return r; }
  381. r = _pid.CompareTo(other._pid);
  382. if (r != 0) { return r; }
  383. return _increment.CompareTo(other._increment);
  384. }
  385. /// <summary>
  386. /// Compares this ObjectId to another ObjectId.
  387. /// </summary>
  388. /// <param name="rhs">The other ObjectId.</param>
  389. /// <returns>True if the two ObjectIds are equal.</returns>
  390. public bool Equals(ObjectId rhs)
  391. {
  392. return
  393. _timestamp == rhs._timestamp &&
  394. _machine == rhs._machine &&
  395. _pid == rhs._pid &&
  396. _increment == rhs._increment;
  397. }
  398. /// <summary>
  399. /// Compares this ObjectId to another object.
  400. /// </summary>
  401. /// <param name="obj">The other object.</param>
  402. /// <returns>True if the other object is an ObjectId and equal to this one.</returns>
  403. public override bool Equals(object obj)
  404. {
  405. if (obj is ObjectId)
  406. {
  407. return Equals((ObjectId)obj);
  408. }
  409. else
  410. {
  411. return false;
  412. }
  413. }
  414. /// <summary>
  415. /// Gets the hash code.
  416. /// </summary>
  417. /// <returns>The hash code.</returns>
  418. public override int GetHashCode()
  419. {
  420. int hash = 17;
  421. hash = 37 * hash + _timestamp.GetHashCode();
  422. hash = 37 * hash + _machine.GetHashCode();
  423. hash = 37 * hash + _pid.GetHashCode();
  424. hash = 37 * hash + _increment.GetHashCode();
  425. return hash;
  426. }
  427. /// <summary>
  428. /// Converts the ObjectId to a byte array.
  429. /// </summary>
  430. /// <returns>A byte array.</returns>
  431. public byte[] ToByteArray()
  432. {
  433. return Pack(_timestamp, _machine, _pid, _increment);
  434. }
  435. /// <summary>
  436. /// Returns a string representation of the value.
  437. /// </summary>
  438. /// <returns>A string representation of the value.</returns>
  439. public override string ToString()
  440. {
  441. return BsonUtils.ToHexString(Pack(_timestamp, _machine, _pid, _increment));
  442. }
  443. // explicit IConvertible implementation
  444. TypeCode IConvertible.GetTypeCode()
  445. {
  446. return TypeCode.Object;
  447. }
  448. bool IConvertible.ToBoolean(IFormatProvider provider)
  449. {
  450. throw new InvalidCastException();
  451. }
  452. byte IConvertible.ToByte(IFormatProvider provider)
  453. {
  454. throw new InvalidCastException();
  455. }
  456. char IConvertible.ToChar(IFormatProvider provider)
  457. {
  458. throw new InvalidCastException();
  459. }
  460. DateTime IConvertible.ToDateTime(IFormatProvider provider)
  461. {
  462. throw new InvalidCastException();
  463. }
  464. decimal IConvertible.ToDecimal(IFormatProvider provider)
  465. {
  466. throw new InvalidCastException();
  467. }
  468. double IConvertible.ToDouble(IFormatProvider provider)
  469. {
  470. throw new InvalidCastException();
  471. }
  472. short IConvertible.ToInt16(IFormatProvider provider)
  473. {
  474. throw new InvalidCastException();
  475. }
  476. int IConvertible.ToInt32(IFormatProvider provider)
  477. {
  478. throw new InvalidCastException();
  479. }
  480. long IConvertible.ToInt64(IFormatProvider provider)
  481. {
  482. throw new InvalidCastException();
  483. }
  484. sbyte IConvertible.ToSByte(IFormatProvider provider)
  485. {
  486. throw new InvalidCastException();
  487. }
  488. float IConvertible.ToSingle(IFormatProvider provider)
  489. {
  490. throw new InvalidCastException();
  491. }
  492. string IConvertible.ToString(IFormatProvider provider)
  493. {
  494. return ToString();
  495. }
  496. object IConvertible.ToType(Type conversionType, IFormatProvider provider)
  497. {
  498. switch (Type.GetTypeCode(conversionType))
  499. {
  500. case TypeCode.String:
  501. return ((IConvertible)this).ToString(provider);
  502. case TypeCode.Object:
  503. if (conversionType == typeof(object) || conversionType == typeof(ObjectId))
  504. {
  505. return this;
  506. }
  507. if (conversionType == typeof(BsonObjectId))
  508. {
  509. return new BsonObjectId(this);
  510. }
  511. if (conversionType == typeof(BsonString))
  512. {
  513. return new BsonString(((IConvertible)this).ToString(provider));
  514. }
  515. break;
  516. }
  517. throw new InvalidCastException();
  518. }
  519. ushort IConvertible.ToUInt16(IFormatProvider provider)
  520. {
  521. throw new InvalidCastException();
  522. }
  523. uint IConvertible.ToUInt32(IFormatProvider provider)
  524. {
  525. throw new InvalidCastException();
  526. }
  527. ulong IConvertible.ToUInt64(IFormatProvider provider)
  528. {
  529. throw new InvalidCastException();
  530. }
  531. }
  532. }