Wed Sep 11 15:26:34 CEST 2002 Paolo Molaro <lupus@ximian.com>
[mono.git] / mcs / class / corlib / System / Guid.cs
index b64734aa8f07c18a5456d8f747b272de9fc9831a..5f15c707ce09414fc1da3e31076c3660fd4ad007 100755 (executable)
@@ -8,9 +8,11 @@
 //
 
 using System.Globalization;
+using System.Security.Cryptography;
 
 namespace System {
 
+[Serializable]
 public struct Guid  : IFormattable, IComparable  {
 
        private uint _timeLow;
@@ -25,33 +27,62 @@ public struct Guid  : IFormattable, IComparable  {
        private byte _node4;
        private byte _node5;
 
-       private class GuidState {
-               protected Random _rnd;
+       internal class GuidState {
+               protected Random _prnd; // Pseudo RNG
+               protected RandomNumberGenerator _rnd; // Strong RNG
+               protected bool _usePRnd; // 'true' for pseudo RNG
                protected ushort _clockSeq;
                protected ulong _lastTimestamp;
                protected byte[] _mac;
+
+               public int NextInt(uint x)
+                {
+                       if (_usePRnd) {
+                               return _prnd.Next ((int) x);
+                       }
+                       else {
+                               byte[] b = new byte[4];
+                               _rnd.GetBytes (b);
+
+                               uint res = BitConverter.ToUInt32 (b, 0);
+                               res = (res % x);
+                               return (int) res;
+                       }
+               }
+
+               public void NextBytes(byte[] b)
+               {
+                       if ( _usePRnd ) {
+                               _prnd . NextBytes (b);
+                       }
+                       else {
+                               _rnd . GetBytes (b);
+                       }
+               }
        
                [MonoTODO("Get real MAC address")]
-               public GuidState () {
-                       _rnd = new Random(unchecked((int) DateTime.Now.Ticks));
-                       _clockSeq = (ushort) _rnd.Next(0x4000); // 14 bits
+               public GuidState (bool usePRnd)
+               {
+                       _usePRnd = usePRnd;
+                       if ( _usePRnd ) {
+                               _prnd = new Random (unchecked((int) DateTime.Now.Ticks));
+                       }
+                       else {
+                               _rnd = RandomNumberGenerator.Create ();
+                       }
+                       _clockSeq = (ushort) NextInt (0x4000); // 14 bits
                        _lastTimestamp = 0ul;
                        _mac = new byte[6];
-                       _rnd.NextBytes (_mac);
+                       NextBytes (_mac);
                        _mac[0] |= 0x80;
                }
 
-               public Random Rnd {
-                       get {
-                               return _rnd;
-                       }
-               }
-
-               public ulong NewTimestamp () {
+               public ulong NewTimestamp ()
+               {
                        ulong timestamp;
 
                        do {
-                               timestamp = (ulong) (DateTime.UtcNow - new DateTime(1582, 10, 15, 0, 0, 0)).Ticks;
+                               timestamp = (ulong) (DateTime.UtcNow - new DateTime (1582, 10, 15, 0, 0, 0)).Ticks;
                                if (timestamp < _lastTimestamp) {
                                        // clock moved backwards!
                                        _clockSeq++;
@@ -81,26 +112,205 @@ public struct Guid  : IFormattable, IComparable  {
                
        };
 
-       private static GuidState _guidState = new GuidState ();
+       internal class GuidParser {
+
+               private string _src;
+               private int _length;
+               private int _cur;
+       
+               public GuidParser (string src)
+               {
+                       _src = src;
+                       Reset ();
+               }
+               
+               private void Reset ()
+               {
+                       _cur = 0;
+                       _length = _src.Length;
+               }
+       
+               private bool AtEnd ()
+               {
+                       return _cur >= _length;
+               }
+       
+               private void ThrowFormatException ()
+               {
+                       throw new FormatException (Locale.GetText ("Invalid format for Guid.Guid(string)"));
+               }
+       
+               private ulong ParseHex(int length, bool strictLength)
+               {
+                       ulong res = 0;
+                       int i;
+                       bool end = false;
+               
+                       for (i=0; (!end) && i<length; ++i) {
+                               if (AtEnd ()) {
+                                       if (strictLength || i==0) {
+                                               ThrowFormatException ();
+                                       }
+                                       else {
+                                               end = true;
+                                       }
+                               }
+                               else {
+                                       char c = Char.ToLower (_src[_cur]);
+                                       if (Char.IsDigit (c)) {
+                                               res = res * 16 + c - '0';
+                                               _cur++;
+                                       }
+                                       else if (c >= 'a' && c <= 'f') {
+                                               res = res * 16 + c - 'a' + 10;
+                                               _cur++;
+                                       }
+                                       else {
+                                               if (strictLength || i==0) {
+                                                       ThrowFormatException ();
+                                               }
+                                               else {
+                                                       end = true;
+                                               }
+                                       }
+                               }
+                       }
+                       
+                       return res;
+               }
+       
+               private bool ParseOptChar (char c)
+               {
+                       if (!AtEnd() && _src[_cur] == c) {
+                               _cur++;
+                               return true;
+                       }
+                       else {
+                               return false;
+                       }
+               }
+       
+               private void ParseChar (char c)
+               {
+                       bool b = ParseOptChar (c);
+                       if (!b) {
+                               ThrowFormatException ();
+                       }
+               }
+       
+               private Guid ParseGuid1 ()
+               {
+                       bool openBrace; 
+                       int a;
+                       short b;
+                       short c;
+                       byte[] d = new byte[8];
+                       int i;
+       
+                       openBrace = ParseOptChar ('{');
+                       a = (int) ParseHex(8, true);
+                       ParseChar('-');
+                       b = (short) ParseHex(4, true);
+                       ParseChar('-');
+                       c = (short) ParseHex(4, true);
+                       ParseChar('-');
+                       for (i=0; i<8; ++i) {
+                               d[i] = (byte) ParseHex(2, true);
+                               if (i == 1) {
+                                       ParseChar('-');
+                               }       
+                       }
+
+                       if (openBrace && !ParseOptChar('}')) {
+                               ThrowFormatException ();
+                       }
+       
+                       return new Guid(a, b, c, d);
+               }
+       
+               private void ParseHexPrefix ()
+               {
+                       ParseChar ('0');
+                       ParseChar ('x');
+               }
+       
+               private Guid ParseGuid2 ()
+               {
+                       int a;
+                       short b;
+                       short c;
+                       byte[] d = new byte [8];
+                       int i;
+       
+                       ParseChar ('{');
+                       ParseHexPrefix ();
+                       a = (int) ParseHex (8, false);
+                       ParseChar (',');
+                       ParseHexPrefix ();
+                       b = (short) ParseHex (4, false);
+                       ParseChar (',');
+                       ParseHexPrefix ();
+                       c = (short) ParseHex (4, false);
+                       ParseChar (',');
+                       ParseChar ('{');
+                       for (i=0; i<8; ++i) {
+                               ParseHexPrefix ();
+                               d[i] = (byte) ParseHex (2, false);
+                               if (i != 7) {
+                                       ParseChar (',');
+                               }
+
+                       }       
+                       ParseChar ('}');
+                       ParseChar ('}');
+       
+                       return new Guid (a,b,c,d);                      
+                       
+               }
+       
+               public Guid Parse ()
+               {
+                       Guid g;
+       
+                       try {
+                               g  = ParseGuid1 ();
+                       }
+                       catch (FormatException) {
+                               Reset ();
+                               g = ParseGuid2 (); 
+                       }
+                       if (!AtEnd () ) {
+                               ThrowFormatException ();
+                       }
+                       return g;
+               }
+
+       }
+
+       private static GuidState _guidState = new GuidState ( true /* use pseudo RNG? */ ); 
 
-       private static void CheckNull (object o) {
+       private static void CheckNull (object o)
+       {
                if (o == null) {
                        throw new ArgumentNullException (Locale.GetText ("Value cannot be null."));
                }
        }
 
-       private static void CheckLength (byte[] o, int l) {
+       private static void CheckLength (byte[] o, int l)
+       {
                if (o . Length != l) {
-                       throw new ArgumentException (String.Format(Locale.GetText ("Array should be exactly {0} bytes long."), l));
+                       throw new ArgumentException (String.Format (Locale.GetText ("Array should be exactly {0} bytes long."), l));
                }
        }
 
-       private static void CheckArray (byte[] o, int l) {
+       private static void CheckArray (byte[] o, int l)
+       {
                CheckNull (o);
                CheckLength (o, l);
        }
 
-       public Guid (byte[] b) {
+       public Guid (byte[] b)
+       {
                CheckArray (b, 16);
                _timeLow = System.BitConverter.ToUInt32 (b, 0);
                _timeMid = System.BitConverter.ToUInt16 (b, 4);
@@ -115,6 +325,16 @@ public struct Guid  : IFormattable, IComparable  {
                _node5 = b[15];
        }
 
+       public Guid (string g)
+       {
+               CheckNull (g);
+
+               GuidParser p = new GuidParser (g);
+               Guid guid = p.Parse();
+
+               this = guid;
+       }
+
        public Guid (int a, short b, short c, byte[] d) 
        {
                CheckArray(d, 8);
@@ -184,7 +404,8 @@ public struct Guid  : IFormattable, IComparable  {
                }
        }
 
-       public int CompareTo (object value ) {
+       public int CompareTo (object value )
+       {
                if (value == null )
                        return 1;
 
@@ -232,16 +453,18 @@ public struct Guid  : IFormattable, IComparable  {
                return 0;
        }
 
-       public override bool Equals ( object o ) {
+       public override bool Equals ( object o )
+       {
                try {
-                       return CompareTo(o) == 0;       
+                       return CompareTo (o) == 0;      
                }
                catch ( ArgumentException ) {
                        return false;
                }
        }
 
-       public override int GetHashCode () {
+       public override int GetHashCode ()
+       {
                int res;
 
                res = (int) _timeLow; 
@@ -258,7 +481,8 @@ public struct Guid  : IFormattable, IComparable  {
                return res;
        }
 
-       private static Guid NewTimeGuid() {
+       private static Guid NewTimeGuid()
+       {
                ulong timestamp = _guidState.NewTimestamp ();
 
                // Bit [31..0] (32 bits) for timeLow
@@ -279,9 +503,11 @@ public struct Guid  : IFormattable, IComparable  {
                return new Guid(timeLow, timeMid, timeHi, clockSeqHi, clockSeqLow, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        }
 
-       private static Guid NewRandomGuid () {
+       private static Guid NewRandomGuid ()
+       {
                byte[] b = new byte[16];
-               _guidState.Rnd.NextBytes(b);
+
+               _guidState.NextBytes (b);
 
                Guid res = new Guid(b);
                // Mask in Variant 1-0 in Bit[7..6]
@@ -292,11 +518,13 @@ public struct Guid  : IFormattable, IComparable  {
        }
 
        [MonoTODO]
-       public static Guid NewGuid () {
-               return NewTimeGuid();
+       public static Guid NewGuid ()
+       {
+               return NewRandomGuid();
        }
 
-       public byte[] ToByteArray () {
+       public byte[] ToByteArray ()
+       {
                byte[] res = new byte[16];
                byte[] tmp;
                int d = 0;
@@ -329,7 +557,8 @@ public struct Guid  : IFormattable, IComparable  {
                return res;
        }
 
-       private string BaseToString(bool h, bool p, bool b) {
+       private string BaseToString(bool h, bool p, bool b)
+       {
                string res = "";
                
                if (p) {
@@ -339,29 +568,29 @@ public struct Guid  : IFormattable, IComparable  {
                        res += "{";
                }
        
-               res += _timeLow.ToString("x8");
+               res += _timeLow.ToString ("x8");
                if (h) {
                        res += "-";
                }
-               res += _timeMid.ToString("x4");
+               res += _timeMid.ToString ("x4");
                if (h) {
                        res += "-";
                }
-               res += _timeHighAndVersion.ToString("x4");
+               res += _timeHighAndVersion.ToString ("x4");
                if (h) {
                        res += "-";
                }
-               res += _clockSeqHiAndReserved.ToString("x2");
-               res += _clockSeqLow.ToString("x2");
+               res += _clockSeqHiAndReserved.ToString ("x2");
+               res += _clockSeqLow.ToString ("x2");
                if (h) {
                        res += "-";
                }
-               res += _node0.ToString("x2");
-               res += _node1.ToString("x2");
-               res += _node2.ToString("x2");
-               res += _node3.ToString("x2");
-               res += _node4.ToString("x2");
-               res += _node5.ToString("x2");
+               res += _node0.ToString ("x2");
+               res += _node1.ToString ("x2");
+               res += _node2.ToString ("x2");
+               res += _node3.ToString ("x2");
+               res += _node4.ToString ("x2");
+               res += _node5.ToString ("x2");
 
                if (p) {
                        res += ")";
@@ -373,13 +602,15 @@ public struct Guid  : IFormattable, IComparable  {
                return res;
        }
 
-       public override string ToString () {
+       public override string ToString ()
+       {
                return BaseToString (true, false, false);
        }
 
-       public string ToString (string format) {
+       public string ToString (string format)
+       {
                string f;
-               bool h = false;
+               bool h = true;
                bool p = false;
                bool b = false;
 
@@ -387,17 +618,15 @@ public struct Guid  : IFormattable, IComparable  {
                        f = format.ToLower();
 
                        if (f == "b") {
-                               h = true;
                                b = true;
                        }
                        else if (f == "p") {
-                               h = true;
                                p = true;
                        }
-                       else if (f == "d") {
-                               h = true;
+                       else if (f == "n") {
+                               h = false;
                        }
-                       else if (f != "n" && f != "") {
+                       else if (f != "d" && f != "") {
                                throw new FormatException ( Locale.GetText ("Argument to Guid.ToString(string format) should be \"b\", \"B\", \"d\", \"D\", \"n\", \"N\", \"p\" or \"P\""));
                        }
                }
@@ -405,15 +634,18 @@ public struct Guid  : IFormattable, IComparable  {
                return BaseToString (h, p, b);
        }
 
-       public string ToString (string format, IFormatProvider provider) {
+       public string ToString (string format, IFormatProvider provider)
+       {
                return ToString (format);
        }
 
-       public static bool operator == (Guid a, Guid b) {
+       public static bool operator == (Guid a, Guid b)
+       {
                return a.Equals(b);
        }
 
-       public static bool operator != (Guid a, Guid b) {
+       public static bool operator != (Guid a, Guid b)
+       {
                return !( a.Equals (b) );
        }