Extensions.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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 InputStream GetResourceAsStream(this Type type, string name)
  176. {
  177. //Type.`Assembly` property deleted
  178. //string str2 = type.Assembly.GetName().Name + ".resources";
  179. string str2 = type.GetTypeInfo().Assembly.GetName().Name + ".resources";
  180. string[] textArray1 = { str2, ".", type.Namespace, ".", name };
  181. string str = string.Concat(textArray1);
  182. //Type.`Assembly` property deleted
  183. //Stream manifestResourceStream = type.Assembly.GetManifestResourceStream(str);
  184. Stream manifestResourceStream = type.GetTypeInfo().Assembly.GetManifestResourceStream(str);
  185. if (manifestResourceStream == null)
  186. {
  187. return null;
  188. }
  189. return InputStream.Wrap(manifestResourceStream);
  190. }
  191. public static long GetTime(this DateTime dateTime)
  192. {
  193. return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch();
  194. }
  195. public static void InitCause(this Exception ex, Exception cause)
  196. {
  197. Console.WriteLine(cause);
  198. }
  199. public static bool IsEmpty<T>(this ICollection<T> col)
  200. {
  201. return (col.Count == 0);
  202. }
  203. public static bool IsEmpty<T>(this Stack<T> col)
  204. {
  205. return (col.Count == 0);
  206. }
  207. public static bool IsLower(this char c)
  208. {
  209. return char.IsLower(c);
  210. }
  211. public static bool IsUpper(this char c)
  212. {
  213. return char.IsUpper(c);
  214. }
  215. public static Iterator<T> Iterator<T>(this ICollection<T> col)
  216. {
  217. return new EnumeratorWrapper<T>(col, col.GetEnumerator());
  218. }
  219. public static Iterator<T> Iterator<T>(this IEnumerable<T> col)
  220. {
  221. return new EnumeratorWrapper<T>(col, col.GetEnumerator());
  222. }
  223. public static T Last<T>(this ICollection<T> col)
  224. {
  225. IList<T> list = col as IList<T>;
  226. if (list != null)
  227. {
  228. return list[list.Count - 1];
  229. }
  230. return col.Last();
  231. }
  232. public static int LowestOneBit(int val)
  233. {
  234. return (1 << NumberOfTrailingZeros(val));
  235. }
  236. public static bool Matches(this string str, string regex)
  237. {
  238. Regex regex2 = new Regex(regex);
  239. return regex2.IsMatch(str);
  240. }
  241. public static DateTime CreateDate(long milliSecondsSinceEpoch)
  242. {
  243. long num = EpochTicks + (milliSecondsSinceEpoch * 10000);
  244. return new DateTime(num);
  245. }
  246. public static DateTime CreateDateFromUTC(long milliSecondsSinceEpoch)
  247. {
  248. long num = EpochTicks + (milliSecondsSinceEpoch * 10000);
  249. return new DateTime(num, DateTimeKind.Utc);
  250. }
  251. public static DateTimeOffset MillisToDateTimeOffset(long milliSecondsSinceEpoch, long offsetMinutes)
  252. {
  253. TimeSpan offset = TimeSpan.FromMinutes(offsetMinutes);
  254. long num = EpochTicks + (milliSecondsSinceEpoch * 10000);
  255. return new DateTimeOffset(num + offset.Ticks, offset);
  256. }
  257. public static int NumberOfLeadingZeros(int val)
  258. {
  259. uint num = (uint)val;
  260. int count = 0;
  261. while ((num & 0x80000000) == 0)
  262. {
  263. num = num << 1;
  264. count++;
  265. }
  266. return count;
  267. }
  268. public static int NumberOfTrailingZeros(int val)
  269. {
  270. uint num = (uint)val;
  271. int count = 0;
  272. while ((num & 1) == 0)
  273. {
  274. num = num >> 1;
  275. count++;
  276. }
  277. return count;
  278. }
  279. public static int Read(this StreamReader reader, char[] data)
  280. {
  281. return reader.Read(data, 0, data.Length);
  282. }
  283. public static T Remove<T>(this IList<T> list, T item)
  284. {
  285. int index = list.IndexOf(item);
  286. if (index == -1)
  287. {
  288. return default(T);
  289. }
  290. T local = list[index];
  291. list.RemoveAt(index);
  292. return local;
  293. }
  294. public static T Remove<T>(this IList<T> list, int i)
  295. {
  296. T old;
  297. try
  298. {
  299. old = list[i];
  300. list.RemoveAt(i);
  301. }
  302. catch (IndexOutOfRangeException)
  303. {
  304. throw new NoSuchElementException();
  305. }
  306. return old;
  307. }
  308. public static T RemoveFirst<T>(this IList<T> list)
  309. {
  310. return list.Remove(0);
  311. }
  312. public static string ReplaceAll(this string str, string regex, string replacement)
  313. {
  314. Regex rgx = new Regex(regex);
  315. if (replacement.IndexOfAny(new[] { '\\', '$' }) != -1)
  316. {
  317. // Back references not yet supported
  318. StringBuilder sb = new StringBuilder();
  319. for (int n = 0; n < replacement.Length; n++)
  320. {
  321. char c = replacement[n];
  322. if (c == '$')
  323. throw new NotSupportedException("Back references not supported");
  324. if (c == '\\')
  325. c = replacement[++n];
  326. sb.Append(c);
  327. }
  328. replacement = sb.ToString();
  329. }
  330. return rgx.Replace(str, replacement);
  331. }
  332. public static bool RegionMatches(this string str, bool ignoreCase, int toOffset, string other, int ooffset, int len)
  333. {
  334. if (toOffset < 0 || ooffset < 0 || toOffset + len > str.Length || ooffset + len > other.Length)
  335. return false;
  336. return string.Compare(str, toOffset, other, ooffset, len) == 0;
  337. }
  338. public static T Set<T>(this IList<T> list, int index, T item)
  339. {
  340. T old = list[index];
  341. list[index] = item;
  342. return old;
  343. }
  344. public static int Signum(long val)
  345. {
  346. if (val < 0)
  347. {
  348. return -1;
  349. }
  350. if (val > 0)
  351. {
  352. return 1;
  353. }
  354. return 0;
  355. }
  356. public static void RemoveAll<T, TU>(this ICollection<T> col, ICollection<TU> items) where TU : T
  357. {
  358. foreach (var u in items)
  359. col.Remove(u);
  360. }
  361. public static bool ContainsAll<T, TU>(this ICollection<T> col, ICollection<TU> items) where TU : T
  362. {
  363. foreach (var u in items)
  364. if (!col.Any(n => (ReferenceEquals(n, u)) || n.Equals(u)))
  365. return false;
  366. return true;
  367. }
  368. public static bool Contains<T>(this ICollection<T> col, object item)
  369. {
  370. if (!(item is T))
  371. return false;
  372. return col.Any(n => (ReferenceEquals(n, item)) || n.Equals(item));
  373. }
  374. public static void Sort<T>(this IList<T> list)
  375. {
  376. List<T> sorted = new List<T>(list);
  377. sorted.Sort();
  378. for (int i = 0; i < list.Count; i++)
  379. {
  380. list[i] = sorted[i];
  381. }
  382. }
  383. public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
  384. {
  385. List<T> sorted = new List<T>(list);
  386. sorted.Sort(comparer);
  387. for (int i = 0; i < list.Count; i++)
  388. {
  389. list[i] = sorted[i];
  390. }
  391. }
  392. public static string[] Split(this string str, string regex)
  393. {
  394. return str.Split(regex, 0);
  395. }
  396. public static string[] Split(this string str, string regex, int limit)
  397. {
  398. Regex rgx = new Regex(regex);
  399. List<string> list = new List<string>();
  400. int startIndex = 0;
  401. if (limit != 1)
  402. {
  403. int nm = 1;
  404. foreach (Match match in rgx.Matches(str))
  405. {
  406. list.Add(str.Substring(startIndex, match.Index - startIndex));
  407. startIndex = match.Index + match.Length;
  408. if (limit > 0 && ++nm == limit)
  409. break;
  410. }
  411. }
  412. if (startIndex < str.Length)
  413. {
  414. list.Add(str.Substring(startIndex));
  415. }
  416. if (limit >= 0)
  417. {
  418. int count = list.Count - 1;
  419. while ((count >= 0) && (list[count].Length == 0))
  420. {
  421. count--;
  422. }
  423. list.RemoveRange(count + 1, (list.Count - count) - 1);
  424. }
  425. return list.ToArray();
  426. }
  427. public static IList<T> SubList<T>(this IList<T> list, int start, int len)
  428. {
  429. List<T> sublist = new List<T>(len);
  430. for (int i = start; i < (start + len); i++)
  431. {
  432. sublist.Add(list[i]);
  433. }
  434. return sublist;
  435. }
  436. public static char[] ToCharArray(this string str)
  437. {
  438. char[] destination = new char[str.Length];
  439. str.CopyTo(0, destination, 0, str.Length);
  440. return destination;
  441. }
  442. public static long ToMillisecondsSinceEpoch(this DateTime dateTime)
  443. {
  444. if (dateTime.Kind != DateTimeKind.Utc)
  445. {
  446. throw new ArgumentException("dateTime is expected to be expressed as a UTC DateTime", "dateTime");
  447. }
  448. return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch();
  449. }
  450. public static long ToMillisecondsSinceEpoch(this DateTimeOffset dateTimeOffset)
  451. {
  452. return (((dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks) - EpochTicks) / TimeSpan.TicksPerMillisecond);
  453. }
  454. public static string ToOctalString(int val)
  455. {
  456. return Convert.ToString(val, 8);
  457. }
  458. public static string ToHexString(int val)
  459. {
  460. return Convert.ToString(val, 16);
  461. }
  462. public static string ToString(object val)
  463. {
  464. return val.ToString();
  465. }
  466. public static string ToString(int val, int bas)
  467. {
  468. return Convert.ToString(val, bas);
  469. }
  470. public static IList<TU> UpcastTo<T, TU>(this IList<T> s) where T : TU
  471. {
  472. List<TU> list = new List<TU>(s.Count);
  473. for (int i = 0; i < s.Count; i++)
  474. {
  475. list.Add(s[i]);
  476. }
  477. return list;
  478. }
  479. public static ICollection<TU> UpcastTo<T, TU>(this ICollection<T> s) where T : TU
  480. {
  481. List<TU> list = new List<TU>(s.Count);
  482. foreach (var v in s)
  483. {
  484. list.Add(v);
  485. }
  486. return list;
  487. }
  488. public static T ValueOf<T>(T val)
  489. {
  490. return val;
  491. }
  492. //use? for NUnit-testing?
  493. //public static string GetTestName(object obj)
  494. //{
  495. // return GetTestName();
  496. //}
  497. //public static string GetTestName()
  498. //{
  499. // MethodBase met;
  500. // int n = 0;
  501. // do
  502. // {
  503. // met = new StackFrame(n).GetMethod();
  504. // if (met != null)
  505. // {
  506. // foreach (Attribute at in met.GetCustomAttributes(true))
  507. // {
  508. // if (at.GetType().FullName == "NUnit.Framework.TestAttribute")
  509. // {
  510. // // Convert back to camel case
  511. // string name = met.Name;
  512. // if (char.IsUpper(name[0]))
  513. // name = char.ToLower(name[0]) + name.Substring(1);
  514. // return name;
  515. // }
  516. // }
  517. // }
  518. // n++;
  519. // } while (met != null);
  520. // return "";
  521. //}
  522. public static string GetHostAddress(this IPAddress addr)
  523. {
  524. return addr.ToString();
  525. }
  526. public static IPAddress GetAddressByName(string host)
  527. {
  528. if (host == "0.0.0.0")
  529. {
  530. return IPAddress.Any;
  531. }
  532. try
  533. {
  534. return IPAddress.Parse(host);
  535. }
  536. catch (Exception ex)
  537. {
  538. return null;
  539. }
  540. }
  541. public static IPAddress[] GetAddressesByName(string host)
  542. {
  543. //IReadOnlyList<EndpointPair> data = null;
  544. //try
  545. //{
  546. // Task.Run(async () =>
  547. // {
  548. // data = await DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0");
  549. // }).Wait();
  550. //}
  551. //catch (Exception ex)
  552. //{
  553. // return null;
  554. //}
  555. //return data != null
  556. // ? data.Where(i => i.RemoteHostName.Type == HostNameType.Ipv4)
  557. // .GroupBy(i => i.RemoteHostName.DisplayName)
  558. // .Select(i => IPAddress.Parse(i.First().RemoteHostName.DisplayName))
  559. // .ToArray()
  560. // : null;
  561. //get v4-address only
  562. var entry = Task.Run(() => System.Net.Dns.GetHostEntryAsync(host))
  563. .GetAwaiter()
  564. .GetResult();
  565. return entry.AddressList
  566. .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork)
  567. .ToArray();
  568. }
  569. public static string GetImplementationVersion(this Assembly asm)
  570. {
  571. return asm.GetName().Version.ToString();
  572. }
  573. public static string GetHost(this Uri uri)
  574. {
  575. return string.IsNullOrEmpty(uri.Host) ? "" : uri.Host;
  576. }
  577. public static string GetUserInfo(this Uri uri)
  578. {
  579. return string.IsNullOrEmpty(uri.UserInfo) ? null : uri.UserInfo;
  580. }
  581. public static string GetQuery(this Uri uri)
  582. {
  583. return string.IsNullOrEmpty(uri.Query) ? null : uri.Query;
  584. }
  585. public static int GetLocalPort(this Socket socket)
  586. {
  587. return ((IPEndPoint)socket.LocalEndPoint).Port;
  588. }
  589. public static int GetPort(this Socket socket)
  590. {
  591. return ((IPEndPoint)socket.RemoteEndPoint).Port;
  592. }
  593. public static IPAddress GetInetAddress(this Socket socket)
  594. {
  595. return ((IPEndPoint)socket.RemoteEndPoint).Address;
  596. }
  597. /*public static bool RemoveElement(this ArrayList list, object elem)
  598. {
  599. int i = list.IndexOf(elem);
  600. if (i == -1)
  601. return false;
  602. list.RemoveAt(i);
  603. return true;
  604. }*/
  605. public static Semaphore CreateSemaphore(int count)
  606. {
  607. return new Semaphore(count, int.MaxValue);
  608. }
  609. }
  610. }