/// <summary> /// Decodes a BEncoded number from the supplied RawReader /// </summary> /// <param name="reader">RawReader containing a BEncoded Number</param> internal override void DecodeInternal(RawReader reader) { var sign = 1; if (reader == null) { throw new ArgumentNullException("reader"); } try { if (reader.ReadByte() != 'i') // remove the leading 'i' { throw new BEncodingException("Invalid data found. Aborting."); } if (reader.PeekChar() == '-') { sign = -1; reader.ReadChar(); } int letter; while (((letter = reader.PeekChar()) != -1) && letter != 'e') { if (letter < '0' || letter > '9') { throw new BEncodingException("Invalid number found."); } number = number * 10 + (letter - '0'); reader.ReadChar(); } if (reader.ReadByte() != 'e') //remove the trailing 'e' { throw new BEncodingException("Invalid data found. Aborting."); } number *= sign; } catch (BEncodingException ex) { throw new BEncodingException("Couldn't decode number", ex); } catch { throw new BEncodingException("Couldn't decode number"); } }
/// <summary> /// Decodes a BEncodedString from the supplied StreamReader /// </summary> /// <param name="reader">The StreamReader containing the BEncodedString</param> internal override void DecodeInternal(RawReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } int letterCount; var length = string.Empty; try { while ((reader.PeekChar() != -1) && (reader.PeekChar() != ':')) // read in how many characters { length += (char)reader.ReadChar(); // the string is } if (reader.ReadChar() != ':') // remove the ':' { throw new BEncodingException("Invalid data found. Aborting"); } if (!int.TryParse(length, out letterCount)) { throw new BEncodingException(string.Format("Invalid BEncodedString. Length was '{0}' instead of a number", length)); } textBytes = new byte[letterCount]; if (reader.Read(textBytes, 0, letterCount) != letterCount) { throw new BEncodingException("Couldn't decode string"); } } catch (Exception ex) { if (ex is BEncodingException) { throw; } else { throw new BEncodingException("Couldn't decode string", ex); } } }