Extensions.cs 21 KB

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