5 // Duco Fijma (duco@lorentz.xs4all.nl)
10 using System.Globalization;
11 using System.Security.Cryptography;
17 public struct Guid : IFormattable, IComparable {
19 private uint _timeLow;
20 private ushort _timeMid;
21 private ushort _timeHighAndVersion;
22 private byte _clockSeqHiAndReserved;
23 private byte _clockSeqLow;
31 internal class GuidState {
32 protected Random _prnd; // Pseudo RNG
33 protected RandomNumberGenerator _rnd; // Strong RNG
34 protected bool _usePRnd; // 'true' for pseudo RNG
35 protected ushort _clockSeq;
36 protected ulong _lastTimestamp;
37 protected byte[] _mac;
39 public int NextInt(uint x)
42 return _prnd.Next ((int) x);
45 byte[] b = new byte[4];
48 uint res = BitConverter.ToUInt32 (b, 0);
54 public void NextBytes(byte[] b)
57 _prnd . NextBytes (b);
64 [MonoTODO("Get real MAC address")]
65 public GuidState (bool usePRnd)
69 _prnd = new Random (unchecked((int) DateTime.Now.Ticks));
72 _rnd = RandomNumberGenerator.Create ();
74 _clockSeq = (ushort) NextInt (0x4000); // 14 bits
81 public ulong NewTimestamp ()
86 timestamp = (ulong) (DateTime.UtcNow - new DateTime (1582, 10, 15, 0, 0, 0)).Ticks;
87 if (timestamp < _lastTimestamp) {
88 // clock moved backwards!
90 _clockSeq = (ushort) (_clockSeq & 0x3fff);
93 if (timestamp > _lastTimestamp) {
94 _lastTimestamp = timestamp;
101 public ushort ClockSeq {
116 internal class GuidParser {
122 public GuidParser (string src)
128 private void Reset ()
131 _length = _src.Length;
134 private bool AtEnd ()
136 return _cur >= _length;
139 private void ThrowFormatException ()
141 throw new FormatException (Locale.GetText ("Invalid format for Guid.Guid(string)"));
144 private ulong ParseHex(int length, bool strictLength)
150 for (i=0; (!end) && i<length; ++i) {
152 if (strictLength || i==0) {
153 ThrowFormatException ();
160 char c = Char.ToLower (_src[_cur]);
161 if (Char.IsDigit (c)) {
162 res = res * 16 + c - '0';
165 else if (c >= 'a' && c <= 'f') {
166 res = res * 16 + c - 'a' + 10;
170 if (strictLength || i==0) {
171 ThrowFormatException ();
183 private bool ParseOptChar (char c)
185 if (!AtEnd() && _src[_cur] == c) {
194 private void ParseChar (char c)
196 bool b = ParseOptChar (c);
198 ThrowFormatException ();
202 private Guid ParseGuid1 ()
208 byte[] d = new byte[8];
211 openBrace = ParseOptChar ('{');
212 a = (int) ParseHex(8, true);
214 b = (short) ParseHex(4, true);
216 c = (short) ParseHex(4, true);
218 for (i=0; i<8; ++i) {
219 d[i] = (byte) ParseHex(2, true);
225 if (openBrace && !ParseOptChar('}')) {
226 ThrowFormatException ();
229 return new Guid(a, b, c, d);
232 private void ParseHexPrefix ()
238 private Guid ParseGuid2 ()
243 byte[] d = new byte [8];
248 a = (int) ParseHex (8, false);
251 b = (short) ParseHex (4, false);
254 c = (short) ParseHex (4, false);
257 for (i=0; i<8; ++i) {
259 d[i] = (byte) ParseHex (2, false);
268 return new Guid (a,b,c,d);
279 catch (FormatException) {
284 ThrowFormatException ();
291 private static GuidState _guidState = new GuidState ( true /* use pseudo RNG? */ );
293 private static void CheckNull (object o)
296 throw new ArgumentNullException (Locale.GetText ("Value cannot be null."));
300 private static void CheckLength (byte[] o, int l)
302 if (o . Length != l) {
303 throw new ArgumentException (String.Format (Locale.GetText ("Array should be exactly {0} bytes long."), l));
307 private static void CheckArray (byte[] o, int l)
313 public Guid (byte[] b)
316 _timeLow = System.BitConverter.ToUInt32 (b, 0);
317 _timeMid = System.BitConverter.ToUInt16 (b, 4);
318 _timeHighAndVersion = System.BitConverter.ToUInt16 (b, 6);
319 _clockSeqHiAndReserved = b[8];
329 public Guid (string g)
333 GuidParser p = new GuidParser (g);
334 Guid guid = p.Parse();
339 public Guid (int a, short b, short c, byte[] d)
343 _timeMid = (ushort) b;
344 _timeHighAndVersion = (ushort) c;
345 _clockSeqHiAndReserved = d[0];
367 : this((uint) a, (ushort) b, (ushort) c, d, e, f, g, h, i, j, k) {}
369 [CLSCompliant(false)]
385 _timeHighAndVersion = c;
386 _clockSeqHiAndReserved = d;
396 public static readonly Guid Empty = new Guid(0,0,0,0,0,0,0,0,0,0,0);
398 private static int Compare (uint x, uint y)
408 public int CompareTo (object value )
413 if (!(value is Guid)) {
414 throw new ArgumentException (Locale.GetText (
415 "Argument of System.Guid.CompareTo should be a Guid"));
418 Guid v = (Guid) value;
420 if (_timeLow != v._timeLow ) {
421 return Compare(_timeLow, v._timeLow);
423 else if (_timeMid != v._timeMid) {
424 return Compare(_timeMid, v._timeMid);
426 else if (_timeHighAndVersion != v._timeHighAndVersion) {
427 return Compare(_timeHighAndVersion, v._timeHighAndVersion);
429 else if (_clockSeqHiAndReserved != v._clockSeqHiAndReserved) {
430 return Compare(_clockSeqHiAndReserved, v._clockSeqHiAndReserved);
432 else if (_clockSeqLow != v._clockSeqLow) {
433 return Compare(_clockSeqLow, v._clockSeqLow);
435 else if (_node0 != v._node0) {
436 return Compare(_node0, v._node0);
438 else if (_node1 != v._node1) {
439 return Compare(_node1, v._node1);
441 else if (_node2 != v._node2) {
442 return Compare(_node2, v._node2);
444 else if (_node3 != v._node3) {
445 return Compare(_node3, v._node3);
447 else if (_node4 != v._node4) {
448 return Compare(_node4, v._node4);
450 else if (_node5 != v._node5) {
451 return Compare(_node5, v._node5);
457 public override bool Equals ( object o )
460 return CompareTo (o) == 0;
462 catch ( ArgumentException ) {
467 public override int GetHashCode ()
471 res = (int) _timeLow;
472 res = res ^ ((int) _timeMid << 16 | _timeHighAndVersion);
473 res = res ^ ((int) _clockSeqHiAndReserved << 24);
474 res = res ^ ((int) _clockSeqLow << 16);
475 res = res ^ ((int) _node0 << 8);
476 res = res ^ ((int) _node1);
477 res = res ^ ((int) _node2 << 24);
478 res = res ^ ((int) _node3 << 16);
479 res = res ^ ((int) _node4 << 8);
480 res = res ^ ((int) _node5);
485 private static Guid NewTimeGuid()
487 ulong timestamp = _guidState.NewTimestamp ();
489 // Bit [31..0] (32 bits) for timeLow
490 uint timeLow = (uint) (timestamp & 0x00000000fffffffful);
491 // Bit [47..32] (16 bits) for timeMid
492 ushort timeMid = (ushort) ((timestamp & 0x0000ffff00000000ul) >> 32);
493 // Bit [59..48] (12 bits) for timeHi
494 ushort timeHi = (ushort) ((timestamp & 0x0fff000000000000ul) >> 48);
495 // Bit [7..0] (8 bits) for clockSeqLo
496 byte clockSeqLow = (byte) (Guid._guidState.ClockSeq & 0x00ffu);
497 // Bit [13..8] (6 bits) for clockSeqHi
498 byte clockSeqHi = (byte) ((Guid._guidState.ClockSeq & 0x3f00u) >> 8);
499 byte[] mac = _guidState.MAC;
501 clockSeqHi = (byte) (clockSeqHi | 0x80u); // Bit[7] = 1, Bit[6] = 0 (Variant)
502 timeHi = (ushort) (timeHi | 0x1000u); // Bit[15..13] = 1 (Guid is time-based)
504 return new Guid(timeLow, timeMid, timeHi, clockSeqHi, clockSeqLow, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
507 private static Guid NewRandomGuid ()
509 byte[] b = new byte[16];
511 _guidState.NextBytes (b);
513 Guid res = new Guid(b);
514 // Mask in Variant 1-0 in Bit[7..6]
515 res._clockSeqHiAndReserved = (byte) ((res._clockSeqHiAndReserved & 0x3fu) | 0x80u);
516 // Mask in Version 4 (random based Guid) in Bits[15..13]
517 res._timeHighAndVersion = (ushort) ((res._timeHighAndVersion & 0x0fffu) | 0x4000u);
521 private static char ToHex(int b)
523 return (char)((b<0xA)?('0' + b):('a' + b - 0xA));
527 public static Guid NewGuid ()
529 return NewRandomGuid();
532 public byte[] ToByteArray ()
534 byte[] res = new byte[16];
539 tmp = BitConverter.GetBytes(_timeLow);
540 for (s=0; s<4; ++s) {
544 tmp = BitConverter.GetBytes(_timeMid);
545 for (s=0; s<2; ++s) {
549 tmp = BitConverter.GetBytes(_timeHighAndVersion);
550 for (s=0; s<2; ++s) {
554 res[8] = _clockSeqHiAndReserved;
555 res[9] = _clockSeqLow;
566 private string BaseToString(bool h, bool p, bool b)
568 StringBuilder res = new StringBuilder (40);
576 res.Append (_timeLow.ToString ("x8"));
580 res.Append (_timeMid.ToString ("x4"));
584 res.Append (_timeHighAndVersion.ToString ("x4"));
590 ToHex((_clockSeqHiAndReserved >> 4) & 0xf),
591 ToHex(_clockSeqHiAndReserved & 0xf),
592 ToHex((_clockSeqLow >> 4) & 0xf),
593 ToHex(_clockSeqLow & 0xf)
603 ToHex((_node0 >> 4) & 0xf),
605 ToHex((_node1 >> 4) & 0xf),
607 ToHex((_node2 >> 4) & 0xf),
609 ToHex((_node3 >> 4) & 0xf),
611 ToHex((_node4 >> 4) & 0xf),
613 ToHex((_node5 >> 4) & 0xf),
625 return res.ToString ();
628 public override string ToString ()
630 return BaseToString (true, false, false);
633 public string ToString (string format)
640 if (format != null) {
641 f = format.ToLower();
652 else if (f != "d" && f != "") {
653 throw new FormatException ( Locale.GetText ("Argument to Guid.ToString(string format) should be \"b\", \"B\", \"d\", \"D\", \"n\", \"N\", \"p\" or \"P\""));
657 return BaseToString (h, p, b);
660 public string ToString (string format, IFormatProvider provider)
662 return ToString (format);
665 public static bool operator == (Guid a, Guid b)
670 public static bool operator != (Guid a, Guid b)
672 return !( a.Equals (b) );