forked from mongodb/mongo-csharp-driver
/
ObjectId.cs
400 lines (367 loc) · 13.9 KB
/
ObjectId.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/* Copyright 2010-2012 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace MongoDB.Bson
{
/// <summary>
/// Represents an ObjectId (see also BsonObjectId).
/// </summary>
[Serializable]
public struct ObjectId : IComparable<ObjectId>, IEquatable<ObjectId>
{
// private static fields
private static ObjectId __emptyInstance = default(ObjectId);
private static int __staticMachine;
private static short __staticPid;
private static int __staticIncrement; // high byte will be masked out when generating new ObjectId
// private fields
// 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
// the extra two bytes are not visible to anyone outside of this class and they buy us considerable simplification
// an additional advantage of this representation is that it will serialize to JSON without any 64 bit overflow problems
private int _timestamp;
private int _machine;
private short _pid;
private int _increment;
// static constructor
static ObjectId()
{
__staticMachine = GetMachineHash();
__staticPid = (short)Process.GetCurrentProcess().Id; // use low order two bytes only
__staticIncrement = (new Random()).Next();
}
// constructors
/// <summary>
/// Initializes a new instance of the ObjectId class.
/// </summary>
/// <param name="bytes">The value.</param>
public ObjectId(byte[] bytes)
{
Unpack(bytes, out _timestamp, out _machine, out _pid, out _increment);
}
/// <summary>
/// Initializes a new instance of the ObjectId class.
/// </summary>
/// <param name="timestamp">The timestamp.</param>
/// <param name="machine">The machine hash.</param>
/// <param name="pid">The PID.</param>
/// <param name="increment">The increment.</param>
public ObjectId(int timestamp, int machine, short pid, int increment)
{
_timestamp = timestamp;
_machine = machine;
_pid = pid;
_increment = increment;
}
/// <summary>
/// Initializes a new instance of the ObjectId class.
/// </summary>
/// <param name="value">The value.</param>
public ObjectId(string value)
{
Unpack(BsonUtils.ParseHexString(value), out _timestamp, out _machine, out _pid, out _increment);
}
// public static properties
/// <summary>
/// Gets an instance of ObjectId where the value is empty.
/// </summary>
public static ObjectId Empty
{
get { return __emptyInstance; }
}
// public properties
/// <summary>
/// Gets the timestamp.
/// </summary>
public int Timestamp
{
get { return _timestamp; }
}
/// <summary>
/// Gets the machine.
/// </summary>
public int Machine
{
get { return _machine; }
}
/// <summary>
/// Gets the PID.
/// </summary>
public short Pid
{
get { return _pid; }
}
/// <summary>
/// Gets the increment.
/// </summary>
public int Increment
{
get { return _increment; }
}
/// <summary>
/// Gets the creation time (derived from the timestamp).
/// </summary>
public DateTime CreationTime
{
get { return BsonConstants.UnixEpoch.AddSeconds(_timestamp); }
}
// public operators
/// <summary>
/// Compares two ObjectIds.
/// </summary>
/// <param name="lhs">The first ObjectId.</param>
/// <param name="rhs">The other ObjectId</param>
/// <returns>True if the first ObjectId is less than the second ObjectId.</returns>
public static bool operator <(ObjectId lhs, ObjectId rhs)
{
return lhs.CompareTo(rhs) < 0;
}
/// <summary>
/// Compares two ObjectIds.
/// </summary>
/// <param name="lhs">The first ObjectId.</param>
/// <param name="rhs">The other ObjectId</param>
/// <returns>True if the first ObjectId is less than or equal to the second ObjectId.</returns>
public static bool operator <=(ObjectId lhs, ObjectId rhs)
{
return lhs.CompareTo(rhs) <= 0;
}
/// <summary>
/// Compares two ObjectIds.
/// </summary>
/// <param name="lhs">The first ObjectId.</param>
/// <param name="rhs">The other ObjectId.</param>
/// <returns>True if the two ObjectIds are equal.</returns>
public static bool operator ==(ObjectId lhs, ObjectId rhs)
{
return lhs.Equals(rhs);
}
/// <summary>
/// Compares two ObjectIds.
/// </summary>
/// <param name="lhs">The first ObjectId.</param>
/// <param name="rhs">The other ObjectId.</param>
/// <returns>True if the two ObjectIds are not equal.</returns>
public static bool operator !=(ObjectId lhs, ObjectId rhs)
{
return !(lhs == rhs);
}
/// <summary>
/// Compares two ObjectIds.
/// </summary>
/// <param name="lhs">The first ObjectId.</param>
/// <param name="rhs">The other ObjectId</param>
/// <returns>True if the first ObjectId is greather than or equal to the second ObjectId.</returns>
public static bool operator >=(ObjectId lhs, ObjectId rhs)
{
return lhs.CompareTo(rhs) >= 0;
}
/// <summary>
/// Compares two ObjectIds.
/// </summary>
/// <param name="lhs">The first ObjectId.</param>
/// <param name="rhs">The other ObjectId</param>
/// <returns>True if the first ObjectId is greather than the second ObjectId.</returns>
public static bool operator >(ObjectId lhs, ObjectId rhs)
{
return lhs.CompareTo(rhs) > 0;
}
// public static methods
/// <summary>
/// Generates a new ObjectId with a unique value.
/// </summary>
/// <returns>A ObjectId.</returns>
public static ObjectId GenerateNewId()
{
int timestamp = GetCurrentTimestamp();
int increment = Interlocked.Increment(ref __staticIncrement) & 0x00ffffff; // only use low order 3 bytes
return new ObjectId(timestamp, __staticMachine, __staticPid, increment);
}
/// <summary>
/// Packs the components of an ObjectId into a byte array.
/// </summary>
/// <param name="timestamp">The timestamp.</param>
/// <param name="machine">The machine hash.</param>
/// <param name="pid">The PID.</param>
/// <param name="increment">The increment.</param>
/// <returns>A byte array.</returns>
public static byte[] Pack(int timestamp, int machine, short pid, int increment)
{
byte[] bytes = new byte[12];
bytes[0] = (byte)(timestamp >> 24);
bytes[1] = (byte)(timestamp >> 16);
bytes[2] = (byte)(timestamp >> 8);
bytes[3] = (byte)(timestamp);
bytes[4] = (byte)(machine >> 16);
bytes[5] = (byte)(machine >> 8);
bytes[6] = (byte)(machine);
bytes[7] = (byte)(pid >> 8);
bytes[8] = (byte)(pid);
bytes[9] = (byte)(increment >> 16);
bytes[10] = (byte)(increment >> 8);
bytes[11] = (byte)(increment);
return bytes;
}
/// <summary>
/// Parses a string and creates a new ObjectId.
/// </summary>
/// <param name="s">The string value.</param>
/// <returns>A ObjectId.</returns>
public static ObjectId Parse(string s)
{
ObjectId objectId;
if (TryParse(s, out objectId))
{
return objectId;
}
else
{
var message = string.Format("'{0}' is not a valid 24 digit hex string.", s);
throw new FormatException(message);
}
}
/// <summary>
/// Tries to parse a string and create a new ObjectId.
/// </summary>
/// <param name="s">The string value.</param>
/// <param name="objectId">The new ObjectId.</param>
/// <returns>True if the string was parsed successfully.</returns>
public static bool TryParse(string s, out ObjectId objectId)
{
if (s != null && s.Length == 24)
{
byte[] bytes;
if (BsonUtils.TryParseHexString(s, out bytes))
{
objectId = new ObjectId(bytes);
return true;
}
}
objectId = default(ObjectId);
return false;
}
/// <summary>
/// Unpacks a byte array into the components of an ObjectId.
/// </summary>
/// <param name="bytes">A byte array.</param>
/// <param name="timestamp">The timestamp.</param>
/// <param name="machine">The machine hash.</param>
/// <param name="pid">The PID.</param>
/// <param name="increment">The increment.</param>
public static void Unpack(byte[] bytes, out int timestamp, out int machine, out short pid, out int increment)
{
if (bytes.Length != 12)
{
throw new ArgumentOutOfRangeException("Byte array must be 12 bytes long.");
}
timestamp = (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3];
machine = (bytes[4] << 16) + (bytes[5] << 8) + bytes[6];
pid = (short)((bytes[7] << 8) + bytes[8]);
increment = (bytes[9] << 16) + (bytes[10] << 8) + bytes[11];
}
// private static methods
private static int GetMachineHash()
{
var hostName = Environment.MachineName; // use instead of Dns.HostName so it will work offline
var md5 = MD5.Create();
var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(hostName));
return (hash[0] << 16) + (hash[1] << 8) + hash[2]; // use first 3 bytes of hash
}
private static int GetCurrentTimestamp()
{
DateTime now = DateTime.UtcNow;
return (int)Math.Floor((now - BsonConstants.UnixEpoch).TotalSeconds);
}
// public methods
/// <summary>
/// Compares this ObjectId to another ObjectId.
/// </summary>
/// <param name="other">The other ObjectId.</param>
/// <returns>A 32-bit signed integer that indicates whether this ObjectId is less than, equal to, or greather than the other.</returns>
public int CompareTo(ObjectId other)
{
int r = _timestamp.CompareTo(other._timestamp);
if (r != 0) { return r; }
r = _machine.CompareTo(other._machine);
if (r != 0) { return r; }
r = _pid.CompareTo(other._pid);
if (r != 0) { return r; }
return _increment.CompareTo(other._increment);
}
/// <summary>
/// Compares this ObjectId to another ObjectId.
/// </summary>
/// <param name="rhs">The other ObjectId.</param>
/// <returns>True if the two ObjectIds are equal.</returns>
public bool Equals(ObjectId rhs)
{
return
_timestamp == rhs._timestamp &&
_machine == rhs._machine &&
_pid == rhs._pid &&
_increment == rhs._increment;
}
/// <summary>
/// Compares this ObjectId to another object.
/// </summary>
/// <param name="obj">The other object.</param>
/// <returns>True if the other object is an ObjectId and equal to this one.</returns>
public override bool Equals(object obj)
{
if (obj is ObjectId)
{
return Equals((ObjectId)obj);
}
else
{
return false;
}
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int hash = 17;
hash = 37 * hash + _timestamp.GetHashCode();
hash = 37 * hash + _machine.GetHashCode();
hash = 37 * hash + _pid.GetHashCode();
hash = 37 * hash + _increment.GetHashCode();
return hash;
}
/// <summary>
/// Converts the ObjectId to a byte array.
/// </summary>
/// <returns>A byte array.</returns>
public byte[] ToByteArray()
{
return Pack(_timestamp, _machine, _pid, _increment);
}
/// <summary>
/// Returns a string representation of the value.
/// </summary>
/// <returns>A string representation of the value.</returns>
public override string ToString()
{
return BsonUtils.ToHexString(Pack(_timestamp, _machine, _pid, _increment));
}
}
}