Author: alanmc
Date: 2007-05-23 19:43:32 -0400 (Wed, 23 May 2007)
New Revision: 77878

Removed:
   trunk/bitsharp/src/MonoTorrent/BEncoding/BEncode.cs
Modified:
   trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedDictionary.cs
   trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedList.cs
   trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedNumber.cs
   trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedString.cs
   trunk/bitsharp/src/MonoTorrent/BEncoding/IBEncodedValue.cs
   trunk/bitsharp/src/MonoTorrent/Client/ClientEngine.cs
   trunk/bitsharp/src/MonoTorrent/Client/Managers/TrackerManager.cs
   
trunk/bitsharp/src/MonoTorrent/Client/PeerMessages/ExtendedMessages/ExtendedListMessage.cs
   trunk/bitsharp/src/MonoTorrent/Common/Torrent.cs
   trunk/bitsharp/src/MonoTorrent/Common/TorrentCreator.cs
   trunk/bitsharp/src/MonoTorrent/Tracker/ITorrentManager.cs
   trunk/bitsharp/src/MonoTorrent/Tracker/SimpleTorrentManager.cs
Log:
Rejigged BEncoding. Less code, and it is more OO now.

Deleted: trunk/bitsharp/src/MonoTorrent/BEncoding/BEncode.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/BEncoding/BEncode.cs 2007-05-23 23:07:49 UTC 
(rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/BEncoding/BEncode.cs 2007-05-23 23:43:32 UTC 
(rev 77878)
@@ -1,142 +0,0 @@
-//
-// BEncode.cs
-//
-// Authors:
-//   Alan McGovern [EMAIL PROTECTED]
-//   Gregor Burger [EMAIL PROTECTED]
-//
-// Copyright (C) 2006 Alan McGovern
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.IO;
-using System.Diagnostics;
-
-namespace MonoTorrent.BEncoding
-{
-    /// <summary>
-    /// Class for decoding any BEncoded material
-    /// </summary>
-    public static class BEncode
-    {
-        /// <summary>
-        /// Interface for all BEncoded values
-        /// </summary>
-        /// <param name="data">The byte array containing the BEncoded 
data</param>
-        /// <returns></returns>
-        public static IBEncodedValue Decode(byte[] data)
-        {
-            if (data == null)
-                throw new ArgumentNullException("data");
-
-            using (MemoryStream stream = new MemoryStream(data))
-                return (BEncode.Decode(stream));
-        }
-
-
-        /// <summary>
-        /// Decode BEncoded data in the given byte array
-        /// </summary>
-        /// <param name="buffer">The byte array containing the BEncoded 
data</param>
-        /// <param name="offset">The offset at which the data starts at</param>
-        /// <param name="length">The number of bytes to be decoded</param>
-        /// <returns>BEncodedValue containing the data that was in the 
byte[]</returns>
-        public static IBEncodedValue Decode(byte[] buffer, int offset, int 
length)
-        {
-            if (buffer == null)
-                throw new ArgumentNullException("buffer");
-
-            if (offset > buffer.Length - length)
-                throw new ArgumentOutOfRangeException("length");
-
-            using (MemoryStream stream = new MemoryStream(buffer, offset, 
length))
-            using (BinaryReader reader = new BinaryReader(stream, 
Encoding.UTF8))
-                return Decode(reader);
-        }
-
-
-        /// <summary>
-        /// Decode BEncoded data in the given stream 
-        /// </summary>
-        /// <param name="stream">The stream containing the BEncoded 
data</param>
-        /// <returns>BEncodedValue containing the data that was in the 
stream</returns>
-        public static IBEncodedValue Decode(Stream stream)
-        {
-                       if (stream == null)
-                               throw new ArgumentNullException("stream");
-
-            using (BinaryReader reader = new BinaryReader(stream, 
Encoding.UTF8))
-                return Decode(reader);
-        }
-
-
-        /// <summary>
-        /// Decode BEncoded data in the given BinaryReader
-        /// </summary>
-        /// <param name="reader">The BinaryReader containing the BEncoded 
data</param>
-        /// <returns>BEncodedValue containing the data that was in the 
stream</returns>
-        public static IBEncodedValue Decode(BinaryReader reader)
-        {
-            if (reader == null)
-                throw new ArgumentNullException("reader");
-
-            IBEncodedValue data;
-            switch ((char)reader.PeekChar())
-            {
-                case ('i'):                         // Integer
-                    data = new BEncodedNumber();
-                    break;
-
-                case ('d'):                         // Dictionary
-                    data = new BEncodedDictionary();
-                    break;
-
-                case ('l'):                         // List
-                    data = new BEncodedList();
-                    break;
-
-                case ('1'):             // String
-                case ('2'):
-                case ('3'):
-                case ('4'):
-                case ('5'):
-                case ('6'):
-                case ('7'):
-                case ('8'):
-                case ('9'):
-                case ('0'):
-                    data = new BEncodedString();
-                    break;
-
-                default:
-                    throw new BEncodingException("Could not find what value to 
decode");
-            }
-
-            data.Decode(reader);
-            return data;
-        }
-    }
-}

Modified: trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedDictionary.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedDictionary.cs      
2007-05-23 23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedDictionary.cs      
2007-05-23 23:43:32 UTC (rev 77878)
@@ -38,85 +38,53 @@
     /// <summary>
     /// Class representing a BEncoded Dictionary
     /// </summary>
-    public class BEncodedDictionary : IBEncodedValue, 
IDictionary<BEncodedString, IBEncodedValue>
+    public class BEncodedDictionary : BEncodedValue, 
IDictionary<BEncodedString, BEncodedValue>
     {
         #region Member Variables
 
-        private SortedDictionary<BEncodedString, IBEncodedValue> dictionary;
+        private SortedDictionary<BEncodedString, BEncodedValue> dictionary;
 
         #endregion
 
 
         #region Constructors
+
         /// <summary>
         /// Create a new BEncodedDictionary
         /// </summary>
         public BEncodedDictionary()
-            : this(new SortedDictionary<BEncodedString, IBEncodedValue>())
         {
+            this.dictionary = new SortedDictionary<BEncodedString, 
BEncodedValue>();
         }
 
-        public BEncodedDictionary(SortedDictionary<BEncodedString, 
IBEncodedValue> dictionary)
-        {
-            this.dictionary = dictionary;
-        }
         #endregion
 
 
         #region Encode/Decode Methods
-        /// <summary>
-        /// Encodes the list to a byte[] using UTF8 Encoding
-        /// </summary>
-        /// <returns></returns>
-        public byte[] Encode()
-        {
-            return this.Encode(new UTF8Encoding(false, false));
-        }
 
         /// <summary>
-        /// Encodes the list to a byte[] using the supplied encoding
+        /// Encodes the dictionary to a byte[]
         /// </summary>
-        /// <returns></returns>
-        public byte[] Encode(Encoding e)
-        {
-            byte[] buffer = new byte[this.LengthInBytes(e)];
-            this.Encode(buffer, 0, e);
-            return buffer;
-        }
-
-        /// <summary>
-        /// Encodes the list to a byte[] using UTF8 Encoding
-        /// </summary>
         /// <param name="buffer">The buffer to encode the data to</param>
         /// <param name="offset">The offset to start writing the data 
to</param>
         /// <returns></returns>
-        public int Encode(byte[] buffer, int offset)
+        public override int Encode(byte[] buffer, int offset)
         {
-            return this.Encode(buffer, offset, new UTF8Encoding(false, false));
-        }
-
-        /// <summary>
-        /// Encodes the dictionary to a byte[] using the supplied encoding
-        /// </summary>
-        /// <param name="buffer">The buffer to encode the data to</param>
-        /// <param name="offset">The offset to start writing the data 
to</param>
-        /// <param name="e">The encoding to use</param>
-        /// <returns></returns>
-        public int Encode(byte[] buffer, int offset, Encoding e)
-        {
             int written = 0;
 
             //Dictionaries start with 'd'
-            written += e.GetBytes("d", 0, 1, buffer, offset);
+            buffer[offset] = (byte)'d';
+            written++;
 
-            foreach (KeyValuePair<BEncodedString, IBEncodedValue> keypair in 
this)
+            foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair in 
this)
             {
                 written += keypair.Key.Encode(buffer, offset + written);
                 written += keypair.Value.Encode(buffer, offset + written);
             }
 
             // Dictionaries end with 'e'
-            written += e.GetBytes("e", 0, 1, buffer, offset + written);        
         
+            buffer[offset + written] = (byte)'e';
+            written++;
             return written;
         }
 
@@ -124,10 +92,10 @@
         /// Decodes a BEncodedDictionary from the supplied StreamReader
         /// </summary>
         /// <param name="reader"></param>
-        public void Decode(BinaryReader reader)
+        internal override void DecodeInternal(BinaryReader reader)
         {
             BEncodedString key = null;
-            IBEncodedValue value = null;
+            BEncodedValue value = null;
             BEncodedString oldkey = null;
 
             try
@@ -137,12 +105,12 @@
 
                 while ((reader.PeekChar() != -1) && ((char)reader.PeekChar() 
!= 'e'))
                 {
-                    key = (BEncodedString)BEncode.Decode(reader); ;     // 
keys have to be BEncoded strings
+                    key = (BEncodedString)BEncodedValue.Decode(reader); ;     
// keys have to be BEncoded strings
                     if (oldkey != null && oldkey.CompareTo(key) > 0) 
                         throw new BEncodingException("Illegal 
BEncodedDictionary. The attributes are not ordered correctly");
                     
                     oldkey = key;
-                    value = BEncode.Decode(reader);                     // the 
value is a BEncoded value
+                    value = BEncodedValue.Decode(reader);                     
// the value is a BEncoded value
                     dictionary.Add(key, value);
                 }
 
@@ -158,44 +126,37 @@
                 throw new BEncodingException("Couldn't decode dictionary", ex);
             }
         }
+
         #endregion
 
 
         #region Helper Methods
+
         /// <summary>
         /// Returns the size of the dictionary in bytes using UTF8 encoding
         /// </summary>
         /// <returns></returns>
-        public int LengthInBytes()
+        public override int LengthInBytes()
         {
-            return this.LengthInBytes(new UTF8Encoding(false, false));
-        }
-
-        /// <summary>
-        /// Returns the size of the list in bytes using the supplied encoding
-        /// </summary>
-        /// <param name="e">The encoding to use</param>
-        /// <returns></returns>
-        public int LengthInBytes(Encoding e)
-        {
             int length = 0;
-            length += e.GetByteCount("d");   // Dictionaries start with 'd'
+            length += 1;   // Dictionaries start with 'd'
 
-            foreach (KeyValuePair<BEncodedString, IBEncodedValue> keypair in 
this.dictionary)
+            foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair in 
this.dictionary)
             {
                 length += keypair.Key.LengthInBytes();
                 length += keypair.Value.LengthInBytes();
             }
-            length += e.GetByteCount("e");   // Dictionaries end with 'e'
+            length += 1;   // Dictionaries end with 'e'
             return length;
         }
+
         #endregion
 
 
         #region Overridden Methods
         public override bool Equals(object obj)
         {
-            IBEncodedValue val;
+            BEncodedValue val;
             BEncodedDictionary dict = obj as BEncodedDictionary;
             if (dict == null)
                 return false;
@@ -203,7 +164,7 @@
             if (this.dictionary.Count != dict.dictionary.Count)
                 return false;
 
-            foreach (KeyValuePair<BEncodedString, IBEncodedValue> keypair in 
this.dictionary)
+            foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair in 
this.dictionary)
             {
                 if (!dict.TryGetValue(keypair.Key, out val))
                     return false;
@@ -227,7 +188,7 @@
         {
             StringBuilder sb = new StringBuilder(32);
 
-            foreach (KeyValuePair<BEncodedString, IBEncodedValue> keypair in 
dictionary)
+            foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair in 
dictionary)
             {
                 sb.Append(keypair.Key.ToString());
                 sb.Append(keypair.Value.ToString());
@@ -239,12 +200,12 @@
 
 
         #region IDictionary and IList methods
-        public void Add(BEncodedString key, IBEncodedValue value)
+        public void Add(BEncodedString key, BEncodedValue value)
         {
             this.dictionary.Add(key, value);
         }
 
-        public void Add(KeyValuePair<BEncodedString, IBEncodedValue> item)
+        public void Add(KeyValuePair<BEncodedString, BEncodedValue> item)
         {
             this.dictionary.Add(item.Key, item.Value);
         }
@@ -253,7 +214,7 @@
             this.dictionary.Clear();
         }
 
-        public bool Contains(KeyValuePair<BEncodedString, IBEncodedValue> item)
+        public bool Contains(KeyValuePair<BEncodedString, BEncodedValue> item)
         {
             if (!this.dictionary.ContainsKey(item.Key))
                 return false;
@@ -266,7 +227,7 @@
             return this.dictionary.ContainsKey(key);
         }
 
-        public void CopyTo(KeyValuePair<BEncodedString, IBEncodedValue>[] 
array, int arrayIndex)
+        public void CopyTo(KeyValuePair<BEncodedString, BEncodedValue>[] 
array, int arrayIndex)
         {
             this.dictionary.CopyTo(array, arrayIndex);
         }
@@ -296,7 +257,7 @@
             return this.dictionary.Remove(key);
         }
 
-        public bool Remove(KeyValuePair<BEncodedString, IBEncodedValue> item)
+        public bool Remove(KeyValuePair<BEncodedString, BEncodedValue> item)
         {
             return this.dictionary.Remove(item.Key);
         }
@@ -306,12 +267,12 @@
         //    this.dictionary.RemoveAt(index);
         //}
 
-        public bool TryGetValue(BEncodedString key, out IBEncodedValue value)
+        public bool TryGetValue(BEncodedString key, out BEncodedValue value)
         {
             return this.dictionary.TryGetValue(key, out value);
         }
 
-        public IBEncodedValue this[BEncodedString key]
+        public BEncodedValue this[BEncodedString key]
         {
             get { return this.dictionary[key]; }
             set { this.dictionary[key] = value; }
@@ -328,12 +289,12 @@
             get { return this.dictionary.Keys; }
         }
 
-        public ICollection<IBEncodedValue> Values
+        public ICollection<BEncodedValue> Values
         {
             get { return this.dictionary.Values; }
         }
 
-        public IEnumerator<KeyValuePair<BEncodedString, IBEncodedValue>> 
GetEnumerator()
+        public IEnumerator<KeyValuePair<BEncodedString, BEncodedValue>> 
GetEnumerator()
         {
             return this.dictionary.GetEnumerator();
         }

Modified: trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedList.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedList.cs    2007-05-23 
23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedList.cs    2007-05-23 
23:43:32 UTC (rev 77878)
@@ -38,10 +38,10 @@
     /// <summary>
     /// Class representing a BEncoded list
     /// </summary>
-    public class BEncodedList : IBEncodedValue, IList<IBEncodedValue>
+    public class BEncodedList : BEncodedValue, IList<BEncodedValue>
     {
         #region Member Variables
-        private List<IBEncodedValue> list;
+        private List<BEncodedValue> list;
         #endregion
 
 
@@ -50,7 +50,7 @@
         /// Create a new BEncoded List with default capacity
         /// </summary>
         public BEncodedList()
-            : this(new List<IBEncodedValue>())
+            : this(new List<BEncodedValue>())
         {
         }
 
@@ -59,7 +59,7 @@
         /// </summary>
         /// <param name="capacity">The initial capacity</param>
         public BEncodedList(int capacity)
-            : this(new List<IBEncodedValue>(capacity))
+            : this(new List<BEncodedValue>(capacity))
         {
 
         }
@@ -68,7 +68,7 @@
         /// Creates a new BEncoded list from the supplied List
         /// </summary>
         /// <param name="value">The list to use to create the 
BEncodedList</param>
-        public BEncodedList(List<IBEncodedValue> value)
+        public BEncodedList(List<BEncodedValue> value)
         {
             this.list = value;
         }
@@ -76,33 +76,23 @@
 
 
         #region Encode/Decode Methods
-        /// <summary>
-        /// Encodes the list to a byte[] using the supplied Encoding
-        /// </summary>
-        /// <returns></returns>
-        public byte[] Encode()
-        {
-            byte[] buffer = new byte[this.LengthInBytes()];
-            this.Encode(buffer, 0);
-            return buffer;
-        }
 
 
         /// <summary>
-        /// Encodes the list to a byte[] using the supplied encoding
+        /// Encodes the list to a byte[]
         /// </summary>
         /// <param name="buffer">The buffer to encode the list to</param>
         /// <param name="offset">The offset to start writing the data 
at</param>
         /// <returns></returns>
-        public int Encode(byte[] buffer, int offset)
+        public override int Encode(byte[] buffer, int offset)
         {
             int written = 0;
-            written += System.Text.Encoding.UTF8.GetBytes("l", 0, 1, buffer, 
offset);
-
-            foreach (IBEncodedValue value in this.list)
+            buffer[offset] = (byte)'l';
+            written++;
+            foreach (BEncodedValue value in this.list)
                 written += value.Encode(buffer, offset + written);
-
-            written += System.Text.Encoding.UTF8.GetBytes("e", 0, 1, buffer, 
offset + written);
+            buffer[offset + written] = (byte)'e';
+            written++;
             return written;
         }
 
@@ -110,7 +100,7 @@
         /// Decodes a BEncodedList from the given StreamReader
         /// </summary>
         /// <param name="reader"></param>
-        public void Decode(BinaryReader reader)
+        internal override void DecodeInternal(BinaryReader reader)
         {
             try
             {
@@ -118,7 +108,7 @@
                     throw new BEncodingException("Invalid data found. 
Aborting");
 
                 while ((reader.PeekChar() != -1) && ((char)reader.PeekChar() 
!= 'e'))
-                    list.Add(BEncode.Decode(reader));
+                    list.Add(BEncodedValue.Decode(reader));
 
                 if (reader.ReadByte() != 'e')                            // 
Remove the trailing 'e'
                     throw new BEncodingException("Invalid data found. 
Aborting");
@@ -137,19 +127,18 @@
 
         #region Helper Methods
         /// <summary>
-        /// Returns the size of the list in bytes using the supplied encoding
+        /// Returns the size of the list in bytes
         /// </summary>
-        /// <param name="e">The encoding to use</param>
         /// <returns></returns>
-        public int LengthInBytes()
+        public override int LengthInBytes()
         {
             int length = 0;
 
-            length += System.Text.Encoding.UTF8.GetByteCount("l");   // Lists 
start with 'l'
-            foreach (IBEncodedValue item in this.list)
+            length += 1;   // Lists start with 'l'
+            foreach (BEncodedValue item in this.list)
                 length += item.LengthInBytes();
 
-            length += System.Text.Encoding.UTF8.GetByteCount("e");   // Lists 
end with 'e'
+            length += 1;   // Lists end with 'e'
             return length;
         }
         #endregion
@@ -181,7 +170,7 @@
         {
             StringBuilder sb = new StringBuilder(32);
 
-            foreach (IBEncodedValue value in this.list)
+            foreach (BEncodedValue value in this.list)
                 sb.Append(value.ToString());
 
             return sb.ToString();
@@ -190,7 +179,7 @@
 
 
         #region IList methods
-        public void Add(IBEncodedValue item)
+        public void Add(BEncodedValue item)
         {
             this.list.Add(item);
         }
@@ -200,12 +189,12 @@
             this.list.Clear();
         }
 
-        public bool Contains(IBEncodedValue item)
+        public bool Contains(BEncodedValue item)
         {
             return this.list.Contains(item);
         }
 
-        public void CopyTo(IBEncodedValue[] array, int arrayIndex)
+        public void CopyTo(BEncodedValue[] array, int arrayIndex)
         {
             this.list.CopyTo(array, arrayIndex);
         }
@@ -215,12 +204,12 @@
             get { return this.list.Count; }
         }
 
-        public int IndexOf(IBEncodedValue item)
+        public int IndexOf(BEncodedValue item)
         {
             return this.list.IndexOf(item);
         }
 
-        public void Insert(int index, IBEncodedValue item)
+        public void Insert(int index, BEncodedValue item)
         {
             this.list.Insert(index, item);
         }
@@ -230,7 +219,7 @@
             get { return false; }
         }
 
-        public bool Remove(IBEncodedValue item)
+        public bool Remove(BEncodedValue item)
         {
             return this.list.Remove(item);
         }
@@ -240,13 +229,13 @@
             this.list.RemoveAt(index);
         }
 
-        public IBEncodedValue this[int index]
+        public BEncodedValue this[int index]
         {
             get { return this.list[index]; }
             set { this.list[index] = value; }
         }
 
-        public IEnumerator<IBEncodedValue> GetEnumerator()
+        public IEnumerator<BEncodedValue> GetEnumerator()
         {
             return this.list.GetEnumerator();
         }

Modified: trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedNumber.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedNumber.cs  2007-05-23 
23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedNumber.cs  2007-05-23 
23:43:32 UTC (rev 77878)
@@ -38,7 +38,7 @@
     /// <summary>
     /// Class representing a BEncoded number
     /// </summary>
-    public class BEncodedNumber : IBEncodedValue, IComparable<BEncodedNumber>
+    public class BEncodedNumber : BEncodedValue, IComparable<BEncodedNumber>
     {
         #region Member Variables
         /// <summary>
@@ -76,27 +76,21 @@
 
 
         #region Encode/Decode Methods
-        public byte[] Encode()
-        {
-            byte[] data = new byte[this.LengthInBytes()];
-            this.Encode(data, 0);
-            return data;
-        }
 
-
-
         /// <summary>
         /// Encodes this number to the supplied byte[] starting at the 
supplied offset
         /// </summary>
         /// <param name="buffer">The buffer to write the data to</param>
         /// <param name="offset">The offset to start writing the data 
at</param>
         /// <returns></returns>
-        public int Encode(byte[] buffer, int offset)
+        public override int Encode(byte[] buffer, int offset)
         {
             int written = 0;
-            written += System.Text.Encoding.UTF8.GetBytes("i", 0, 1, buffer, 
offset);
+            buffer[offset + written] = (byte)'i';
+            written++;
             written += 
System.Text.Encoding.UTF8.GetBytes(this.number.ToString(), 0, 
this.number.ToString().Length, buffer, offset + written);
-            written += System.Text.Encoding.UTF8.GetBytes("e", 0, 1, buffer, 
offset + written);
+            buffer[offset + written] = (byte)'e';
+            written++;
             return written;
         }
 
@@ -105,7 +99,7 @@
         /// Decodes a BEncoded number from the supplied BinaryReader
         /// </summary>
         /// <param name="reader">BinaryReader containing a BEncoded 
Number</param>
-        public void Decode(BinaryReader reader)
+        internal override void DecodeInternal(BinaryReader reader)
         {
             if (reader == null)
                 throw new ArgumentNullException("reader");
@@ -142,7 +136,7 @@
         /// Returns the length of the encoded string in bytes
         /// </summary>
         /// <returns></returns>
-        public int LengthInBytes()
+        public override int LengthInBytes()
         {
             return System.Text.Encoding.UTF8.GetByteCount('i' + 
this.number.ToString() + 'e');
         }

Modified: trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedString.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedString.cs  2007-05-23 
23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/BEncoding/BEncodedString.cs  2007-05-23 
23:43:32 UTC (rev 77878)
@@ -38,7 +38,7 @@
     /// <summary>
     /// Class representing a BEncoded string
     /// </summary>
-    public class BEncodedString : IBEncodedValue, IComparable<BEncodedString>
+    public class BEncodedString : BEncodedValue, IComparable<BEncodedString>
     {
         #region Member Variables
 
@@ -119,16 +119,6 @@
 
 
         #region Encode/Decode Methods
-        /// <summary>
-        /// Creates a BEncoded string representation of this string
-        /// </summary>
-        /// <returns></returns>
-        public byte[] Encode()
-        {
-            byte[] buffer = new byte[this.LengthInBytes()];
-            this.Encode(buffer, 0);
-            return buffer;
-        }
 
 
         /// <summary>
@@ -138,7 +128,7 @@
         /// <param name="offset">The offset at which to save the data 
to</param>
         /// <param name="e">The encoding to use</param>
         /// <returns>The number of bytes encoded</returns>
-        public int Encode(byte[] buffer, int offset)
+        public override int Encode(byte[] buffer, int offset)
         {
             string output = this.textBytes.Length + ":";
             int written = System.Text.Encoding.UTF8.GetBytes(output, 0, 
output.Length, buffer, offset);
@@ -151,7 +141,7 @@
         /// Decodes a BEncodedString from the supplied StreamReader
         /// </summary>
         /// <param name="reader">The StreamReader containing the 
BEncodedString</param>
-        public void Decode(BinaryReader reader)
+        internal override void DecodeInternal(BinaryReader reader)
         {
             if (reader == null)
                 throw new ArgumentNullException("reader");
@@ -188,7 +178,7 @@
 
 
         #region Helper Methods
-        public int LengthInBytes()
+        public override int LengthInBytes()
         {
             string output = this.textBytes.Length.ToString() + ":";
             return (output.Length + this.textBytes.Length);

Modified: trunk/bitsharp/src/MonoTorrent/BEncoding/IBEncodedValue.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/BEncoding/IBEncodedValue.cs  2007-05-23 
23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/BEncoding/IBEncodedValue.cs  2007-05-23 
23:43:32 UTC (rev 77878)
@@ -38,37 +38,141 @@
     /// <summary>
     /// Base interface for all BEncoded values.
     /// </summary>
-    public interface IBEncodedValue
+    public abstract class BEncodedValue
     {
         /// <summary>
         /// Encodes the BEncodedValue into a byte array
         /// </summary>
         /// <returns>Byte array containing the BEncoded Data</returns>
-        byte[] Encode();
+        public byte[] Encode()
+        {
+            byte[] buffer = new byte[LengthInBytes()];
 
+            if (Encode(buffer, 0) != buffer.Length)
+                throw new BEncodingException("Error encoding the data");
 
+            return buffer;
+        }
 
+        internal abstract void DecodeInternal(BinaryReader reader);
+
         /// <summary>
         /// Encodes the BEncodedValue into the supplied buffer
         /// </summary>
         /// <param name="buffer">The buffer to encode the information 
to</param>
         /// <param name="offset">The offset in the buffer to start writing the 
data</param>
         /// <returns></returns>
-        int Encode(byte[] buffer, int offset);
+        public abstract int Encode(byte[] buffer, int offset);
 
 
+        /// <summary>
+        /// Interface for all BEncoded values
+        /// </summary>
+        /// <param name="data">The byte array containing the BEncoded 
data</param>
+        /// <returns></returns>
+        public static BEncodedValue Decode(byte[] data)
+        {
+            if (data == null)
+                throw new ArgumentNullException("data");
 
+            using (MemoryStream stream = new MemoryStream(data))
+                return (BEncodedValue.Decode(stream));
+        }
+
+
         /// <summary>
-        /// Decodes the data in the supplied BinaryReader into BEncodedValues
+        /// Decode BEncoded data in the given byte array
         /// </summary>
-        /// <param name="reader">The StreamReader containing the data</param>
-        void Decode(BinaryReader reader);
+        /// <param name="buffer">The byte array containing the BEncoded 
data</param>
+        /// <param name="offset">The offset at which the data starts at</param>
+        /// <param name="length">The number of bytes to be decoded</param>
+        /// <returns>BEncodedValue containing the data that was in the 
byte[]</returns>
+        public static BEncodedValue Decode(byte[] buffer, int offset, int 
length)
+        {
+            if (buffer == null)
+                throw new ArgumentNullException("buffer");
 
+            if (offset > buffer.Length - length)
+                throw new ArgumentOutOfRangeException("length");
 
+            using (MemoryStream stream = new MemoryStream(buffer, offset, 
length))
+            using (BinaryReader reader = new BinaryReader(stream, 
Encoding.UTF8))
+                return Decode(reader);
+        }
+
+
         /// <summary>
+        /// Decode BEncoded data in the given stream 
+        /// </summary>
+        /// <param name="stream">The stream containing the BEncoded 
data</param>
+        /// <returns>BEncodedValue containing the data that was in the 
stream</returns>
+        public static BEncodedValue Decode(Stream stream)
+        {
+            if (stream == null)
+                throw new ArgumentNullException("stream");
+
+            using (BinaryReader reader = new BinaryReader(stream, 
Encoding.UTF8))
+                return Decode(reader);
+        }
+
+
+        /// <summary>
+        /// Decode BEncoded data in the given BinaryReader
+        /// </summary>
+        /// <param name="reader">The BinaryReader containing the BEncoded 
data</param>
+        /// <returns>BEncodedValue containing the data that was in the 
stream</returns>
+        public static BEncodedValue Decode(BinaryReader reader)
+        {
+            if (reader == null)
+                throw new ArgumentNullException("reader");
+
+            BEncodedValue data;
+            switch ((char)reader.PeekChar())
+            {
+                case ('i'):                         // Integer
+                    data = new BEncodedNumber();
+                    break;
+
+                case ('d'):                         // Dictionary
+                    data = new BEncodedDictionary();
+                    break;
+
+                case ('l'):                         // List
+                    data = new BEncodedList();
+                    break;
+
+                case ('1'):             // String
+                case ('2'):
+                case ('3'):
+                case ('4'):
+                case ('5'):
+                case ('6'):
+                case ('7'):
+                case ('8'):
+                case ('9'):
+                case ('0'):
+                    data = new BEncodedString();
+                    break;
+
+                default:
+                    throw new BEncodingException("Could not find what value to 
decode");
+            }
+
+            data.DecodeInternal(reader);
+            return data;
+        }
+
+
+        public static T Decode<T>(BinaryReader reader) where T : BEncodedValue
+        {
+            return (T)BEncodedValue.Decode(reader);
+        }
+
+
+        /// <summary>
         /// Returns the size of the byte[] needed to encode this BEncodedValue
         /// </summary>
         /// <returns></returns>
-        int LengthInBytes();
+        public abstract int LengthInBytes();
     }
 }
\ No newline at end of file

Modified: trunk/bitsharp/src/MonoTorrent/Client/ClientEngine.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Client/ClientEngine.cs       2007-05-23 
23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/Client/ClientEngine.cs       2007-05-23 
23:43:32 UTC (rev 77878)
@@ -40,7 +40,6 @@
 using System.Xml.Serialization;
 using MonoTorrent.Client.Encryption;
 using MonoTorrent.Common;
-using Nat;
 
 namespace MonoTorrent.Client
 {

Modified: trunk/bitsharp/src/MonoTorrent/Client/Managers/TrackerManager.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Client/Managers/TrackerManager.cs    
2007-05-23 23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/Client/Managers/TrackerManager.cs    
2007-05-23 23:43:32 UTC (rev 77878)
@@ -246,7 +246,7 @@
         private void HandleAnnounce(TrackerConnectionID id, BEncodedDictionary 
dict)
         {
             int peersAdded = 0;
-            foreach (KeyValuePair<BEncodedString, IBEncodedValue> keypair in 
dict)
+            foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair in 
dict)
             {
                 switch (keypair.Key.Text)
                 {
@@ -360,10 +360,10 @@
                 return;
 
             BEncodedDictionary files = (BEncodedDictionary)dict["files"];
-            foreach (KeyValuePair<BEncodedString, IBEncodedValue> keypair in 
files)
+            foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair in 
files)
             {
                 d = (BEncodedDictionary)keypair.Value;
-                foreach (KeyValuePair<BEncodedString, IBEncodedValue> kp in d)
+                foreach (KeyValuePair<BEncodedString, BEncodedValue> kp in d)
                 {
                     switch (kp.Key.ToString())
                     {
@@ -450,7 +450,7 @@
                     }
                     response.Close();
                     dataStream.Seek(0, SeekOrigin.Begin);
-                    return (BEncodedDictionary)BEncode.Decode(dataStream);
+                    return 
(BEncodedDictionary)BEncodedValue.Decode(dataStream);
                 }
             }
             catch (WebException)

Modified: 
trunk/bitsharp/src/MonoTorrent/Client/PeerMessages/ExtendedMessages/ExtendedListMessage.cs
===================================================================
--- 
trunk/bitsharp/src/MonoTorrent/Client/PeerMessages/ExtendedMessages/ExtendedListMessage.cs
  2007-05-23 23:07:49 UTC (rev 77877)
+++ 
trunk/bitsharp/src/MonoTorrent/Client/PeerMessages/ExtendedMessages/ExtendedListMessage.cs
  2007-05-23 23:43:32 UTC (rev 77878)
@@ -70,7 +70,7 @@
 
         internal void Decode(byte[] buffer, int offset, int length)
         {
-            this.dictionary = (BEncodedDictionary)BEncode.Decode(buffer, 
offset, length);
+            this.dictionary = (BEncodedDictionary)BEncodedValue.Decode(buffer, 
offset, length);
         }
 
         internal void Handle(PeerId id)

Modified: trunk/bitsharp/src/MonoTorrent/Common/Torrent.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Common/Torrent.cs    2007-05-23 23:07:49 UTC 
(rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/Common/Torrent.cs    2007-05-23 23:43:32 UTC 
(rev 77878)
@@ -46,7 +46,7 @@
     {
         #region Private Fields
 
-        private IBEncodedValue azureusProperties;
+        private BEncodedValue azureusProperties;
         private List<List<string>> announceUrls;
         private string comment;
         private string createdBy;
@@ -84,7 +84,7 @@
         /// <summary>
         /// FIXME: No idea what this is.
         /// </summary>
-        public IBEncodedValue AzureusProperties
+        public BEncodedValue AzureusProperties
         {
             get { return this.azureusProperties; }
         }
@@ -318,7 +318,7 @@
                 ed2k = null;
                 sha1 = null;
 
-                foreach (KeyValuePair<BEncodedString, IBEncodedValue> keypair 
in dict)
+                foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair 
in dict)
                 {
                     switch (keypair.Key.Text)
                     {
@@ -381,7 +381,7 @@
         /// <param name="dictionary">The dictionary representing the Info 
section of the .torrent file</param>
         private void ProcessInfo(BEncodedDictionary dictionary)
         {
-            foreach (KeyValuePair<BEncodedString, IBEncodedValue> keypair in 
dictionary)
+            foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair in 
dictionary)
             {
                 switch (keypair.Key.Text)
                 {
@@ -512,7 +512,7 @@
             {
                 try
                 {
-                    Torrent t = 
Torrent.Load((BEncodedDictionary)BEncode.Decode(reader));
+                    Torrent t = 
Torrent.Load((BEncodedDictionary)BEncodedValue.Decode(reader));
                     t.torrentPath = path;
                     return t;
                 }
@@ -531,7 +531,7 @@
         public static Torrent Load(BEncodedDictionary torrentInformation)
         {
             Torrent t = new Torrent();
-            foreach (KeyValuePair<BEncodedString, IBEncodedValue> keypair in 
torrentInformation)
+            foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair in 
torrentInformation)
             {
                 switch (keypair.Key.Text)
                 {

Modified: trunk/bitsharp/src/MonoTorrent/Common/TorrentCreator.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Common/TorrentCreator.cs     2007-05-23 
23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/Common/TorrentCreator.cs     2007-05-23 
23:43:32 UTC (rev 77878)
@@ -75,7 +75,7 @@
         {
             get
             {
-                IBEncodedValue val = Get(this.torrent, new 
BEncodedString("comment"));
+                BEncodedValue val = Get(this.torrent, new 
BEncodedString("comment"));
                 return val == null ? string.Empty : val.ToString();
             }
             set { Set(this.torrent, "comment", new BEncodedString(value)); }
@@ -88,7 +88,7 @@
         {
             get
             {
-                IBEncodedValue val = Get(this.torrent, new 
BEncodedString("created by"));
+                BEncodedValue val = Get(this.torrent, new 
BEncodedString("created by"));
                 return val == null ? string.Empty : val.ToString();
             }
             set { Set(this.torrent, "created by", new BEncodedString(value)); }
@@ -123,7 +123,7 @@
         {
             get
             {
-                IBEncodedValue val = 
Get((BEncodedDictionary)this.torrent["info"], new BEncodedString("piece 
length"));
+                BEncodedValue val = 
Get((BEncodedDictionary)this.torrent["info"], new BEncodedString("piece 
length"));
                 return val == null ? -1 : ((BEncodedNumber)val).Number;
             }
             set { Set((BEncodedDictionary)this.torrent["info"], "piece 
length", new BEncodedNumber(value)); }
@@ -136,7 +136,7 @@
         {
             get
             {
-                IBEncodedValue val = 
Get((BEncodedDictionary)this.torrent["info"], new BEncodedString("private"));
+                BEncodedValue val = 
Get((BEncodedDictionary)this.torrent["info"], new BEncodedString("private"));
                 return val == null ? false : ((BEncodedNumber)val).Number == 1;
             }
             set { Set((BEncodedDictionary)this.torrent["info"], "private", new 
BEncodedNumber(value ? 1 : 0)); }
@@ -147,7 +147,7 @@
         {
             get
             {
-                IBEncodedValue val = Get(this.torrent, new 
BEncodedString("publisher"));
+                BEncodedValue val = Get(this.torrent, new 
BEncodedString("publisher"));
                 return val == null ? string.Empty : val.ToString();
             }
             set { Set(this.torrent, "publisher", new BEncodedString(value)); }
@@ -160,7 +160,7 @@
         {
             get
             {
-                IBEncodedValue val = Get(this.torrent, new 
BEncodedString("publisher-url"));
+                BEncodedValue val = Get(this.torrent, new 
BEncodedString("publisher-url"));
                 return val == null ? string.Empty : val.ToString();
             }
             set { Set(this.torrent, "publisher-url", new 
BEncodedString(value)); }
@@ -288,7 +288,7 @@
         /// <summary>
         /// This can be used to add custom values to the main bencoded 
dictionary
         /// </summary>        
-        public void AddCustom(BEncodedString key, IBEncodedValue value)
+        public void AddCustom(BEncodedString key, BEncodedValue value)
         {
             this.torrent.Add(key, value);
         }
@@ -297,7 +297,7 @@
         /// <summary>
         /// This can be used to add custom values to the main bencoded 
dictionary
         /// </summary>        
-        public void AddCustom(KeyValuePair<BEncodedString, IBEncodedValue> 
customInfo)
+        public void AddCustom(KeyValuePair<BEncodedString, BEncodedValue> 
customInfo)
         {
             this.torrent.Add(customInfo);
         }
@@ -443,7 +443,7 @@
         }
 
 
-        private static IBEncodedValue Get(BEncodedDictionary dictionary, 
BEncodedString key)
+        private static BEncodedValue Get(BEncodedDictionary dictionary, 
BEncodedString key)
         {
             return dictionary.ContainsKey(key) ? dictionary[key] : null;
         }
@@ -534,7 +534,7 @@
 
         /// <summary>This can be used to remove custom values from the main 
bencoded dictionary.
         /// </summary>
-        public void RemoveCustom(KeyValuePair<BEncodedString, IBEncodedValue> 
customInfo)
+        public void RemoveCustom(KeyValuePair<BEncodedString, BEncodedValue> 
customInfo)
         {
             this.torrent.Remove(customInfo);
         }
@@ -559,7 +559,7 @@
         }
 
 
-        private static void Set(BEncodedDictionary dictionary, BEncodedString 
key, IBEncodedValue value)
+        private static void Set(BEncodedDictionary dictionary, BEncodedString 
key, BEncodedValue value)
         {
             if (dictionary.ContainsKey(key))
                 dictionary[key] = value;

Modified: trunk/bitsharp/src/MonoTorrent/Tracker/ITorrentManager.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Tracker/ITorrentManager.cs   2007-05-23 
23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/Tracker/ITorrentManager.cs   2007-05-23 
23:43:32 UTC (rev 77878)
@@ -66,7 +66,7 @@
         ///</summary>
         ///<returns>if par.compact is true then the value is a BEncodedString 
otherwise it's a BEncodedDictionary
         ///</returns>
-        IBEncodedValue GetPeersList(AnnounceParameters par);     
+        BEncodedValue GetPeersList(AnnounceParameters par);     
         
         
         ///<summary>this method returns the scrape entry for this 
torrent</summary>

Modified: trunk/bitsharp/src/MonoTorrent/Tracker/SimpleTorrentManager.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Tracker/SimpleTorrentManager.cs      
2007-05-23 23:07:49 UTC (rev 77877)
+++ trunk/bitsharp/src/MonoTorrent/Tracker/SimpleTorrentManager.cs      
2007-05-23 23:43:32 UTC (rev 77878)
@@ -140,7 +140,7 @@
             peer.Update(par);
         }
         
-        public IBEncodedValue GetPeersList(AnnounceParameters par)
+        public BEncodedValue GetPeersList(AnnounceParameters par)
         {
             if (par.compact) {
                 return GetCompactList(par);
@@ -150,7 +150,7 @@
         }
         
         //TODO refactor - done not debuged
-        private IBEncodedValue GetCompactList(AnnounceParameters par)
+        private BEncodedValue GetCompactList(AnnounceParameters par)
         {            
             Peer exclude = null;
             if (peers.Contains(Peer.GetKey(par))) {
@@ -172,11 +172,11 @@
         }
         
         //TODO refactor: done - not debuged
-        private IBEncodedValue GetNonCompactList(AnnounceParameters par)
+        private BEncodedValue GetNonCompactList(AnnounceParameters par)
         {
             Peer exclude = peers.Get(Peer.GetKey(par));            
             IList<Peer> randomPeers = peers.GetRandomPeers(par.numberWanted, 
exclude);            
-            List<IBEncodedValue> announceList = new 
List<IBEncodedValue>(randomPeers.Count);
+            List<BEncodedValue> announceList = new 
List<BEncodedValue>(randomPeers.Count);
             
             foreach (Peer each in randomPeers) {
                 announceList.Add(each.PeersEntry);

_______________________________________________
Mono-patches maillist  -  [email protected]
http://lists.ximian.com/mailman/listinfo/mono-patches

Reply via email to