Extensions.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. //using Windows.Networking;
  15. //using Windows.Networking.Sockets;
  16. namespace SharpCifs.Util.Sharpen
  17. {
  18. public static class Extensions
  19. {
  20. private static readonly long EpochTicks;
  21. static Extensions()
  22. {
  23. DateTime time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  24. EpochTicks = time.Ticks;
  25. }
  26. public static void Add<T>(this IList<T> list, int index, T item)
  27. {
  28. list.Insert(index, item);
  29. }
  30. public static void AddFirst<T>(this IList<T> list, T item)
  31. {
  32. list.Insert(0, item);
  33. }
  34. public static void AddLast<T>(this IList<T> list, T item)
  35. {
  36. list.Add(item);
  37. }
  38. public static void RemoveLast<T>(this IList<T> list)
  39. {
  40. if (list.Count > 0)
  41. list.Remove(list.Count - 1);
  42. }
  43. public static StringBuilder AppendRange(this StringBuilder sb, string str, int start, int end)
  44. {
  45. return sb.Append(str, start, end - start);
  46. }
  47. public static StringBuilder Delete(this StringBuilder sb, int start, int end)
  48. {
  49. return sb.Remove(start, end - start);
  50. }
  51. public static void SetCharAt(this StringBuilder sb, int index, char c)
  52. {
  53. sb[index] = c;
  54. }
  55. public static int IndexOf(this StringBuilder sb, string str)
  56. {
  57. return sb.ToString().IndexOf(str);
  58. }
  59. public static int BitCount(int val)
  60. {
  61. uint num = (uint)val;
  62. int count = 0;
  63. for (int i = 0; i < 32; i++)
  64. {
  65. if ((num & 1) != 0)
  66. {
  67. count++;
  68. }
  69. num >>= 1;
  70. }
  71. return count;
  72. }
  73. public static IndexOutOfRangeException CreateIndexOutOfRangeException(int index)
  74. {
  75. return new IndexOutOfRangeException("Index: " + index);
  76. }
  77. public static string Decode(this Encoding e, byte[] chars, int start, int len)
  78. {
  79. try
  80. {
  81. byte[] bom = e.GetPreamble();
  82. if (bom != null && bom.Length > 0)
  83. {
  84. if (len >= bom.Length)
  85. {
  86. int pos = start;
  87. bool hasBom = true;
  88. for (int n = 0; n < bom.Length && hasBom; n++)
  89. {
  90. if (bom[n] != chars[pos++])
  91. hasBom = false;
  92. }
  93. if (hasBom)
  94. {
  95. len -= pos - start;
  96. start = pos;
  97. }
  98. }
  99. }
  100. return e.GetString(chars, start, len);
  101. }
  102. catch (DecoderFallbackException)
  103. {
  104. throw new CharacterCodingException();
  105. }
  106. }
  107. public static Encoding GetEncoding(string name)
  108. {
  109. // Encoding e = Encoding.GetEncoding (name, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
  110. try
  111. {
  112. Encoding e = Encoding.GetEncoding(name.Replace('_', '-'));
  113. if (e is UTF8Encoding)
  114. return new UTF8Encoding(false, true);
  115. return e;
  116. }
  117. catch (ArgumentException)
  118. {
  119. throw new UnsupportedCharsetException(name);
  120. }
  121. }
  122. public static ICollection<KeyValuePair<T, TU>> EntrySet<T, TU>(this IDictionary<T, TU> s)
  123. {
  124. return s;
  125. }
  126. public static bool AddItem<T>(this IList<T> list, T item)
  127. {
  128. list.Add(item);
  129. return true;
  130. }
  131. public static bool AddItem<T>(this ICollection<T> list, T item)
  132. {
  133. list.Add(item);
  134. return true;
  135. }
  136. public static TU Get<T, TU>(this IDictionary<T, TU> d, T key)
  137. {
  138. TU val;
  139. d.TryGetValue(key, out val);
  140. return val;
  141. }
  142. public static TU Put<T, TU>(this IDictionary<T, TU> d, T key, TU value)
  143. {
  144. TU old;
  145. d.TryGetValue(key, out old);
  146. d[key] = value;
  147. return old;
  148. }
  149. public static void PutAll<T, TU>(this IDictionary<T, TU> d, IDictionary<T, TU> values)
  150. {
  151. foreach (KeyValuePair<T, TU> val in values)
  152. d[val.Key] = val.Value;
  153. }
  154. public static CultureInfo GetEnglishCulture()
  155. {
  156. return new CultureInfo("en-US");
  157. }
  158. public static T GetFirst<T>(this IList<T> list)
  159. {
  160. return ((list.Count == 0) ? default(T) : list[0]);
  161. }
  162. public static CultureInfo GetGermanCulture()
  163. {
  164. CultureInfo r = new CultureInfo("de-DE");
  165. return r;
  166. }
  167. public static T GetLast<T>(this IList<T> list)
  168. {
  169. return ((list.Count == 0) ? default(T) : list[list.Count - 1]);
  170. }
  171. public static int GetOffset(this TimeZoneInfo tzone, long date)
  172. {
  173. return (int)tzone.GetUtcOffset(MillisToDateTimeOffset(date, 0).DateTime).TotalMilliseconds;
  174. }
  175. public static long GetTime(this DateTime dateTime)
  176. {
  177. return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch();
  178. }
  179. public static void InitCause(this Exception ex, Exception cause)
  180. {
  181. Console.WriteLine(cause);
  182. }
  183. public static bool IsEmpty<T>(this ICollection<T> col)
  184. {
  185. return (col.Count == 0);
  186. }
  187. public static bool IsEmpty<T>(this Stack<T> col)
  188. {
  189. return (col.Count == 0);
  190. }
  191. public static bool IsLower(this char c)
  192. {
  193. return char.IsLower(c);
  194. }
  195. public static bool IsUpper(this char c)
  196. {
  197. return char.IsUpper(c);
  198. }
  199. public static Iterator<T> Iterator<T>(this ICollection<T> col)
  200. {
  201. return new EnumeratorWrapper<T>(col, col.GetEnumerator());
  202. }
  203. public static Iterator<T> Iterator<T>(this IEnumerable<T> col)
  204. {
  205. return new EnumeratorWrapper<T>(col, col.GetEnumerator());
  206. }
  207. public static T Last<T>(this ICollection<T> col)
  208. {
  209. IList<T> list = col as IList<T>;
  210. if (list != null)
  211. {
  212. return list[list.Count - 1];
  213. }
  214. return col.Last();
  215. }
  216. public static int LowestOneBit(int val)
  217. {
  218. return (1 << NumberOfTrailingZeros(val));
  219. }
  220. public static bool Matches(this string str, string regex)
  221. {
  222. Regex regex2 = new Regex(regex);
  223. return regex2.IsMatch(str);
  224. }
  225. public static DateTime CreateDate(long milliSecondsSinceEpoch)
  226. {
  227. long num = EpochTicks + (milliSecondsSinceEpoch * 10000);
  228. return new DateTime(num);
  229. }
  230. public static DateTime CreateDateFromUTC(long milliSecondsSinceEpoch)
  231. {
  232. long num = EpochTicks + (milliSecondsSinceEpoch * 10000);
  233. return new DateTime(num, DateTimeKind.Utc);
  234. }
  235. public static DateTimeOffset MillisToDateTimeOffset(long milliSecondsSinceEpoch, long offsetMinutes)
  236. {
  237. TimeSpan offset = TimeSpan.FromMinutes(offsetMinutes);
  238. long num = EpochTicks + (milliSecondsSinceEpoch * 10000);
  239. return new DateTimeOffset(num + offset.Ticks, offset);
  240. }
  241. public static int NumberOfLeadingZeros(int val)
  242. {
  243. uint num = (uint)val;
  244. int count = 0;
  245. while ((num & 0x80000000) == 0)
  246. {
  247. num = num << 1;
  248. count++;
  249. }
  250. return count;
  251. }
  252. public static int NumberOfTrailingZeros(int val)
  253. {
  254. uint num = (uint)val;
  255. int count = 0;
  256. while ((num & 1) == 0)
  257. {
  258. num = num >> 1;
  259. count++;
  260. }
  261. return count;
  262. }
  263. public static int Read(this StreamReader reader, char[] data)
  264. {
  265. return reader.Read(data, 0, data.Length);
  266. }
  267. public static T Remove<T>(this IList<T> list, T item)
  268. {
  269. int index = list.IndexOf(item);
  270. if (index == -1)
  271. {
  272. return default(T);
  273. }
  274. T local = list[index];
  275. list.RemoveAt(index);
  276. return local;
  277. }
  278. public static T Remove<T>(this IList<T> list, int i)
  279. {
  280. T old;
  281. try
  282. {
  283. old = list[i];
  284. list.RemoveAt(i);
  285. }
  286. catch (IndexOutOfRangeException)
  287. {
  288. throw new NoSuchElementException();
  289. }
  290. return old;
  291. }
  292. public static T RemoveFirst<T>(this IList<T> list)
  293. {
  294. return list.Remove(0);
  295. }
  296. public static string ReplaceAll(this string str, string regex, string replacement)
  297. {
  298. Regex rgx = new Regex(regex);
  299. if (replacement.IndexOfAny(new[] { '\\', '$' }) != -1)
  300. {
  301. // Back references not yet supported
  302. StringBuilder sb = new StringBuilder();
  303. for (int n = 0; n < replacement.Length; n++)
  304. {
  305. char c = replacement[n];
  306. if (c == '$')
  307. throw new NotSupportedException("Back references not supported");
  308. if (c == '\\')
  309. c = replacement[++n];
  310. sb.Append(c);
  311. }
  312. replacement = sb.ToString();
  313. }
  314. return rgx.Replace(str, replacement);
  315. }
  316. public static bool RegionMatches(this string str, bool ignoreCase, int toOffset, string other, int ooffset, int len)
  317. {
  318. if (toOffset < 0 || ooffset < 0 || toOffset + len > str.Length || ooffset + len > other.Length)
  319. return false;
  320. return string.Compare(str, toOffset, other, ooffset, len) == 0;
  321. }
  322. public static T Set<T>(this IList<T> list, int index, T item)
  323. {
  324. T old = list[index];
  325. list[index] = item;
  326. return old;
  327. }
  328. public static int Signum(long val)
  329. {
  330. if (val < 0)
  331. {
  332. return -1;
  333. }
  334. if (val > 0)
  335. {
  336. return 1;
  337. }
  338. return 0;
  339. }
  340. public static void RemoveAll<T, TU>(this ICollection<T> col, ICollection<TU> items) where TU : T
  341. {
  342. foreach (var u in items)
  343. col.Remove(u);
  344. }
  345. public static bool ContainsAll<T, TU>(this ICollection<T> col, ICollection<TU> items) where TU : T
  346. {
  347. foreach (var u in items)
  348. if (!col.Any(n => (ReferenceEquals(n, u)) || n.Equals(u)))
  349. return false;
  350. return true;
  351. }
  352. public static bool Contains<T>(this ICollection<T> col, object item)
  353. {
  354. if (!(item is T))
  355. return false;
  356. return col.Any(n => (ReferenceEquals(n, item)) || n.Equals(item));
  357. }
  358. public static void Sort<T>(this IList<T> list)
  359. {
  360. List<T> sorted = new List<T>(list);
  361. sorted.Sort();
  362. for (int i = 0; i < list.Count; i++)
  363. {
  364. list[i] = sorted[i];
  365. }
  366. }
  367. public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
  368. {
  369. List<T> sorted = new List<T>(list);
  370. sorted.Sort(comparer);
  371. for (int i = 0; i < list.Count; i++)
  372. {
  373. list[i] = sorted[i];
  374. }
  375. }
  376. public static string[] Split(this string str, string regex)
  377. {
  378. return str.Split(regex, 0);
  379. }
  380. public static string[] Split(this string str, string regex, int limit)
  381. {
  382. Regex rgx = new Regex(regex);
  383. List<string> list = new List<string>();
  384. int startIndex = 0;
  385. if (limit != 1)
  386. {
  387. int nm = 1;
  388. foreach (Match match in rgx.Matches(str))
  389. {
  390. list.Add(str.Substring(startIndex, match.Index - startIndex));
  391. startIndex = match.Index + match.Length;
  392. if (limit > 0 && ++nm == limit)
  393. break;
  394. }
  395. }
  396. if (startIndex < str.Length)
  397. {
  398. list.Add(str.Substring(startIndex));
  399. }
  400. if (limit >= 0)
  401. {
  402. int count = list.Count - 1;
  403. while ((count >= 0) && (list[count].Length == 0))
  404. {
  405. count--;
  406. }
  407. list.RemoveRange(count + 1, (list.Count - count) - 1);
  408. }
  409. return list.ToArray();
  410. }
  411. public static IList<T> SubList<T>(this IList<T> list, int start, int len)
  412. {
  413. List<T> sublist = new List<T>(len);
  414. for (int i = start; i < (start + len); i++)
  415. {
  416. sublist.Add(list[i]);
  417. }
  418. return sublist;
  419. }
  420. public static char[] ToCharArray(this string str)
  421. {
  422. char[] destination = new char[str.Length];
  423. str.CopyTo(0, destination, 0, str.Length);
  424. return destination;
  425. }
  426. public static long ToMillisecondsSinceEpoch(this DateTime dateTime)
  427. {
  428. if (dateTime.Kind != DateTimeKind.Utc)
  429. {
  430. throw new ArgumentException("dateTime is expected to be expressed as a UTC DateTime", "dateTime");
  431. }
  432. return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch();
  433. }
  434. public static long ToMillisecondsSinceEpoch(this DateTimeOffset dateTimeOffset)
  435. {
  436. return (((dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks) - EpochTicks) / TimeSpan.TicksPerMillisecond);
  437. }
  438. public static string ToOctalString(int val)
  439. {
  440. return Convert.ToString(val, 8);
  441. }
  442. public static string ToHexString(int val)
  443. {
  444. return Convert.ToString(val, 16);
  445. }
  446. public static string ToString(object val)
  447. {
  448. return val.ToString();
  449. }
  450. public static string ToString(int val, int bas)
  451. {
  452. return Convert.ToString(val, bas);
  453. }
  454. public static IList<TU> UpcastTo<T, TU>(this IList<T> s) where T : TU
  455. {
  456. List<TU> list = new List<TU>(s.Count);
  457. for (int i = 0; i < s.Count; i++)
  458. {
  459. list.Add(s[i]);
  460. }
  461. return list;
  462. }
  463. public static ICollection<TU> UpcastTo<T, TU>(this ICollection<T> s) where T : TU
  464. {
  465. List<TU> list = new List<TU>(s.Count);
  466. foreach (var v in s)
  467. {
  468. list.Add(v);
  469. }
  470. return list;
  471. }
  472. public static T ValueOf<T>(T val)
  473. {
  474. return val;
  475. }
  476. //use? for NUnit-testing?
  477. //public static string GetTestName(object obj)
  478. //{
  479. // return GetTestName();
  480. //}
  481. //public static string GetTestName()
  482. //{
  483. // MethodBase met;
  484. // int n = 0;
  485. // do
  486. // {
  487. // met = new StackFrame(n).GetMethod();
  488. // if (met != null)
  489. // {
  490. // foreach (Attribute at in met.GetCustomAttributes(true))
  491. // {
  492. // if (at.GetType().FullName == "NUnit.Framework.TestAttribute")
  493. // {
  494. // // Convert back to camel case
  495. // string name = met.Name;
  496. // if (char.IsUpper(name[0]))
  497. // name = char.ToLower(name[0]) + name.Substring(1);
  498. // return name;
  499. // }
  500. // }
  501. // }
  502. // n++;
  503. // } while (met != null);
  504. // return "";
  505. //}
  506. public static string GetHostAddress(this IPAddress addr)
  507. {
  508. return addr.ToString();
  509. }
  510. public static IPAddress GetAddressByName(string host)
  511. {
  512. if (host == "0.0.0.0")
  513. {
  514. return IPAddress.Any;
  515. }
  516. try
  517. {
  518. return IPAddress.Parse(host);
  519. }
  520. catch (Exception ex)
  521. {
  522. return null;
  523. }
  524. }
  525. public static IPAddress[] GetAddressesByName(string host)
  526. {
  527. //IReadOnlyList<EndpointPair> data = null;
  528. //try
  529. //{
  530. // Task.Run(async () =>
  531. // {
  532. // data = await DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0");
  533. // }).Wait();
  534. //}
  535. //catch (Exception ex)
  536. //{
  537. // return null;
  538. //}
  539. //return data != null
  540. // ? data.Where(i => i.RemoteHostName.Type == HostNameType.Ipv4)
  541. // .GroupBy(i => i.RemoteHostName.DisplayName)
  542. // .Select(i => IPAddress.Parse(i.First().RemoteHostName.DisplayName))
  543. // .ToArray()
  544. // : null;
  545. //get v4-address only
  546. var entry = Task.Run(() => System.Net.Dns.GetHostEntryAsync(host))
  547. .GetAwaiter()
  548. .GetResult();
  549. return entry.AddressList
  550. .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork)
  551. .ToArray();
  552. }
  553. public static string GetImplementationVersion(this Assembly asm)
  554. {
  555. return asm.GetName().Version.ToString();
  556. }
  557. public static string GetHost(this Uri uri)
  558. {
  559. return string.IsNullOrEmpty(uri.Host) ? "" : uri.Host;
  560. }
  561. public static string GetUserInfo(this Uri uri)
  562. {
  563. return string.IsNullOrEmpty(uri.UserInfo) ? null : uri.UserInfo;
  564. }
  565. public static string GetQuery(this Uri uri)
  566. {
  567. return string.IsNullOrEmpty(uri.Query) ? null : uri.Query;
  568. }
  569. public static int GetLocalPort(this Socket socket)
  570. {
  571. return ((IPEndPoint)socket.LocalEndPoint).Port;
  572. }
  573. public static int GetPort(this Socket socket)
  574. {
  575. return ((IPEndPoint)socket.RemoteEndPoint).Port;
  576. }
  577. public static IPAddress GetInetAddress(this Socket socket)
  578. {
  579. return ((IPEndPoint)socket.RemoteEndPoint).Address;
  580. }
  581. /*public static bool RemoveElement(this ArrayList list, object elem)
  582. {
  583. int i = list.IndexOf(elem);
  584. if (i == -1)
  585. return false;
  586. list.RemoveAt(i);
  587. return true;
  588. }*/
  589. public static Semaphore CreateSemaphore(int count)
  590. {
  591. return new Semaphore(count, int.MaxValue);
  592. }
  593. }
  594. }