Ext.cs 33 KB

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