Utils.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Security.Cryptography;
  6. using System.Globalization;
  7. using System.Runtime.InteropServices;
  8. using System.Collections;
  9. namespace CommonLang
  10. {
  11. public static class CUtils
  12. {
  13. public static readonly Encoding UTF8 = new UTF8Encoding(false, false);
  14. public static readonly Encoding UTF8_BOM = new UTF8Encoding(true, false);
  15. //本地时间戳,线程阻塞不是特别准确的,
  16. public static long localTimeMS = 0;
  17. public static long S_LOCAL_TIMESTAMPMS = 0; //本地时间戳
  18. public static long CurrentTimeMS
  19. {
  20. get { return System.DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; }
  21. }
  22. public static void Swap<T>(ref T a, ref T b)
  23. {
  24. T ta = a;
  25. a = b;
  26. b = ta;
  27. }
  28. public static IntPtr ToIntPtr(object obj)
  29. {
  30. if (obj == null)
  31. {
  32. return new IntPtr(0);
  33. }
  34. GCHandle hObject = GCHandle.Alloc(obj, GCHandleType.Pinned);
  35. IntPtr pObject = hObject.AddrOfPinnedObject();
  36. if (hObject.IsAllocated)
  37. hObject.Free();
  38. return pObject;
  39. }
  40. public static bool RandomPercent(Random random, float percent)
  41. {
  42. //大于等于 0.0 并且小于 1.0 的双精度浮点数。//
  43. if (random.NextDouble() * 100f < percent)
  44. {
  45. return true;
  46. }
  47. return false;
  48. }
  49. public static float RandomFactor(Random random, float value, float factor)
  50. {
  51. if (factor == 0)
  52. {
  53. return value;
  54. }
  55. return value + value * (float)(factor / 2f + random.NextDouble() * factor);
  56. }
  57. public static T RandomEnumValue<T>(Random random)
  58. {
  59. Array values = Enum.GetValues(typeof(T));
  60. int count = values.Length;
  61. if (count > 0)
  62. {
  63. var ret = values.GetValue(random.Next(0, count));
  64. return (T)ret;
  65. }
  66. return default(T);
  67. }
  68. #region CLONE
  69. public static T TryClone<T>(T src) where T : class, ICloneable
  70. {
  71. if (src == null) return null;
  72. return (T)src.Clone();
  73. }
  74. public static T[] CloneArray<T>(T[] src)
  75. where T : class, ICloneable
  76. {
  77. if (src == null) return null;
  78. T[] ret = new T[src.Length];
  79. for (int i = 0; i < src.Length; i++)
  80. {
  81. if (src[i] != null)
  82. {
  83. ret[i] = (T)src[i].Clone();
  84. }
  85. else
  86. {
  87. ret[i] = null;
  88. }
  89. }
  90. return ret;
  91. }
  92. public static List<T> CloneList<T>(IList<T> src)
  93. where T : class, ICloneable
  94. {
  95. if (src == null) return null;
  96. List<T> ret = new List<T>(src.Count);
  97. for (int i = 0; i < src.Count; i++)
  98. {
  99. if (src[i] != null)
  100. {
  101. ret.Add((T)src[i].Clone());
  102. }
  103. else
  104. {
  105. ret.Add(null);
  106. }
  107. }
  108. return ret;
  109. }
  110. public static Dictionary<K, V> CloneMap<K, V>(IDictionary<K, V> map)
  111. where V : ICloneable
  112. {
  113. if (map == null) return null;
  114. Dictionary<K, V> ret = new Dictionary<K, V>(map.Count);
  115. foreach (K k in map.Keys)
  116. {
  117. ret.Add(k, (V)ret[k].Clone());
  118. }
  119. return ret;
  120. }
  121. #endregion
  122. #region STRING
  123. public static string DecodeUTF8(byte[] data)
  124. {
  125. if (data.Length > 3)
  126. {
  127. if ((data[0] == 0xEF) && (data[1] == 0xBB) && (data[2] == 0xBF))
  128. {
  129. return UTF8_BOM.GetString(data);
  130. }
  131. }
  132. return UTF8.GetString(data);
  133. }
  134. public static string ToHexString(byte[] data)
  135. {
  136. StringBuilder sb = new StringBuilder();
  137. for (int i = 0; i < data.Length; i++)
  138. {
  139. byte d = data[i];
  140. sb.Append(d.ToString("x2"));
  141. }
  142. return sb.ToString();
  143. }
  144. public static string BinToHex(byte[] bin)
  145. {
  146. StringBuilder hexdata = new StringBuilder();
  147. for (int i = 0; i < bin.Length; i++)
  148. {
  149. string hex = bin[i].ToString("X2");
  150. if (hex.Length < 2)
  151. {
  152. hexdata.Append("0" + hex);
  153. }
  154. else if (hex.Length == 2)
  155. {
  156. hexdata.Append(hex);
  157. }
  158. }
  159. return hexdata.ToString();
  160. }
  161. public static byte[] HexToBin(string hex)
  162. {
  163. if (hex.Length % 2 != 0)
  164. {
  165. hex = "0" + hex;
  166. }
  167. int count = hex.Length;
  168. byte[] os = new byte[count / 2 + 1];
  169. for (int i = 0; i < count; i += 2)
  170. {
  171. string hch = hex.Substring(i, 2);
  172. byte read = byte.Parse(hch, NumberStyles.AllowHexSpecifier);
  173. os[i / 2] = read;
  174. }
  175. return os;
  176. }
  177. public static string ToBytesSizeString(long bytes)
  178. {
  179. long b = bytes;
  180. long kb = b >> 10;
  181. long mb = kb >> 10;
  182. long gb = mb >> 10;
  183. long tb = gb >> 10;
  184. if (tb > 10)
  185. {
  186. return tb + "." + gb % 1024 + "t";
  187. }
  188. if (gb > 10)
  189. {
  190. return gb + "." + mb % 1024 + "g";
  191. }
  192. if (mb > 10)
  193. {
  194. return mb + "." + kb % 1024 + "m";
  195. }
  196. if (kb > 10)
  197. {
  198. return kb + "." + b % 1024 + "k";
  199. }
  200. return b + "b";
  201. }
  202. public static string ListToString(IList list, string split = ", ", string prefix = "", string suffix = "")
  203. {
  204. StringBuilder sb = new StringBuilder();
  205. for (int i = 0; i < list.Count; i++)
  206. {
  207. object obj = list[i];
  208. sb.Append(prefix + obj);
  209. if (i < list.Count - 1)
  210. {
  211. sb.Append(split);
  212. }
  213. sb.Append(suffix);
  214. }
  215. return sb.ToString();
  216. }
  217. public static string MapToString(IDictionary list, string kv_split = "=", string line_split = "\n", string prefix = "", string suffix = "")
  218. {
  219. StringBuilder sb = new StringBuilder();
  220. int i = 0;
  221. foreach (object key in list.Keys)
  222. {
  223. object obj = list[key];
  224. sb.Append(prefix + key + kv_split + obj + suffix);
  225. if (i < list.Count - 1)
  226. {
  227. sb.Append(line_split);
  228. }
  229. i++;
  230. }
  231. return sb.ToString();
  232. }
  233. public static string ArrayToString(Array list, string split = ", ", string prefix = "", string suffix = "")
  234. {
  235. StringBuilder sb = new StringBuilder();
  236. for (int i = 0; i < list.Length; i++)
  237. {
  238. object obj = list.GetValue(i);
  239. sb.Append(prefix + obj);
  240. if (i < list.Length - 1)
  241. {
  242. sb.Append(split);
  243. }
  244. sb.Append(suffix);
  245. }
  246. return sb.ToString();
  247. }
  248. /// <summary>
  249. ///
  250. /// </summary>
  251. /// <param name="time"></param>
  252. /// <param name="format">YYMMDD_hhmmss</param>
  253. /// <returns></returns>
  254. public static string FormatTime(DateTime time, string format = "YYMMDD_hhmmss")
  255. {
  256. format = format.Replace("YY", time.Year.ToString("d4"));
  257. format = format.Replace("MM", time.Month.ToString("d2"));
  258. format = format.Replace("DD", time.Day.ToString("d2"));
  259. format = format.Replace("hh", time.Hour.ToString("d2"));
  260. format = format.Replace("mm", time.Minute.ToString("d2"));
  261. format = format.Replace("ss", time.Second.ToString("d2"));
  262. return format;
  263. }
  264. /// <summary>
  265. ///
  266. /// </summary>
  267. /// <param name="seconds"></param>
  268. /// <param name="format">hhmmss</param>
  269. /// <returns></returns>
  270. public static string FormatTime(int seconds, string format = "hh:mm:ss")
  271. {
  272. format = format.Replace("hh", (seconds / 60 / 60).ToString());
  273. format = format.Replace("mm", (seconds / 60 % 60).ToString("d2"));
  274. format = format.Replace("ss", (seconds % 60).ToString("d2"));
  275. return format;
  276. }
  277. #endregion
  278. #region ARRAY_AND_COLLECTIONS
  279. public static IList<T> RemoveAll<T>(IList<T> src, ICollection<T> list)
  280. {
  281. if (list.Count > 0)
  282. {
  283. for (int i = src.Count - 1; i >= 0; i--)
  284. {
  285. T e = src[i];
  286. if (e != null && list.Contains(e))
  287. {
  288. src.RemoveAt(i);
  289. }
  290. }
  291. }
  292. return src;
  293. }
  294. public static void RandomList<T>(Random random, IList<T> src)
  295. {
  296. for (int i = src.Count - 1; i >= 0; i--)
  297. {
  298. int r = random.Next(0, src.Count);
  299. T t = src[r];
  300. src[r] = src[i];
  301. src[i] = t;
  302. }
  303. }
  304. public static void RandomArray<T>(Random random, T[] src)
  305. {
  306. for (int i = src.Length - 1; i >= 0; i--)
  307. {
  308. int r = random.Next(0, src.Length);
  309. T t = src[r];
  310. src[r] = src[i];
  311. src[i] = t;
  312. }
  313. }
  314. public static T[] ArrayLink<T>(T[] a, params T[] b)
  315. {
  316. T[] dst = new T[a.Length + b.Length];
  317. Array.Copy(a, 0, dst, 0, a.Length);
  318. Array.Copy(b, 0, dst, a.Length, b.Length);
  319. return dst;
  320. }
  321. public static void ArrayCopy<T>(ICollection<T> src, Queue<T> dst)
  322. {
  323. foreach (T t in src)
  324. {
  325. dst.Enqueue(t);
  326. }
  327. }
  328. public static void ArrayCopy<T>(ICollection<T> src, ICollection<T> dst)
  329. {
  330. foreach (T t in src)
  331. {
  332. dst.Add(t);
  333. }
  334. }
  335. public static bool ArraysEqual<T>(T[] a1, T[] a2)
  336. {
  337. if (ReferenceEquals(a1, a2))
  338. return true;
  339. if (a1 == null || a2 == null)
  340. return false;
  341. if (a1.Length != a2.Length)
  342. return false;
  343. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  344. for (int i = 0; i < a1.Length; i++)
  345. {
  346. if (!comparer.Equals(a1[i], a2[i])) return false;
  347. }
  348. return true;
  349. }
  350. public static T GetRandomInArray<T>(IList<T> list, Random random)
  351. {
  352. if (list.Count == 0) return default(T);
  353. int rd = random.Next(list.Count);
  354. return list[rd];
  355. }
  356. public static T GetRandomInArray<T>(T[] list, Random random)
  357. {
  358. if (list.Length == 0) return default(T);
  359. int rd = random.Next(list.Length);
  360. return list[rd];
  361. }
  362. public static int[] GetArrayRanges(Array array)
  363. {
  364. Type type = array.GetType();
  365. int rank = type.GetArrayRank();
  366. int[] ranges = new int[rank];
  367. for (int i = 0; i < rank; i++)
  368. {
  369. ranges[i] = array.GetLength(i);
  370. }
  371. return ranges;
  372. }
  373. public static int[] GetArrayRankIndex(int[] ranks, int total_index)
  374. {
  375. int[] ret = new int[ranks.Length];
  376. if (ranks.Length == 1)
  377. {
  378. ret[0] = total_index;
  379. return ret;
  380. }
  381. if (ranks.Length == 2)
  382. {
  383. ret[0] = total_index / ranks[1];
  384. ret[1] = total_index % ranks[1];
  385. return ret;
  386. }
  387. if (ranks.Length == 3)
  388. {
  389. ret[0] = total_index / ranks[2] / ranks[1];
  390. ret[1] = total_index / ranks[2] % ranks[1];
  391. ret[2] = total_index % ranks[2];
  392. return ret;
  393. }
  394. if (ranks.Length == 4)
  395. {
  396. ret[0] = total_index / ranks[3] / ranks[2] / ranks[1];
  397. ret[1] = total_index / ranks[3] / ranks[2] % ranks[1];
  398. ret[2] = total_index / ranks[3] % ranks[2];
  399. ret[3] = total_index % ranks[3];
  400. return ret;
  401. }
  402. return GetArrayIndex(ranks, total_index);
  403. }
  404. public static int GetArrayTotalIndex(int[] ranks, params int[] indices)
  405. {
  406. int total_index = 0;
  407. if (ranks.Length == 1)
  408. {
  409. total_index = indices[0];
  410. return total_index;
  411. }
  412. if (ranks.Length == 2)
  413. {
  414. total_index += indices[0] * ranks[1];
  415. total_index += indices[1];
  416. return total_index;
  417. }
  418. if (ranks.Length == 3)
  419. {
  420. total_index += indices[0] * ranks[2] * ranks[1];
  421. total_index += indices[1] * ranks[2];
  422. total_index += indices[2];
  423. return total_index;
  424. }
  425. if (ranks.Length == 4)
  426. {
  427. total_index += indices[0] * ranks[3] * ranks[2] * ranks[1];
  428. total_index += indices[1] * ranks[3] * ranks[2];
  429. total_index += indices[2] * ranks[3];
  430. total_index += indices[3];
  431. return total_index;
  432. }
  433. return GetArrayIndex(ranks, indices);
  434. }
  435. private static int[] GetArrayIndex(int[] arrayStruct, int index)
  436. {
  437. int[] valueArray = new int[arrayStruct.Length];
  438. int[] tempArray = new int[arrayStruct.Length];
  439. int[] outIndex = new int[arrayStruct.Length];
  440. valueArray[arrayStruct.Length - 1] = 1;
  441. for (int i = arrayStruct.Length - 1 - 1; i >= 0; --i)
  442. {
  443. valueArray[i] = arrayStruct[i + 1] * valueArray[i + 1];
  444. }
  445. if (index < 0 || index > valueArray[0] * arrayStruct[0])
  446. throw new Exception(" Array Out of index " + index);
  447. outIndex[0] = index / valueArray[0];
  448. tempArray[0] = outIndex[0] * valueArray[0];
  449. for (int i = 1; i < arrayStruct.Length; ++i)
  450. {
  451. outIndex[i] = (index - tempArray[i - 1]) / valueArray[i];
  452. tempArray[i] = tempArray[i - 1] + outIndex[i] * valueArray[i];
  453. }
  454. return outIndex;
  455. }
  456. private static int GetArrayIndex(int[] arrayStruct, int[] arrayIndex)
  457. {
  458. int index = 0;
  459. int[] valueArray = new int[arrayStruct.Length];
  460. valueArray[arrayStruct.Length - 1] = 1;
  461. for (int i = arrayStruct.Length - 1 - 1; i >= 0; --i)
  462. {
  463. valueArray[i] = arrayStruct[i + 1] * valueArray[i + 1];
  464. }
  465. for (int i = 0; i < arrayStruct.Length; ++i)
  466. {
  467. index += valueArray[i] * arrayIndex[i];
  468. }
  469. return index;
  470. }
  471. public static T GetMinOrMax<T>(T[] array, int index)
  472. {
  473. if (array.Length > 0)
  474. {
  475. if (index < 0)
  476. {
  477. return array[0];
  478. }
  479. if (index >= array.Length)
  480. {
  481. return array[array.Length - 1];
  482. }
  483. return array[index];
  484. }
  485. return default(T);
  486. }
  487. public static T GetMinOrMax<T>(IList<T> array, int index)
  488. {
  489. if (array.Count > 0)
  490. {
  491. if (index < 0)
  492. {
  493. return array[0];
  494. }
  495. if (index >= array.Count)
  496. {
  497. return array[array.Count - 1];
  498. }
  499. return array[index];
  500. }
  501. return default(T);
  502. }
  503. public delegate bool TestRemove<T>(T data);
  504. public static void RemoveAll<T>(LinkedList<T> list, TestRemove<T> test)
  505. {
  506. if (list.Count > 0)
  507. {
  508. List<LinkedListNode<T>> removed = null;
  509. for (LinkedListNode<T> it = list.Last; it != null; it = it.Previous)
  510. {
  511. T t = it.Value;
  512. if (test(t))
  513. {
  514. if (removed == null)
  515. {
  516. removed = new List<LinkedListNode<T>>(2);
  517. }
  518. removed.Add(it);
  519. }
  520. }
  521. if (removed != null)
  522. {
  523. foreach (LinkedListNode<T> it in removed)
  524. {
  525. list.Remove(it);
  526. }
  527. }
  528. }
  529. }
  530. public static void RemoveAll<T>(ICollection<T> list, TestRemove<T> test)
  531. {
  532. if (list.Count > 0)
  533. {
  534. List<T> removed = null;
  535. foreach (T t in list)
  536. {
  537. if (test(t))
  538. {
  539. if (removed == null)
  540. {
  541. removed = new List<T>(2);
  542. }
  543. removed.Add(t);
  544. }
  545. }
  546. if (removed != null)
  547. {
  548. for (int i = removed.Count - 1; i >= 0; --i)
  549. {
  550. list.Remove(removed[i]);
  551. }
  552. }
  553. }
  554. }
  555. public static void RemoveAll<T>(IList<T> list, TestRemove<T> test)
  556. {
  557. if (list.Count > 0)
  558. {
  559. List<T> removed = null;
  560. for (int i = list.Count - 1; i >= 0; --i)
  561. {
  562. T t = list[i];
  563. if (test(t))
  564. {
  565. if (removed == null)
  566. {
  567. removed = new List<T>(2);
  568. }
  569. removed.Add(t);
  570. }
  571. }
  572. if (removed != null)
  573. {
  574. for (int i = removed.Count - 1; i >= 0; --i)
  575. {
  576. list.Remove(removed[i]);
  577. }
  578. }
  579. }
  580. }
  581. public static List<T> ToGenericList<T>(IEnumerable list, int capacity = 0)
  582. {
  583. List<T> ret = (capacity > 0) ? new List<T>(capacity) : new List<T>();
  584. foreach (object obj in list)
  585. {
  586. ret.Add((T)obj);
  587. }
  588. return ret;
  589. }
  590. public static void SetListSize<T>(List<T> list, int length)
  591. {
  592. int d = length - list.Count;
  593. if (d < 0)
  594. {
  595. list.RemoveRange(length, -d);
  596. }
  597. else if (d > 0)
  598. {
  599. for (int i = 0; i < d; i++)
  600. {
  601. list.Add(default(T));
  602. }
  603. }
  604. }
  605. public static void SwapInList<T>(List<T> list, int i, int j)
  606. {
  607. T oi = list[i];
  608. list[i] = list[j];
  609. list[j] = oi;
  610. }
  611. public static void SwapInArray<T>(T[] array, int i, int j)
  612. {
  613. T oi = array[i];
  614. array[i] = array[j];
  615. array[j] = oi;
  616. }
  617. /** 转换成整数 */
  618. public static int CastInt(float value)
  619. {
  620. if(value < 0)
  621. {
  622. return (int)(value - 0.5);
  623. }
  624. return (int)(value + 0.5);
  625. }
  626. public static int CastInt(double value)
  627. {
  628. if (value < 0)
  629. {
  630. return (int)(value - 0.5);
  631. }
  632. return (int)(value + 0.5);
  633. }
  634. #endregion
  635. }
  636. }