5 // Duco Fijma (duco@lorentz.xs4all.nl)
10 using System.Globalization;
11 using System.Security.Cryptography;
16 public struct Guid : IFormattable, IComparable {
18 private uint _timeLow;
19 private ushort _timeMid;
20 private ushort _timeHighAndVersion;
21 private byte _clockSeqHiAndReserved;
22 private byte _clockSeqLow;
30 internal class GuidState {
31 protected Random _prnd; // Pseudo RNG
32 protected RandomNumberGenerator _rnd; // Strong RNG
33 protected bool _usePRnd; // 'true' for pseudo RNG
34 protected ushort _clockSeq;
35 protected ulong _lastTimestamp;
36 protected byte[] _mac;
38 public int NextInt(uint x)
41 return _prnd.Next ((int) x);
44 byte[] b = new byte[4];
47 uint res = BitConverter.ToUInt32 (b, 0);
53 public void NextBytes(byte[] b)
56 _prnd . NextBytes (b);
63 [MonoTODO("Get real MAC address")]
64 public GuidState (bool usePRnd)
68 _prnd = new Random (unchecked((int) DateTime.Now.Ticks));
71 _rnd = RandomNumberGenerator.Create ();
73 _clockSeq = (ushort) NextInt (0x4000); // 14 bits
80 public ulong NewTimestamp ()
85 timestamp = (ulong) (DateTime.UtcNow - new DateTime (1582, 10, 15, 0, 0, 0)).Ticks;
86 if (timestamp < _lastTimestamp) {
87 // clock moved backwards!
89 _clockSeq = (ushort) (_clockSeq & 0x3fff);
92 if (timestamp > _lastTimestamp) {
93 _lastTimestamp = timestamp;
100 public ushort ClockSeq {
115 internal class GuidParser {
121 public GuidParser (string src)
127 private void Reset ()
130 _length = _src.Length;
133 private bool AtEnd ()
135 return _cur >= _length;
138 private void ThrowFormatException ()
140 throw new FormatException (Locale.GetText ("Invalid format for Guid.Guid(string)"));
143 private ulong ParseHex(int length, bool strictLength)
149 for (i=0; (!end) && i<length; ++i) {
151 if (strictLength || i==0) {
152 ThrowFormatException ();
159 char c = Char.ToLower (_src[_cur]);
160 if (Char.IsDigit (c)) {
161 res = res * 16 + c - '0';
164 else if (c >= 'a' && c <= 'f') {
165 res = res * 16 + c - 'a' + 10;
169 if (strictLength || i==0) {
170 ThrowFormatException ();
182 private bool ParseOptChar (char c)
184 if (!AtEnd() && _src[_cur] == c) {
193 private void ParseChar (char c)
195 bool b = ParseOptChar (c);
197 ThrowFormatException ();
201 private Guid ParseGuid1 ()
207 byte[] d = new byte[8];
210 openBrace = ParseOptChar ('{');
211 a = (int) ParseHex(8, true);
213 b = (short) ParseHex(4, true);
215 c = (short) ParseHex(4, true);
217 for (i=0; i<8; ++i) {
218 d[i] = (byte) ParseHex(2, true);
224 if (openBrace && !ParseOptChar('}')) {
225 ThrowFormatException ();
228 return new Guid(a, b, c, d);
231 private void ParseHexPrefix ()
237 private Guid ParseGuid2 ()
242 byte[] d = new byte [8];
247 a = (int) ParseHex (8, false);
250 b = (short) ParseHex (4, false);
253 c = (short) ParseHex (4, false);
256 for (i=0; i<8; ++i) {
258 d[i] = (byte) ParseHex (2, false);
267 return new Guid (a,b,c,d);
278 catch (FormatException) {
283 ThrowFormatException ();
290 private static GuidState _guidState = new GuidState ( true /* use pseudo RNG? */ );
292 private static void CheckNull (object o)
295 throw new ArgumentNullException (Locale.GetText ("Value cannot be null."));
299 private static void CheckLength (byte[] o, int l)
301 if (o . Length != l) {
302 throw new ArgumentException (String.Format (Locale.GetText ("Array should be exactly {0} bytes long."), l));
306 private static void CheckArray (byte[] o, int l)
312 public Guid (byte[] b)
315 _timeLow = System.BitConverter.ToUInt32 (b, 0);
316 _timeMid = System.BitConverter.ToUInt16 (b, 4);
317 _timeHighAndVersion = System.BitConverter.ToUInt16 (b, 6);
318 _clockSeqHiAndReserved = b[8];
328 public Guid (string g)
332 GuidParser p = new GuidParser (g);
333 Guid guid = p.Parse();
338 public Guid (int a, short b, short c, byte[] d)
342 _timeMid = (ushort) b;
343 _timeHighAndVersion = (ushort) c;
344 _clockSeqHiAndReserved = d[0];
366 : this((uint) a, (ushort) b, (ushort) c, d, e, f, g, h, i, j, k) {}
368 [CLSCompliant(false)]
384 _timeHighAndVersion = c;
385 _clockSeqHiAndReserved = d;
395 public static readonly Guid Empty = new Guid(0,0,0,0,0,0,0,0,0,0,0);
397 private static int Compare (uint x, uint y)
407 public int CompareTo (object value )
412 if (!(value is Guid)) {
413 throw new ArgumentException (Locale.GetText (
414 "Argument of System.Guid.CompareTo should be a Guid"));
417 Guid v = (Guid) value;
419 if (_timeLow != v._timeLow ) {
420 return Compare(_timeLow, v._timeLow);
422 else if (_timeMid != v._timeMid) {
423 return Compare(_timeMid, v._timeMid);
425 else if (_timeHighAndVersion != v._timeHighAndVersion) {
426 return Compare(_timeHighAndVersion, v._timeHighAndVersion);
428 else if (_clockSeqHiAndReserved != v._clockSeqHiAndReserved) {
429 return Compare(_clockSeqHiAndReserved, v._clockSeqHiAndReserved);
431 else if (_clockSeqLow != v._clockSeqLow) {
432 return Compare(_clockSeqLow, v._clockSeqLow);
434 else if (_node0 != v._node0) {
435 return Compare(_node0, v._node0);
437 else if (_node1 != v._node1) {
438 return Compare(_node1, v._node1);
440 else if (_node2 != v._node2) {
441 return Compare(_node2, v._node2);
443 else if (_node3 != v._node3) {
444 return Compare(_node3, v._node3);
446 else if (_node4 != v._node4) {
447 return Compare(_node4, v._node4);
449 else if (_node5 != v._node5) {
450 return Compare(_node5, v._node5);
456 public override bool Equals ( object o )
459 return CompareTo (o) == 0;
461 catch ( ArgumentException ) {
466 public override int GetHashCode ()
470 res = (int) _timeLow;
471 res = res ^ ((int) _timeMid << 16 | _timeHighAndVersion);
472 res = res ^ ((int) _clockSeqHiAndReserved << 24);
473 res = res ^ ((int) _clockSeqLow << 16);
474 res = res ^ ((int) _node0 << 8);
475 res = res ^ ((int) _node1);
476 res = res ^ ((int) _node2 << 24);
477 res = res ^ ((int) _node3 << 16);
478 res = res ^ ((int) _node4 << 8);
479 res = res ^ ((int) _node5);
484 private static Guid NewTimeGuid()
486 ulong timestamp = _guidState.NewTimestamp ();
488 // Bit [31..0] (32 bits) for timeLow
489 uint timeLow = (uint) (timestamp & 0x00000000fffffffful);
490 // Bit [47..32] (16 bits) for timeMid
491 ushort timeMid = (ushort) ((timestamp & 0x0000ffff00000000ul) >> 32);
492 // Bit [59..48] (12 bits) for timeHi
493 ushort timeHi = (ushort) ((timestamp & 0x0fff000000000000ul) >> 48);
494 // Bit [7..0] (8 bits) for clockSeqLo
495 byte clockSeqLow = (byte) (Guid._guidState.ClockSeq & 0x00ffu);
496 // Bit [13..8] (6 bits) for clockSeqHi
497 byte clockSeqHi = (byte) ((Guid._guidState.ClockSeq & 0x3f00u) >> 8);
498 byte[] mac = _guidState.MAC;
500 clockSeqHi = (byte) (clockSeqHi | 0x80u); // Bit[7] = 1, Bit[6] = 0 (Variant)
501 timeHi = (ushort) (timeHi | 0x1000u); // Bit[15..13] = 1 (Guid is time-based)
503 return new Guid(timeLow, timeMid, timeHi, clockSeqHi, clockSeqLow, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
506 private static Guid NewRandomGuid ()
508 byte[] b = new byte[16];
510 _guidState.NextBytes (b);
512 Guid res = new Guid(b);
513 // Mask in Variant 1-0 in Bit[7..6]
514 res._clockSeqHiAndReserved = (byte) ((res._clockSeqHiAndReserved & 0x3fu) | 0x80u);
515 // Mask in Version 4 (random based Guid) in Bits[15..13]
516 res._timeHighAndVersion = (ushort) ((res._timeHighAndVersion & 0x0fffu) | 0x4000u);
521 public static Guid NewGuid ()
523 return NewRandomGuid();
526 public byte[] ToByteArray ()
528 byte[] res = new byte[16];
533 tmp = BitConverter.GetBytes(_timeLow);
534 for (s=0; s<4; ++s) {
538 tmp = BitConverter.GetBytes(_timeMid);
539 for (s=0; s<2; ++s) {
543 tmp = BitConverter.GetBytes(_timeHighAndVersion);
544 for (s=0; s<2; ++s) {
548 res[8] = _clockSeqHiAndReserved;
549 res[9] = _clockSeqLow;
560 private string BaseToString(bool h, bool p, bool b)
571 res += _timeLow.ToString ("x8");
575 res += _timeMid.ToString ("x4");
579 res += _timeHighAndVersion.ToString ("x4");
583 res += _clockSeqHiAndReserved.ToString ("x2");
584 res += _clockSeqLow.ToString ("x2");
588 res += _node0.ToString ("x2");
589 res += _node1.ToString ("x2");
590 res += _node2.ToString ("x2");
591 res += _node3.ToString ("x2");
592 res += _node4.ToString ("x2");
593 res += _node5.ToString ("x2");
605 public override string ToString ()
607 return BaseToString (true, false, false);
610 public string ToString (string format)
617 if (format != null) {
618 f = format.ToLower();
629 else if (f != "d" && f != "") {
630 throw new FormatException ( Locale.GetText ("Argument to Guid.ToString(string format) should be \"b\", \"B\", \"d\", \"D\", \"n\", \"N\", \"p\" or \"P\""));
634 return BaseToString (h, p, b);
637 public string ToString (string format, IFormatProvider provider)
639 return ToString (format);
642 public static bool operator == (Guid a, Guid b)
647 public static bool operator != (Guid a, Guid b)
649 return !( a.Equals (b) );