Skip to content

Commit bd7bd49

Browse files
committed
Add Torrent.PiecesAsHexString property
1 parent b411941 commit bd7bd49

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

BencodeNET/Torrents/Torrent.cs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.IO;
55
using System.Linq;
66
using System.Text;
7+
using System.Text.RegularExpressions;
78
using BencodeNET.Exceptions;
89
using BencodeNET.IO;
910

@@ -128,9 +129,39 @@ public virtual string DisplayName
128129
// TODO: Split into list of 20-byte hashes and rename to something appropriate?
129130
/// <summary>
130131
/// A concatenation of all 20-byte SHA1 hash values (one for each piece).
132+
/// Use <see cref="PiecesAsHexString"/> to get/set this value as a hex string instead.
131133
/// </summary>
132134
public virtual byte[] Pieces { get; set; }
133135

136+
/// <summary>
137+
/// Gets or sets <see cref="Pieces"/> from/to a hex string (without dashes), e.g. 1C115D26444AEF2A5E936133DCF8789A552BBE9F[...].
138+
/// The length of the string must be a multiple of 40.
139+
/// </summary>
140+
public virtual string PiecesAsHexString
141+
{
142+
get
143+
{
144+
return BitConverter.ToString(Pieces).Replace("-", "");
145+
}
146+
set
147+
{
148+
if (value?.Length % 40 != 0)
149+
throw new ArgumentException("Value length must be a multiple of 40 (20 bytes as hex).");
150+
151+
if (Regex.IsMatch(value, "[^0-9A-F]"))
152+
throw new ArgumentException("Value must only contain hex characters (0-9 and A-F) and only uppercase.");
153+
154+
var bytes = new byte[value.Length/2];
155+
for (var i = 0; i < bytes.Length; i++)
156+
{
157+
var str = $"{value[i*2]}{value[i*2+1]}";
158+
bytes[i] = Convert.ToByte(str, 16);
159+
}
160+
161+
Pieces = bytes;
162+
}
163+
}
164+
134165
/// <summary>
135166
/// [optional] If set to true clients must only publish it's presence to the defined trackers.
136167
/// Mainly used for private trackers which don't allow PEX, DHT etc.
@@ -209,7 +240,7 @@ protected virtual BDictionary CreateInfoDictionary(Encoding encoding)
209240
if (PieceSize > 0)
210241
info[TorrentInfoFields.PieceLength] = (BNumber) PieceSize;
211242

212-
if (Pieces != null)
243+
if (Pieces?.Length > 0)
213244
info[TorrentInfoFields.Pieces] = new BString(Pieces, encoding);
214245

215246
if (IsPrivate)

0 commit comments

Comments
 (0)