1
using System.Reflection;
4
using System.Net.Sockets;
5
using System.Threading;
6
using System.Collections.Specialized;
10
using ICSharpCode.SharpZipLib.Zip.Compression;
12
using System.Collections;
13
using System.Collections.Generic;
14
using System.Diagnostics;
15
using System.Globalization;
17
using System.Runtime.CompilerServices;
19
using System.Text.RegularExpressions;
21
internal static class Extensions
23
private static readonly long EPOCH_TICKS;
27
DateTime time = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
28
EPOCH_TICKS = time.Ticks;
31
public static void Add<T> (this IList<T> list, int index, T item)
33
list.Insert (index, item);
36
public static StringBuilder AppendRange (this StringBuilder sb, string str, int start, int end)
38
return sb.Append (str, start, end - start);
41
public static StringBuilder Delete (this StringBuilder sb, int start, int end)
43
return sb.Remove (start, end - start);
46
public static void SetCharAt (this StringBuilder sb, int index, char c)
51
public static int IndexOf (this StringBuilder sb, string str)
53
return sb.ToString ().IndexOf (str);
56
public static Iterable<T> AsIterable<T> (this IEnumerable<T> s)
58
return new EnumerableWrapper<T> (s);
61
public static int BitCount (int val)
65
for (int i = 0; i < 32; i++) {
74
public static IndexOutOfRangeException CreateIndexOutOfRangeException (int index)
76
return new IndexOutOfRangeException ("Index: " + index);
79
public static CultureInfo CreateLocale (string language, string country, string variant)
81
return CultureInfo.GetCultureInfo ("en-US");
84
public static string Name (this Encoding e)
86
return e.BodyName.ToUpper ();
89
public static string Decode (this Encoding e, byte[] chars, int start, int len)
92
byte[] bom = e.GetPreamble ();
93
if (bom != null && bom.Length > 0) {
94
if (len >= bom.Length) {
97
for (int n=0; n<bom.Length && hasBom; n++) {
98
if (bom[n] != chars [pos++])
107
return e.GetString (chars, start, len);
108
} catch (DecoderFallbackException) {
109
throw new CharacterCodingException ();
113
public static string Decode (this Encoding e, ByteBuffer buffer)
115
return e.Decode (buffer.Array (), buffer.ArrayOffset () + buffer.Position (), buffer.Limit () - buffer.Position ());
118
public static ByteBuffer Encode (this Encoding e, CharSequence str)
120
return ByteBuffer.Wrap (e.GetBytes (str.ToString ()));
123
public static ByteBuffer Encode (this Encoding e, string str)
125
return ByteBuffer.Wrap (e.GetBytes (str));
128
public static Encoding GetEncoding (string name)
130
// Encoding e = Encoding.GetEncoding (name, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
131
Encoding e = Encoding.GetEncoding (name.Replace ('_','-'));
132
if (e is UTF8Encoding)
133
return new UTF8Encoding (false, true);
137
public static ICollection<KeyValuePair<T, U>> EntrySet<T, U> (this IDictionary<T, U> s)
142
public static void Finish (this Inflater i)
146
public static bool AddItem<T> (this IList<T> list, T item)
152
public static bool AddItem<T> (this ICollection<T> list, T item)
158
public static U Get<T, U> (this IDictionary<T, U> d, T key)
161
d.TryGetValue (key, out val);
165
public static U Put<T, U> (this IDictionary<T, U> d, T key, U value)
168
d.TryGetValue (key, out old);
173
public static void PutAll<T, U> (this IDictionary<T, U> d, IDictionary<T, U> values)
175
foreach (KeyValuePair<T,U> val in values)
176
d[val.Key] = val.Value;
179
public static object Put (this Hashtable d, object key, object value)
181
object old = d [key];
186
public static string Put (this StringDictionary d, string key, string value)
188
string old = d [key];
193
public static CultureInfo GetEnglishCulture ()
195
return CultureInfo.GetCultureInfo ("en-US");
198
public static T GetFirst<T> (this IList<T> list)
200
return ((list.Count == 0) ? default(T) : list[0]);
203
public static CultureInfo GetGermanCulture ()
205
CultureInfo r = CultureInfo.GetCultureInfo ("de-DE");
209
public static T GetLast<T> (this IList<T> list)
211
return ((list.Count == 0) ? default(T) : list[list.Count - 1]);
214
public static int GetOffset (this TimeZoneInfo tzone, long date)
216
return (int)tzone.GetUtcOffset (MillisToDateTimeOffset (date, 0).DateTime).TotalMilliseconds;
219
public static InputStream GetResourceAsStream (this Type type, string name)
221
string str2 = type.Assembly.GetName ().Name;
222
string[] textArray1 = new string[] { str2, ".resources.", type.Namespace, ".", name };
223
string str = string.Concat (textArray1);
224
Stream manifestResourceStream = type.Assembly.GetManifestResourceStream (str);
225
if (manifestResourceStream == null) {
228
return InputStream.Wrap (manifestResourceStream);
231
public static long GetTime (this DateTime dateTime)
233
return new DateTimeOffset (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch ();
236
public static TimeZoneInfo GetTimeZone (string tzone)
239
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById (tzone);
244
char[] separator = new char[] { ':' };
245
string[] strArray = tzone.Substring (4).Split (separator);
247
if (strArray.Length == 1 && strArray[0].Length > 2) {
248
hours = int.Parse (strArray[0].Substring (0, 2));
249
minutes = int.Parse (strArray[0].Substring (2));
251
hours = int.Parse (strArray[0]);
252
minutes = (strArray.Length <= 1) ? 0 : int.Parse (strArray[1]);
254
TimeSpan t = new TimeSpan (0, hours, minutes, 0, 0);
257
return TimeZoneInfo.CreateCustomTimeZone (tzone, t, tzone, tzone);
260
public static void InitCause (this Exception ex, Exception cause)
262
Console.WriteLine (cause);
265
public static bool IsEmpty<T> (this ICollection<T> col)
267
return (col.Count == 0);
270
public static bool IsEmpty<T> (this Stack<T> col)
272
return (col.Count == 0);
275
public static bool IsLower (this char c)
277
return char.IsLower (c);
280
public static bool IsUpper (this char c)
282
return char.IsUpper (c);
285
public static Sharpen.Iterator<T> Iterator<T> (this ICollection<T> col)
287
return new EnumeratorWrapper<T> (col, col.GetEnumerator ());
290
public static Sharpen.Iterator<T> Iterator<T> (this IEnumerable<T> col)
292
return new EnumeratorWrapper<T> (col, col.GetEnumerator ());
295
public static T Last<T> (this ICollection<T> col)
297
IList<T> list = col as IList<T>;
299
return list[list.Count - 1];
301
return col.Last<T> ();
304
public static ListIterator<T> ListIterator<T> (this IList<T> col, int n)
306
return new ListIterator<T> (col, n);
309
public static int LowestOneBit (int val)
311
return (((int)1) << NumberOfTrailingZeros (val));
314
public static bool Matches (this string str, string regex)
316
Regex regex2 = new Regex (regex);
317
return regex2.IsMatch (str);
320
public static DateTime CreateDate (long milliSecondsSinceEpoch)
322
long num = EPOCH_TICKS + (milliSecondsSinceEpoch * 10000);
323
return new DateTime (num);
326
public static DateTimeOffset MillisToDateTimeOffset (long milliSecondsSinceEpoch, long offsetMinutes)
328
TimeSpan offset = TimeSpan.FromMinutes ((double)offsetMinutes);
329
long num = EPOCH_TICKS + (milliSecondsSinceEpoch * 10000);
330
return new DateTimeOffset (num + offset.Ticks, offset);
333
public static CharsetDecoder NewDecoder (this Encoding enc)
335
return new CharsetDecoder (enc);
338
public static CharsetEncoder NewEncoder (this Encoding enc)
340
return new CharsetEncoder (enc);
343
public static int NumberOfLeadingZeros (int val)
345
uint num = (uint)val;
347
while ((num & 0x80000000) == 0) {
354
public static int NumberOfTrailingZeros (int val)
356
uint num = (uint)val;
358
while ((num & 1) == 0) {
365
public static int Read (this StreamReader reader, char[] data)
367
return reader.Read (data, 0, data.Length);
370
public static T Remove<T> (this IList<T> list, T item)
372
int index = list.IndexOf (item);
376
T local = list[index];
377
list.RemoveAt (index);
381
public static T Remove<T> (this IList<T> list, int i)
387
} catch (IndexOutOfRangeException) {
388
throw new NoSuchElementException ();
393
public static T RemoveFirst<T> (this IList<T> list)
395
return list.Remove<T> (0);
398
public static string ReplaceAll (this string str, string regex, string replacement)
400
Regex rgx = new Regex (regex);
402
if (replacement.IndexOfAny (new char[] { '\\','$' }) != -1) {
403
// Back references not yet supported
404
StringBuilder sb = new StringBuilder ();
405
for (int n=0; n<replacement.Length; n++) {
406
char c = replacement [n];
408
throw new NotSupportedException ("Back references not supported");
410
c = replacement [++n];
413
replacement = sb.ToString ();
416
return rgx.Replace (str, replacement);
419
public static bool RegionMatches (this string str, bool ignoreCase, int toOffset, string other, int ooffset, int len)
421
if (toOffset < 0 || ooffset < 0 || toOffset + len > str.Length || ooffset + len > other.Length)
423
return string.Compare (str, toOffset, other, ooffset, len) == 0;
426
public static T Set<T> (this IList<T> list, int index, T item)
433
public static int Signum (long val)
444
public static void RemoveAll<T,U> (this ICollection<T> col, ICollection<U> items) where U:T
446
foreach (var u in items)
450
public static bool ContainsAll<T,U> (this ICollection<T> col, ICollection<U> items) where U:T
452
foreach (var u in items)
453
if (!col.Any (n => (object.ReferenceEquals (n, u)) || n.Equals (u)))
458
public static bool Contains<T> (this ICollection<T> col, object item)
462
return col.Any (n => (object.ReferenceEquals (n, item)) || n.Equals (item));
465
public static void Sort<T> (this IList<T> list)
467
List<T> sorted = new List<T> (list);
469
for (int i = 0; i < list.Count; i++) {
474
public static void Sort<T> (this IList<T> list, IComparer<T> comparer)
476
List<T> sorted = new List<T> (list);
477
sorted.Sort (comparer);
478
for (int i = 0; i < list.Count; i++) {
483
public static string[] Split (this string str, string regex)
485
return str.Split (regex, 0);
488
public static string[] Split (this string str, string regex, int limit)
490
Regex rgx = new Regex (regex);
491
List<string> list = new List<string> ();
495
foreach (Match match in rgx.Matches (str)) {
496
list.Add (str.Substring (startIndex, match.Index - startIndex));
497
startIndex = match.Index + match.Length;
498
if (limit > 0 && ++nm == limit)
502
if (startIndex < str.Length) {
503
list.Add (str.Substring (startIndex));
506
int count = list.Count - 1;
507
while ((count >= 0) && (list[count].Length == 0)) {
510
list.RemoveRange (count + 1, (list.Count - count) - 1);
512
return list.ToArray ();
515
public static IList<T> SubList<T> (this IList<T> list, int start, int len)
517
List<T> sublist = new List<T> (len);
518
for (int i = start; i < (start + len); i++) {
519
sublist.Add (list[i]);
524
public static char[] ToCharArray (this string str)
526
char[] destination = new char[str.Length];
527
str.CopyTo (0, destination, 0, str.Length);
531
public static long ToMillisecondsSinceEpoch (this DateTime dateTime)
533
if (dateTime.Kind != DateTimeKind.Utc) {
534
throw new ArgumentException ("dateTime is expected to be expressed as a UTC DateTime", "dateTime");
536
return new DateTimeOffset (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch ();
539
public static long ToMillisecondsSinceEpoch (this DateTimeOffset dateTimeOffset)
541
return (((dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks) - EPOCH_TICKS) / TimeSpan.TicksPerMillisecond);
544
public static string ToOctalString (int val)
546
return Convert.ToString (val, 8);
549
public static string ToString (object val)
551
return val.ToString ();
554
public static string ToString (int val, int bas)
556
return Convert.ToString (val, bas);
559
public static IList<U> UpcastTo<T, U> (this IList<T> s) where T : U
561
List<U> list = new List<U> (s.Count);
562
for (int i = 0; i < s.Count; i++) {
568
public static ICollection<U> UpcastTo<T, U> (this ICollection<T> s) where T : U
570
List<U> list = new List<U> (s.Count);
571
foreach (var v in s) {
577
public static T ValueOf<T> (T val)
582
public static int GetTotalInFixed (this Inflater inf)
585
return inf.TotalIn + 4;
590
public static int GetRemainingInputFixed (this Inflater inf)
592
if (inf.RemainingInput >= 4)
593
return inf.RemainingInput - 4;
598
public static string GetTestName (object obj)
600
return GetTestName ();
603
public static string GetTestName ()
608
met = new StackFrame (n).GetMethod ();
610
foreach (Attribute at in met.GetCustomAttributes (true)) {
611
if (at.GetType().FullName == "NUnit.Framework.TestAttribute") {
612
// Convert back to camel case
613
string name = met.Name;
614
if (char.IsUpper (name[0]))
615
name = char.ToLower (name[0]) + name.Substring (1);
621
} while (met != null);
625
public static string GetHostAddress (this IPAddress addr)
627
return addr.ToString ();
630
public static IPAddress GetAddressByName (string name)
632
if (name == "0.0.0.0")
633
return IPAddress.Any;
634
return Dns.GetHostAddresses (name).FirstOrDefault ();
637
public static string GetImplementationVersion (this System.Reflection.Assembly asm)
639
return asm.GetName ().Version.ToString ();
642
public static string GetHost (this Uri uri)
644
return string.IsNullOrEmpty (uri.Host) ? null : uri.Host;
647
public static string GetUserInfo (this Uri uri)
649
return string.IsNullOrEmpty (uri.UserInfo) ? null : uri.UserInfo;
652
public static string GetQuery (this Uri uri)
654
return string.IsNullOrEmpty (uri.Query) ? null : uri.Query;
657
public static HttpURLConnection OpenConnection (this Uri uri, Proxy p)
659
return new HttpsURLConnection (uri, p);
662
public static Uri ToURI (this Uri uri)
667
public static Uri ToURL (this Uri uri)
672
public static InputStream GetInputStream (this Socket socket)
674
return new System.Net.Sockets.NetworkStream (socket);
677
public static OutputStream GetOutputStream (this Socket socket)
679
return new System.Net.Sockets.NetworkStream (socket);
682
public static int GetLocalPort (this Socket socket)
684
return ((IPEndPoint)socket.LocalEndPoint).Port;
687
public static int GetPort (this Socket socket)
689
return ((IPEndPoint)socket.RemoteEndPoint).Port;
692
public static IPAddress GetInetAddress (this Socket socket)
694
return ((IPEndPoint)socket.RemoteEndPoint).Address;
697
public static void Bind2 (this Socket socket, EndPoint ep)
700
socket.Bind (new IPEndPoint (IPAddress.Any, 0));
706
public static void Connect (this Socket socket, EndPoint ep, int timeout)
709
IAsyncResult res = socket.BeginConnect (ep,null, null);
710
if (!res.AsyncWaitHandle.WaitOne (timeout > 0 ? timeout : Timeout.Infinite, true))
711
throw new IOException ("Connection timeout");
712
} catch (SocketException se) {
713
throw new IOException (se.Message);
717
public static Socket CreateServerSocket (int port, int backlog, IPAddress addr)
719
Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
720
s.Bind (new IPEndPoint (addr, port));
724
public static Socket CreateSocket (string host, int port)
726
Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
727
s.Connect (host, port);
731
public static Socket CreateSocket ()
733
return new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
736
public static bool RemoveElement (this ArrayList list, object elem)
738
int i = list.IndexOf (elem);
747
public static System.Threading.Semaphore CreateSemaphore (int count)
749
return new System.Threading.Semaphore (count, int.MaxValue);
752
public static void SetCommand (this ProcessStartInfo si, IList<string> args)
754
si.FileName = args[0];
755
si.Arguments = string.Join (" ", args.Skip (1).Select (a => "\"" + a + "\"").ToArray ());
758
public static SystemProcess Start (this ProcessStartInfo si)
760
si.UseShellExecute = false;
761
si.RedirectStandardInput = true;
762
si.RedirectStandardError = true;
763
si.RedirectStandardOutput = true;
764
si.CreateNoWindow = true;
765
return SystemProcess.Start (si);