-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathObjectId.cs
592 lines (532 loc) · 20.2 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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/* Copyright 2010-present MongoDB 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.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace MongoDB.Bson
{
/// <summary>
/// Represents an ObjectId (see also BsonObjectId).
/// </summary>
public struct ObjectId : IComparable<ObjectId>, IEquatable<ObjectId>, IConvertible
{
// private static fields
private static readonly ObjectId __emptyInstance = default(ObjectId);
private static readonly long __random = CalculateRandomValue();
private static int __staticIncrement = (new Random()).Next();
// private fields
private readonly int _a;
private readonly int _b;
private readonly int _c;
// constructors
/// <summary>
/// Initializes a new instance of the ObjectId class.
/// </summary>
/// <param name="bytes">The bytes.</param>
public ObjectId(byte[] bytes)
{
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
if (bytes.Length != 12)
{
throw new ArgumentException("Byte array must be 12 bytes long", "bytes");
}
FromByteArray(bytes, 0, out _a, out _b, out _c);
}
/// <summary>
/// Initializes a new instance of the ObjectId class.
/// </summary>
/// <param name="bytes">The bytes.</param>
/// <param name="index">The index into the byte array where the ObjectId starts.</param>
internal ObjectId(byte[] bytes, int index)
{
FromByteArray(bytes, index, out _a, out _b, out _c);
}
/// <summary>
/// Initializes a new instance of the ObjectId class.
/// </summary>
/// <param name="value">The value.</param>
public ObjectId(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
var bytes = BsonUtils.ParseHexString(value);
FromByteArray(bytes, 0, out _a, out _b, out _c);
}
private ObjectId(int a, int b, int c)
{
_a = a;
_b = b;
_c = c;
}
// 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 _a; }
}
/// <summary>
/// Gets the creation time (derived from the timestamp).
/// </summary>
public DateTime CreationTime
{
get { return BsonConstants.UnixEpoch.AddSeconds((uint)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>An ObjectId.</returns>
public static ObjectId GenerateNewId()
{
return GenerateNewId(GetTimestampFromDateTime(DateTime.UtcNow));
}
/// <summary>
/// Generates a new ObjectId with a unique value (with the timestamp component based on a given DateTime).
/// </summary>
/// <param name="timestamp">The timestamp component (expressed as a DateTime).</param>
/// <returns>An ObjectId.</returns>
public static ObjectId GenerateNewId(DateTime timestamp)
{
return GenerateNewId(GetTimestampFromDateTime(timestamp));
}
/// <summary>
/// Generates a new ObjectId with a unique value (with the given timestamp).
/// </summary>
/// <param name="timestamp">The timestamp component.</param>
/// <returns>An ObjectId.</returns>
public static ObjectId GenerateNewId(int timestamp)
{
int increment = Interlocked.Increment(ref __staticIncrement) & 0x00ffffff; // only use low order 3 bytes
return Create(timestamp, __random, increment);
}
/// <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)
{
if (s == null)
{
throw new ArgumentNullException("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)
{
// don't throw ArgumentNullException if s is null
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;
}
// internal static methods
internal static long CalculateRandomValue()
{
#if NET472_OR_GREATER
var seed = (int)DateTime.UtcNow.Ticks ^ GetMachineHash() ^ GetPid();
var random = new Random(seed);
#else
var random = new Random();
#endif
var high = random.Next();
var low = random.Next();
var combined = (long)((ulong)(uint)high << 32 | (ulong)(uint)low);
return combined & 0xffffffffff; // low order 5 bytes
}
// private static methods
private static ObjectId Create(int timestamp, long random, int increment)
{
if (random < 0 || random > 0xffffffffff)
{
throw new ArgumentOutOfRangeException(nameof(random), "The random value must be between 0 and 1099511627775 (it must fit in 5 bytes).");
}
if (increment < 0 || increment > 0xffffff)
{
throw new ArgumentOutOfRangeException(nameof(increment), "The increment value must be between 0 and 16777215 (it must fit in 3 bytes).");
}
var a = timestamp;
var b = (int)(random >> 8); // first 4 bytes of random
var c = (int)(random << 24) | increment; // 5th byte of random and 3 byte increment
return new ObjectId(a, b, c);
}
/// <summary>
/// Gets the current process id. This method exists because of how CAS operates on the call stack, checking
/// for permissions before executing the method. Hence, if we inlined this call, the calling method would not execute
/// before throwing an exception requiring the try/catch at an even higher level that we don't necessarily control.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private static int GetCurrentProcessId()
{
using var process = Process.GetCurrentProcess();
return process.Id;
}
private static int GetMachineHash()
{
// use instead of Dns.HostName so it will work offline
var machineName = GetMachineName();
return 0x00ffffff & machineName.GetHashCode(); // use first 3 bytes of hash
}
private static string GetMachineName()
{
try
{
return Environment.MachineName;
}
catch
{
return "";
}
}
private static short GetPid()
{
try
{
return (short)GetCurrentProcessId(); // use low order two bytes only
}
catch
{
return 0;
}
}
private static int GetTimestampFromDateTime(DateTime timestamp)
{
var secondsSinceEpoch = (long)Math.Floor((BsonUtils.ToUniversalTime(timestamp) - BsonConstants.UnixEpoch).TotalSeconds);
if (secondsSinceEpoch < uint.MinValue || secondsSinceEpoch > uint.MaxValue)
{
throw new ArgumentOutOfRangeException("timestamp");
}
return (int)(uint)secondsSinceEpoch;
}
private static void FromByteArray(byte[] bytes, int offset, out int a, out int b, out int c)
{
a = (bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3];
b = (bytes[offset + 4] << 24) | (bytes[offset + 5] << 16) | (bytes[offset + 6] << 8) | bytes[offset + 7];
c = (bytes[offset + 8] << 24) | (bytes[offset + 9] << 16) | (bytes[offset + 10] << 8) | bytes[offset + 11];
}
// 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 result = ((uint)_a).CompareTo((uint)other._a);
if (result != 0) { return result; }
result = ((uint)_b).CompareTo((uint)other._b);
if (result != 0) { return result; }
return ((uint)_c).CompareTo((uint)other._c);
}
/// <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
_a == rhs._a &&
_b == rhs._b &&
_c == rhs._c;
}
/// <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 + _a.GetHashCode();
hash = 37 * hash + _b.GetHashCode();
hash = 37 * hash + _c.GetHashCode();
return hash;
}
/// <summary>
/// Converts the ObjectId to a byte array.
/// </summary>
/// <returns>A byte array.</returns>
public byte[] ToByteArray()
{
var bytes = new byte[12];
ToByteArray(bytes, 0);
return bytes;
}
/// <summary>
/// Converts the ObjectId to a byte array.
/// </summary>
/// <param name="destination">The destination.</param>
/// <param name="offset">The offset.</param>
public void ToByteArray(byte[] destination, int offset)
{
if (destination == null)
{
throw new ArgumentNullException("destination");
}
if (offset + 12 > destination.Length)
{
throw new ArgumentException("Not enough room in destination buffer.", "offset");
}
destination[offset + 0] = (byte)(_a >> 24);
destination[offset + 1] = (byte)(_a >> 16);
destination[offset + 2] = (byte)(_a >> 8);
destination[offset + 3] = (byte)(_a);
destination[offset + 4] = (byte)(_b >> 24);
destination[offset + 5] = (byte)(_b >> 16);
destination[offset + 6] = (byte)(_b >> 8);
destination[offset + 7] = (byte)(_b);
destination[offset + 8] = (byte)(_c >> 24);
destination[offset + 9] = (byte)(_c >> 16);
destination[offset + 10] = (byte)(_c >> 8);
destination[offset + 11] = (byte)(_c);
}
/// <summary>
/// Returns a string representation of the value.
/// </summary>
/// <returns>A string representation of the value.</returns>
public override string ToString()
{
var c = new char[24];
c[0] = BsonUtils.ToHexChar((_a >> 28) & 0x0f);
c[1] = BsonUtils.ToHexChar((_a >> 24) & 0x0f);
c[2] = BsonUtils.ToHexChar((_a >> 20) & 0x0f);
c[3] = BsonUtils.ToHexChar((_a >> 16) & 0x0f);
c[4] = BsonUtils.ToHexChar((_a >> 12) & 0x0f);
c[5] = BsonUtils.ToHexChar((_a >> 8) & 0x0f);
c[6] = BsonUtils.ToHexChar((_a >> 4) & 0x0f);
c[7] = BsonUtils.ToHexChar(_a & 0x0f);
c[8] = BsonUtils.ToHexChar((_b >> 28) & 0x0f);
c[9] = BsonUtils.ToHexChar((_b >> 24) & 0x0f);
c[10] = BsonUtils.ToHexChar((_b >> 20) & 0x0f);
c[11] = BsonUtils.ToHexChar((_b >> 16) & 0x0f);
c[12] = BsonUtils.ToHexChar((_b >> 12) & 0x0f);
c[13] = BsonUtils.ToHexChar((_b >> 8) & 0x0f);
c[14] = BsonUtils.ToHexChar((_b >> 4) & 0x0f);
c[15] = BsonUtils.ToHexChar(_b & 0x0f);
c[16] = BsonUtils.ToHexChar((_c >> 28) & 0x0f);
c[17] = BsonUtils.ToHexChar((_c >> 24) & 0x0f);
c[18] = BsonUtils.ToHexChar((_c >> 20) & 0x0f);
c[19] = BsonUtils.ToHexChar((_c >> 16) & 0x0f);
c[20] = BsonUtils.ToHexChar((_c >> 12) & 0x0f);
c[21] = BsonUtils.ToHexChar((_c >> 8) & 0x0f);
c[22] = BsonUtils.ToHexChar((_c >> 4) & 0x0f);
c[23] = BsonUtils.ToHexChar(_c & 0x0f);
return new string(c);
}
// explicit IConvertible implementation
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException();
}
byte IConvertible.ToByte(IFormatProvider provider)
{
throw new InvalidCastException();
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException();
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException();
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
throw new InvalidCastException();
}
double IConvertible.ToDouble(IFormatProvider provider)
{
throw new InvalidCastException();
}
short IConvertible.ToInt16(IFormatProvider provider)
{
throw new InvalidCastException();
}
int IConvertible.ToInt32(IFormatProvider provider)
{
throw new InvalidCastException();
}
long IConvertible.ToInt64(IFormatProvider provider)
{
throw new InvalidCastException();
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
throw new InvalidCastException();
}
float IConvertible.ToSingle(IFormatProvider provider)
{
throw new InvalidCastException();
}
string IConvertible.ToString(IFormatProvider provider)
{
return ToString();
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
switch (Type.GetTypeCode(conversionType))
{
case TypeCode.String:
return ((IConvertible)this).ToString(provider);
case TypeCode.Object:
if (conversionType == typeof(object) || conversionType == typeof(ObjectId))
{
return this;
}
if (conversionType == typeof(BsonObjectId))
{
return new BsonObjectId(this);
}
if (conversionType == typeof(BsonString))
{
return new BsonString(((IConvertible)this).ToString(provider));
}
break;
}
throw new InvalidCastException();
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
throw new InvalidCastException();
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
throw new InvalidCastException();
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
throw new InvalidCastException();
}
}
}