Ext.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Model.Services;
  9. using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
  10. using WebSocketState = System.Net.WebSockets.WebSocketState;
  11. namespace SocketHttpListener
  12. {
  13. /// <summary>
  14. /// Provides a set of static methods for the websocket-sharp.
  15. /// </summary>
  16. public static class Ext
  17. {
  18. #region Private Const Fields
  19. private const string _tspecials = "()<>@,;:\\\"/[]?={} \t";
  20. #endregion
  21. #region Private Methods
  22. private static MemoryStream compress(this Stream stream)
  23. {
  24. var output = new MemoryStream();
  25. if (stream.Length == 0)
  26. return output;
  27. stream.Position = 0;
  28. using (var ds = new DeflateStream(output, CompressionMode.Compress, true))
  29. {
  30. stream.CopyTo(ds);
  31. //ds.Close(); // "BFINAL" set to 1.
  32. output.Position = 0;
  33. return output;
  34. }
  35. }
  36. private static byte[] decompress(this byte[] value)
  37. {
  38. if (value.Length == 0)
  39. return value;
  40. using (var input = new MemoryStream(value))
  41. {
  42. return input.decompressToArray();
  43. }
  44. }
  45. private static MemoryStream decompress(this Stream stream)
  46. {
  47. var output = new MemoryStream();
  48. if (stream.Length == 0)
  49. return output;
  50. stream.Position = 0;
  51. using (var ds = new DeflateStream(stream, CompressionMode.Decompress, true))
  52. {
  53. ds.CopyTo(output, true);
  54. return output;
  55. }
  56. }
  57. private static byte[] decompressToArray(this Stream stream)
  58. {
  59. using (var decomp = stream.decompress())
  60. {
  61. return decomp.ToArray();
  62. }
  63. }
  64. private static async Task<byte[]> ReadBytesAsync(this Stream stream, byte[] buffer, int offset, int length)
  65. {
  66. var len = await stream.ReadAsync(buffer, offset, length).ConfigureAwait(false);
  67. if (len < 1)
  68. return buffer.SubArray(0, offset);
  69. var tmp = 0;
  70. while (len < length)
  71. {
  72. tmp = await stream.ReadAsync(buffer, offset + len, length - len).ConfigureAwait(false);
  73. if (tmp < 1)
  74. {
  75. break;
  76. }
  77. len += tmp;
  78. }
  79. return len < length
  80. ? buffer.SubArray(0, offset + len)
  81. : buffer;
  82. }
  83. private static async Task<bool> ReadBytesAsync(this Stream stream, byte[] buffer, int offset, int length, Stream dest)
  84. {
  85. var bytes = await stream.ReadBytesAsync(buffer, offset, length).ConfigureAwait(false);
  86. var len = bytes.Length;
  87. dest.Write(bytes, 0, len);
  88. return len == offset + length;
  89. }
  90. #endregion
  91. #region Internal Methods
  92. internal static async Task<byte[]> AppendAsync(this ushort code, string reason)
  93. {
  94. using (var buffer = new MemoryStream())
  95. {
  96. var tmp = code.ToByteArrayInternally(ByteOrder.Big);
  97. await buffer.WriteAsync(tmp, 0, 2).ConfigureAwait(false);
  98. if (reason != null && reason.Length > 0)
  99. {
  100. tmp = Encoding.UTF8.GetBytes(reason);
  101. await buffer.WriteAsync(tmp, 0, tmp.Length).ConfigureAwait(false);
  102. }
  103. return buffer.ToArray();
  104. }
  105. }
  106. internal static string CheckIfClosable(this WebSocketState state)
  107. {
  108. return state == WebSocketState.CloseSent
  109. ? "While closing the WebSocket connection."
  110. : state == WebSocketState.Closed
  111. ? "The WebSocket connection has already been closed."
  112. : null;
  113. }
  114. internal static string CheckIfOpen(this WebSocketState state)
  115. {
  116. return state == WebSocketState.Connecting
  117. ? "A WebSocket connection isn't established."
  118. : state == WebSocketState.CloseSent
  119. ? "While closing the WebSocket connection."
  120. : state == WebSocketState.Closed
  121. ? "The WebSocket connection has already been closed."
  122. : null;
  123. }
  124. internal static string CheckIfValidControlData(this byte[] data, string paramName)
  125. {
  126. return data.Length > 125
  127. ? string.Format("'{0}' length must be less.", paramName)
  128. : null;
  129. }
  130. internal static Stream Compress(this Stream stream, CompressionMethod method)
  131. {
  132. return method == CompressionMethod.Deflate
  133. ? stream.compress()
  134. : stream;
  135. }
  136. internal static bool Contains<T>(this IEnumerable<T> source, Func<T, bool> condition)
  137. {
  138. foreach (T elm in source)
  139. if (condition(elm))
  140. return true;
  141. return false;
  142. }
  143. internal static void CopyTo(this Stream src, Stream dest, bool setDefaultPosition)
  144. {
  145. var readLen = 0;
  146. var bufferLen = 256;
  147. var buffer = new byte[bufferLen];
  148. while ((readLen = src.Read(buffer, 0, bufferLen)) > 0)
  149. {
  150. dest.Write(buffer, 0, readLen);
  151. }
  152. if (setDefaultPosition)
  153. dest.Position = 0;
  154. }
  155. internal static byte[] Decompress(this byte[] value, CompressionMethod method)
  156. {
  157. return method == CompressionMethod.Deflate
  158. ? value.decompress()
  159. : value;
  160. }
  161. internal static byte[] DecompressToArray(this Stream stream, CompressionMethod method)
  162. {
  163. return method == CompressionMethod.Deflate
  164. ? stream.decompressToArray()
  165. : stream.ToByteArray();
  166. }
  167. /// <summary>
  168. /// Determines whether the specified <see cref="int"/> equals the specified <see cref="char"/>,
  169. /// and invokes the specified Action&lt;int&gt; delegate at the same time.
  170. /// </summary>
  171. /// <returns>
  172. /// <c>true</c> if <paramref name="value"/> equals <paramref name="c"/>;
  173. /// otherwise, <c>false</c>.
  174. /// </returns>
  175. /// <param name="value">
  176. /// An <see cref="int"/> to compare.
  177. /// </param>
  178. /// <param name="c">
  179. /// A <see cref="char"/> to compare.
  180. /// </param>
  181. /// <param name="action">
  182. /// An Action&lt;int&gt; delegate that references the method(s) called at
  183. /// the same time as comparing. An <see cref="int"/> parameter to pass to
  184. /// the method(s) is <paramref name="value"/>.
  185. /// </param>
  186. /// <exception cref="ArgumentOutOfRangeException">
  187. /// <paramref name="value"/> isn't between 0 and 255.
  188. /// </exception>
  189. internal static bool EqualsWith(this int value, char c, Action<int> action)
  190. {
  191. if (value < 0 || value > 255)
  192. throw new ArgumentOutOfRangeException(nameof(value));
  193. action(value);
  194. return value == c - 0;
  195. }
  196. internal static string GetMessage(this CloseStatusCode code)
  197. {
  198. return code == CloseStatusCode.ProtocolError
  199. ? "A WebSocket protocol error has occurred."
  200. : code == CloseStatusCode.IncorrectData
  201. ? "An incorrect data has been received."
  202. : code == CloseStatusCode.Abnormal
  203. ? "An exception has occurred."
  204. : code == CloseStatusCode.InconsistentData
  205. ? "An inconsistent data has been received."
  206. : code == CloseStatusCode.PolicyViolation
  207. ? "A policy violation has occurred."
  208. : code == CloseStatusCode.TooBig
  209. ? "A too big data has been received."
  210. : code == CloseStatusCode.IgnoreExtension
  211. ? "WebSocket client did not receive expected extension(s)."
  212. : code == CloseStatusCode.ServerError
  213. ? "WebSocket server got an internal error."
  214. : code == CloseStatusCode.TlsHandshakeFailure
  215. ? "An error has occurred while handshaking."
  216. : string.Empty;
  217. }
  218. internal static string GetNameInternal(this string nameAndValue, string separator)
  219. {
  220. var i = nameAndValue.IndexOf(separator);
  221. return i > 0
  222. ? nameAndValue.Substring(0, i).Trim()
  223. : null;
  224. }
  225. internal static string GetValueInternal(this string nameAndValue, string separator)
  226. {
  227. var i = nameAndValue.IndexOf(separator);
  228. return i >= 0 && i < nameAndValue.Length - 1
  229. ? nameAndValue.Substring(i + 1).Trim()
  230. : null;
  231. }
  232. internal static bool IsCompressionExtension(this string value, CompressionMethod method)
  233. {
  234. return value.StartsWith(method.ToExtensionString());
  235. }
  236. internal static bool IsPortNumber(this int value)
  237. {
  238. return value > 0 && value < 65536;
  239. }
  240. internal static bool IsReserved(this ushort code)
  241. {
  242. return code == (ushort)CloseStatusCode.Undefined ||
  243. code == (ushort)CloseStatusCode.NoStatusCode ||
  244. code == (ushort)CloseStatusCode.Abnormal ||
  245. code == (ushort)CloseStatusCode.TlsHandshakeFailure;
  246. }
  247. internal static bool IsReserved(this CloseStatusCode code)
  248. {
  249. return code == CloseStatusCode.Undefined ||
  250. code == CloseStatusCode.NoStatusCode ||
  251. code == CloseStatusCode.Abnormal ||
  252. code == CloseStatusCode.TlsHandshakeFailure;
  253. }
  254. internal static bool IsText(this string value)
  255. {
  256. var len = value.Length;
  257. for (var i = 0; i < len; i++)
  258. {
  259. char c = value[i];
  260. if (c < 0x20 && !"\r\n\t".Contains(c))
  261. return false;
  262. if (c == 0x7f)
  263. return false;
  264. if (c == '\n' && ++i < len)
  265. {
  266. c = value[i];
  267. if (!" \t".Contains(c))
  268. return false;
  269. }
  270. }
  271. return true;
  272. }
  273. internal static bool IsToken(this string value)
  274. {
  275. foreach (char c in value)
  276. if (c < 0x20 || c >= 0x7f || _tspecials.Contains(c))
  277. return false;
  278. return true;
  279. }
  280. internal static string Quote(this string value)
  281. {
  282. return value.IsToken()
  283. ? value
  284. : string.Format("\"{0}\"", value.Replace("\"", "\\\""));
  285. }
  286. internal static Task<byte[]> ReadBytesAsync(this Stream stream, int length)
  287. => stream.ReadBytesAsync(new byte[length], 0, length);
  288. internal static async Task<byte[]> ReadBytesAsync(this Stream stream, long length, int bufferLength)
  289. {
  290. using (var result = new MemoryStream())
  291. {
  292. var count = length / bufferLength;
  293. var rem = (int)(length % bufferLength);
  294. var buffer = new byte[bufferLength];
  295. var end = false;
  296. for (long i = 0; i < count; i++)
  297. {
  298. if (!await stream.ReadBytesAsync(buffer, 0, bufferLength, result).ConfigureAwait(false))
  299. {
  300. end = true;
  301. break;
  302. }
  303. }
  304. if (!end && rem > 0)
  305. {
  306. await stream.ReadBytesAsync(new byte[rem], 0, rem, result).ConfigureAwait(false);
  307. }
  308. return result.ToArray();
  309. }
  310. }
  311. internal static string RemovePrefix(this string value, params string[] prefixes)
  312. {
  313. var i = 0;
  314. foreach (var prefix in prefixes)
  315. {
  316. if (value.StartsWith(prefix))
  317. {
  318. i = prefix.Length;
  319. break;
  320. }
  321. }
  322. return i > 0
  323. ? value.Substring(i)
  324. : value;
  325. }
  326. internal static T[] Reverse<T>(this T[] array)
  327. {
  328. var len = array.Length;
  329. T[] reverse = new T[len];
  330. var end = len - 1;
  331. for (var i = 0; i <= end; i++)
  332. reverse[i] = array[end - i];
  333. return reverse;
  334. }
  335. internal static IEnumerable<string> SplitHeaderValue(
  336. this string value, params char[] separator)
  337. {
  338. var len = value.Length;
  339. var separators = new string(separator);
  340. var buffer = new StringBuilder(32);
  341. var quoted = false;
  342. var escaped = false;
  343. char c;
  344. for (var i = 0; i < len; i++)
  345. {
  346. c = value[i];
  347. if (c == '"')
  348. {
  349. if (escaped)
  350. escaped = !escaped;
  351. else
  352. quoted = !quoted;
  353. }
  354. else if (c == '\\')
  355. {
  356. if (i < len - 1 && value[i + 1] == '"')
  357. escaped = true;
  358. }
  359. else if (separators.Contains(c))
  360. {
  361. if (!quoted)
  362. {
  363. yield return buffer.ToString();
  364. buffer.Length = 0;
  365. continue;
  366. }
  367. }
  368. else
  369. {
  370. }
  371. buffer.Append(c);
  372. }
  373. if (buffer.Length > 0)
  374. yield return buffer.ToString();
  375. }
  376. internal static byte[] ToByteArray(this Stream stream)
  377. {
  378. using (var output = new MemoryStream())
  379. {
  380. stream.Position = 0;
  381. stream.CopyTo(output);
  382. return output.ToArray();
  383. }
  384. }
  385. internal static byte[] ToByteArrayInternally(this ushort value, ByteOrder order)
  386. {
  387. var bytes = BitConverter.GetBytes(value);
  388. if (!order.IsHostOrder())
  389. Array.Reverse(bytes);
  390. return bytes;
  391. }
  392. internal static byte[] ToByteArrayInternally(this ulong value, ByteOrder order)
  393. {
  394. var bytes = BitConverter.GetBytes(value);
  395. if (!order.IsHostOrder())
  396. Array.Reverse(bytes);
  397. return bytes;
  398. }
  399. internal static string ToExtensionString(
  400. this CompressionMethod method, params string[] parameters)
  401. {
  402. if (method == CompressionMethod.None)
  403. return string.Empty;
  404. var m = string.Format("permessage-{0}", method.ToString().ToLowerInvariant());
  405. if (parameters == null || parameters.Length == 0)
  406. return m;
  407. return string.Format("{0}; {1}", m, parameters.ToString("; "));
  408. }
  409. internal static ushort ToUInt16(this byte[] src, ByteOrder srcOrder)
  410. {
  411. src.ToHostOrder(srcOrder);
  412. return BitConverter.ToUInt16(src, 0);
  413. }
  414. internal static ulong ToUInt64(this byte[] src, ByteOrder srcOrder)
  415. {
  416. src.ToHostOrder(srcOrder);
  417. return BitConverter.ToUInt64(src, 0);
  418. }
  419. internal static string TrimEndSlash(this string value)
  420. {
  421. value = value.TrimEnd('/');
  422. return value.Length > 0
  423. ? value
  424. : "/";
  425. }
  426. internal static string Unquote(this string value)
  427. {
  428. var start = value.IndexOf('\"');
  429. var end = value.LastIndexOf('\"');
  430. if (start < end)
  431. value = value.Substring(start + 1, end - start - 1).Replace("\\\"", "\"");
  432. return value.Trim();
  433. }
  434. internal static void WriteBytes(this Stream stream, byte[] value)
  435. {
  436. using (var src = new MemoryStream(value))
  437. {
  438. src.CopyTo(stream);
  439. }
  440. }
  441. #endregion
  442. #region Public Methods
  443. /// <summary>
  444. /// Determines whether the specified <see cref="string"/> contains any of characters
  445. /// in the specified array of <see cref="char"/>.
  446. /// </summary>
  447. /// <returns>
  448. /// <c>true</c> if <paramref name="value"/> contains any of <paramref name="chars"/>;
  449. /// otherwise, <c>false</c>.
  450. /// </returns>
  451. /// <param name="value">
  452. /// A <see cref="string"/> to test.
  453. /// </param>
  454. /// <param name="chars">
  455. /// An array of <see cref="char"/> that contains characters to find.
  456. /// </param>
  457. public static bool Contains(this string value, params char[] chars)
  458. {
  459. return chars == null || chars.Length == 0
  460. ? true
  461. : value == null || value.Length == 0
  462. ? false
  463. : value.IndexOfAny(chars) != -1;
  464. }
  465. /// <summary>
  466. /// Determines whether the specified <see cref="QueryParamCollection"/> contains the entry
  467. /// with the specified <paramref name="name"/>.
  468. /// </summary>
  469. /// <returns>
  470. /// <c>true</c> if <paramref name="collection"/> contains the entry
  471. /// with <paramref name="name"/>; otherwise, <c>false</c>.
  472. /// </returns>
  473. /// <param name="collection">
  474. /// A <see cref="QueryParamCollection"/> to test.
  475. /// </param>
  476. /// <param name="name">
  477. /// A <see cref="string"/> that represents the key of the entry to find.
  478. /// </param>
  479. public static bool Contains(this QueryParamCollection collection, string name)
  480. {
  481. return collection == null || collection.Count == 0
  482. ? false
  483. : collection[name] != null;
  484. }
  485. /// <summary>
  486. /// Determines whether the specified <see cref="QueryParamCollection"/> contains the entry
  487. /// with the specified both <paramref name="name"/> and <paramref name="value"/>.
  488. /// </summary>
  489. /// <returns>
  490. /// <c>true</c> if <paramref name="collection"/> contains the entry
  491. /// with both <paramref name="name"/> and <paramref name="value"/>;
  492. /// otherwise, <c>false</c>.
  493. /// </returns>
  494. /// <param name="collection">
  495. /// A <see cref="QueryParamCollection"/> to test.
  496. /// </param>
  497. /// <param name="name">
  498. /// A <see cref="string"/> that represents the key of the entry to find.
  499. /// </param>
  500. /// <param name="value">
  501. /// A <see cref="string"/> that represents the value of the entry to find.
  502. /// </param>
  503. public static bool Contains(this QueryParamCollection collection, string name, string value)
  504. {
  505. if (collection == null || collection.Count == 0)
  506. return false;
  507. var values = collection[name];
  508. if (values == null)
  509. return false;
  510. foreach (var v in values.Split(','))
  511. if (v.Trim().Equals(value, StringComparison.OrdinalIgnoreCase))
  512. return true;
  513. return false;
  514. }
  515. /// <summary>
  516. /// Emits the specified <c>EventHandler&lt;TEventArgs&gt;</c> delegate
  517. /// if it isn't <see langword="null"/>.
  518. /// </summary>
  519. /// <param name="eventHandler">
  520. /// An <c>EventHandler&lt;TEventArgs&gt;</c> to emit.
  521. /// </param>
  522. /// <param name="sender">
  523. /// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>.
  524. /// </param>
  525. /// <param name="e">
  526. /// A <c>TEventArgs</c> that represents the event data.
  527. /// </param>
  528. /// <typeparam name="TEventArgs">
  529. /// The type of the event data generated by the event.
  530. /// </typeparam>
  531. public static void Emit<TEventArgs>(
  532. this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e)
  533. where TEventArgs : EventArgs
  534. {
  535. if (eventHandler != null)
  536. eventHandler(sender, e);
  537. }
  538. /// <summary>
  539. /// Gets the description of the specified HTTP status <paramref name="code"/>.
  540. /// </summary>
  541. /// <returns>
  542. /// A <see cref="string"/> that represents the description of the HTTP status code.
  543. /// </returns>
  544. /// <param name="code">
  545. /// One of <see cref="HttpStatusCode"/> enum values, indicates the HTTP status codes.
  546. /// </param>
  547. public static string GetDescription(this HttpStatusCode code)
  548. {
  549. return ((int)code).GetStatusDescription();
  550. }
  551. /// <summary>
  552. /// Gets the description of the specified HTTP status <paramref name="code"/>.
  553. /// </summary>
  554. /// <returns>
  555. /// A <see cref="string"/> that represents the description of the HTTP status code.
  556. /// </returns>
  557. /// <param name="code">
  558. /// An <see cref="int"/> that represents the HTTP status code.
  559. /// </param>
  560. public static string GetStatusDescription(this int code)
  561. {
  562. switch (code)
  563. {
  564. case 100: return "Continue";
  565. case 101: return "Switching Protocols";
  566. case 102: return "Processing";
  567. case 200: return "OK";
  568. case 201: return "Created";
  569. case 202: return "Accepted";
  570. case 203: return "Non-Authoritative Information";
  571. case 204: return "No Content";
  572. case 205: return "Reset Content";
  573. case 206: return "Partial Content";
  574. case 207: return "Multi-Status";
  575. case 300: return "Multiple Choices";
  576. case 301: return "Moved Permanently";
  577. case 302: return "Found";
  578. case 303: return "See Other";
  579. case 304: return "Not Modified";
  580. case 305: return "Use Proxy";
  581. case 307: return "Temporary Redirect";
  582. case 400: return "Bad Request";
  583. case 401: return "Unauthorized";
  584. case 402: return "Payment Required";
  585. case 403: return "Forbidden";
  586. case 404: return "Not Found";
  587. case 405: return "Method Not Allowed";
  588. case 406: return "Not Acceptable";
  589. case 407: return "Proxy Authentication Required";
  590. case 408: return "Request Timeout";
  591. case 409: return "Conflict";
  592. case 410: return "Gone";
  593. case 411: return "Length Required";
  594. case 412: return "Precondition Failed";
  595. case 413: return "Request Entity Too Large";
  596. case 414: return "Request-Uri Too Long";
  597. case 415: return "Unsupported Media Type";
  598. case 416: return "Requested Range Not Satisfiable";
  599. case 417: return "Expectation Failed";
  600. case 422: return "Unprocessable Entity";
  601. case 423: return "Locked";
  602. case 424: return "Failed Dependency";
  603. case 500: return "Internal Server Error";
  604. case 501: return "Not Implemented";
  605. case 502: return "Bad Gateway";
  606. case 503: return "Service Unavailable";
  607. case 504: return "Gateway Timeout";
  608. case 505: return "Http Version Not Supported";
  609. case 507: return "Insufficient Storage";
  610. }
  611. return string.Empty;
  612. }
  613. /// <summary>
  614. /// Determines whether the specified <see cref="ByteOrder"/> is host
  615. /// (this computer architecture) byte order.
  616. /// </summary>
  617. /// <returns>
  618. /// <c>true</c> if <paramref name="order"/> is host byte order;
  619. /// otherwise, <c>false</c>.
  620. /// </returns>
  621. /// <param name="order">
  622. /// One of the <see cref="ByteOrder"/> enum values, to test.
  623. /// </param>
  624. public static bool IsHostOrder(this ByteOrder order)
  625. {
  626. // true : !(true ^ true) or !(false ^ false)
  627. // false: !(true ^ false) or !(false ^ true)
  628. return !(BitConverter.IsLittleEndian ^ (order == ByteOrder.Little));
  629. }
  630. /// <summary>
  631. /// Determines whether the specified <see cref="string"/> is a predefined scheme.
  632. /// </summary>
  633. /// <returns>
  634. /// <c>true</c> if <paramref name="value"/> is a predefined scheme; otherwise, <c>false</c>.
  635. /// </returns>
  636. /// <param name="value">
  637. /// A <see cref="string"/> to test.
  638. /// </param>
  639. public static bool IsPredefinedScheme(this string value)
  640. {
  641. if (value == null || value.Length < 2)
  642. return false;
  643. var c = value[0];
  644. if (c == 'h')
  645. return value == "http" || value == "https";
  646. if (c == 'w')
  647. return value == "ws" || value == "wss";
  648. if (c == 'f')
  649. return value == "file" || value == "ftp";
  650. if (c == 'n')
  651. {
  652. c = value[1];
  653. return c == 'e'
  654. ? value == "news" || value == "net.pipe" || value == "net.tcp"
  655. : value == "nntp";
  656. }
  657. return (c == 'g' && value == "gopher") || (c == 'm' && value == "mailto");
  658. }
  659. /// <summary>
  660. /// Determines whether the specified <see cref="string"/> is a URI string.
  661. /// </summary>
  662. /// <returns>
  663. /// <c>true</c> if <paramref name="value"/> may be a URI string; otherwise, <c>false</c>.
  664. /// </returns>
  665. /// <param name="value">
  666. /// A <see cref="string"/> to test.
  667. /// </param>
  668. public static bool MaybeUri(this string value)
  669. {
  670. if (value == null || value.Length == 0)
  671. return false;
  672. var i = value.IndexOf(':');
  673. if (i == -1)
  674. return false;
  675. if (i >= 10)
  676. return false;
  677. return value.Substring(0, i).IsPredefinedScheme();
  678. }
  679. /// <summary>
  680. /// Retrieves a sub-array from the specified <paramref name="array"/>.
  681. /// A sub-array starts at the specified element position.
  682. /// </summary>
  683. /// <returns>
  684. /// An array of T that receives a sub-array, or an empty array of T if any problems
  685. /// with the parameters.
  686. /// </returns>
  687. /// <param name="array">
  688. /// An array of T that contains the data to retrieve a sub-array.
  689. /// </param>
  690. /// <param name="startIndex">
  691. /// An <see cref="int"/> that contains the zero-based starting position of a sub-array
  692. /// in <paramref name="array"/>.
  693. /// </param>
  694. /// <param name="length">
  695. /// An <see cref="int"/> that contains the number of elements to retrieve a sub-array.
  696. /// </param>
  697. /// <typeparam name="T">
  698. /// The type of elements in the <paramref name="array"/>.
  699. /// </typeparam>
  700. public static T[] SubArray<T>(this T[] array, int startIndex, int length)
  701. {
  702. if (array == null || array.Length == 0)
  703. return new T[0];
  704. if (startIndex < 0 || length <= 0)
  705. return new T[0];
  706. if (startIndex + length > array.Length)
  707. return new T[0];
  708. if (startIndex == 0 && array.Length == length)
  709. return array;
  710. T[] subArray = new T[length];
  711. Array.Copy(array, startIndex, subArray, 0, length);
  712. return subArray;
  713. }
  714. /// <summary>
  715. /// Converts the order of the specified array of <see cref="byte"/> to the host byte order.
  716. /// </summary>
  717. /// <returns>
  718. /// An array of <see cref="byte"/> converted from <paramref name="src"/>.
  719. /// </returns>
  720. /// <param name="src">
  721. /// An array of <see cref="byte"/> to convert.
  722. /// </param>
  723. /// <param name="srcOrder">
  724. /// One of the <see cref="ByteOrder"/> enum values, indicates the byte order of
  725. /// <paramref name="src"/>.
  726. /// </param>
  727. /// <exception cref="ArgumentNullException">
  728. /// <paramref name="src"/> is <see langword="null"/>.
  729. /// </exception>
  730. public static void ToHostOrder(this byte[] src, ByteOrder srcOrder)
  731. {
  732. if (src == null)
  733. {
  734. throw new ArgumentNullException(nameof(src));
  735. }
  736. if (src.Length > 1 && !srcOrder.IsHostOrder())
  737. {
  738. Array.Reverse(src);
  739. }
  740. }
  741. /// <summary>
  742. /// Converts the specified <paramref name="array"/> to a <see cref="string"/> that
  743. /// concatenates the each element of <paramref name="array"/> across the specified
  744. /// <paramref name="separator"/>.
  745. /// </summary>
  746. /// <returns>
  747. /// A <see cref="string"/> converted from <paramref name="array"/>,
  748. /// or <see cref="String.Empty"/> if <paramref name="array"/> is empty.
  749. /// </returns>
  750. /// <param name="array">
  751. /// An array of T to convert.
  752. /// </param>
  753. /// <param name="separator">
  754. /// A <see cref="string"/> that represents the separator string.
  755. /// </param>
  756. /// <typeparam name="T">
  757. /// The type of elements in <paramref name="array"/>.
  758. /// </typeparam>
  759. /// <exception cref="ArgumentNullException">
  760. /// <paramref name="array"/> is <see langword="null"/>.
  761. /// </exception>
  762. public static string ToString<T>(this T[] array, string separator)
  763. {
  764. if (array == null)
  765. throw new ArgumentNullException(nameof(array));
  766. var len = array.Length;
  767. if (len == 0)
  768. return string.Empty;
  769. if (separator == null)
  770. separator = string.Empty;
  771. var buff = new StringBuilder(64);
  772. (len - 1).Times(i => buff.AppendFormat("{0}{1}", array[i].ToString(), separator));
  773. buff.Append(array[len - 1].ToString());
  774. return buff.ToString();
  775. }
  776. /// <summary>
  777. /// Executes the specified <c>Action&lt;int&gt;</c> delegate <paramref name="n"/> times.
  778. /// </summary>
  779. /// <param name="n">
  780. /// An <see cref="int"/> is the number of times to execute.
  781. /// </param>
  782. /// <param name="action">
  783. /// An <c>Action&lt;int&gt;</c> delegate that references the method(s) to execute.
  784. /// An <see cref="int"/> parameter to pass to the method(s) is the zero-based count of
  785. /// iteration.
  786. /// </param>
  787. public static void Times(this int n, Action<int> action)
  788. {
  789. if (n > 0 && action != null)
  790. for (int i = 0; i < n; i++)
  791. action(i);
  792. }
  793. /// <summary>
  794. /// Converts the specified <see cref="string"/> to a <see cref="Uri"/>.
  795. /// </summary>
  796. /// <returns>
  797. /// A <see cref="Uri"/> converted from <paramref name="uriString"/>, or <see langword="null"/>
  798. /// if <paramref name="uriString"/> isn't successfully converted.
  799. /// </returns>
  800. /// <param name="uriString">
  801. /// A <see cref="string"/> to convert.
  802. /// </param>
  803. public static Uri ToUri(this string uriString)
  804. {
  805. return Uri.TryCreate(
  806. uriString, uriString.MaybeUri() ? UriKind.Absolute : UriKind.Relative, out var res)
  807. ? res
  808. : null;
  809. }
  810. /// <summary>
  811. /// URL-decodes the specified <see cref="string"/>.
  812. /// </summary>
  813. /// <returns>
  814. /// A <see cref="string"/> that receives the decoded string, or the <paramref name="value"/>
  815. /// if it's <see langword="null"/> or empty.
  816. /// </returns>
  817. /// <param name="value">
  818. /// A <see cref="string"/> to decode.
  819. /// </param>
  820. public static string UrlDecode(this string value)
  821. {
  822. return value == null || value.Length == 0
  823. ? value
  824. : WebUtility.UrlDecode(value);
  825. }
  826. #endregion
  827. }
  828. }