Ext.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Net;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.Services;
  10. using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
  11. using WebSocketState = System.Net.WebSockets.WebSocketState;
  12. namespace SocketHttpListener
  13. {
  14. /// <summary>
  15. /// Provides a set of static methods for the websocket-sharp.
  16. /// </summary>
  17. public static class Ext
  18. {
  19. #region Private Const Fields
  20. private const string _tspecials = "()<>@,;:\\\"/[]?={} \t";
  21. #endregion
  22. #region Private Methods
  23. private static MemoryStream compress(this Stream stream)
  24. {
  25. var output = new MemoryStream();
  26. if (stream.Length == 0)
  27. return output;
  28. stream.Position = 0;
  29. using (var ds = new DeflateStream(output, CompressionMode.Compress, true))
  30. {
  31. stream.CopyTo(ds);
  32. //ds.Close(); // "BFINAL" set to 1.
  33. output.Position = 0;
  34. return output;
  35. }
  36. }
  37. private static byte[] decompress(this byte[] value)
  38. {
  39. if (value.Length == 0)
  40. return value;
  41. using (var input = new MemoryStream(value))
  42. {
  43. return input.decompressToArray();
  44. }
  45. }
  46. private static MemoryStream decompress(this Stream stream)
  47. {
  48. var output = new MemoryStream();
  49. if (stream.Length == 0)
  50. return output;
  51. stream.Position = 0;
  52. using (var ds = new DeflateStream(stream, CompressionMode.Decompress, true))
  53. {
  54. ds.CopyTo(output, true);
  55. return output;
  56. }
  57. }
  58. private static byte[] decompressToArray(this Stream stream)
  59. {
  60. using (var decomp = stream.decompress())
  61. {
  62. return decomp.ToArray();
  63. }
  64. }
  65. private static byte[] readBytes(this Stream stream, byte[] buffer, int offset, int length)
  66. {
  67. var len = stream.Read(buffer, offset, length);
  68. if (len < 1)
  69. return buffer.SubArray(0, offset);
  70. var tmp = 0;
  71. while (len < length)
  72. {
  73. tmp = stream.Read(buffer, offset + len, length - len);
  74. if (tmp < 1)
  75. break;
  76. len += tmp;
  77. }
  78. return len < length
  79. ? buffer.SubArray(0, offset + len)
  80. : buffer;
  81. }
  82. private static bool readBytes(
  83. this Stream stream, byte[] buffer, int offset, int length, Stream dest)
  84. {
  85. var bytes = stream.readBytes(buffer, offset, length);
  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 byte[] Append(this ushort code, string reason)
  93. {
  94. using (var buffer = new MemoryStream())
  95. {
  96. var tmp = code.ToByteArrayInternally(ByteOrder.Big);
  97. buffer.Write(tmp, 0, 2);
  98. if (reason != null && reason.Length > 0)
  99. {
  100. tmp = Encoding.UTF8.GetBytes(reason);
  101. buffer.Write(tmp, 0, tmp.Length);
  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("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 byte[] ReadBytes(this Stream stream, int length)
  287. {
  288. return stream.readBytes(new byte[length], 0, length);
  289. }
  290. internal static byte[] ReadBytes(this Stream stream, long length, int bufferLength)
  291. {
  292. using (var result = new MemoryStream())
  293. {
  294. var count = length / bufferLength;
  295. var rem = (int)(length % bufferLength);
  296. var buffer = new byte[bufferLength];
  297. var end = false;
  298. for (long i = 0; i < count; i++)
  299. {
  300. if (!stream.readBytes(buffer, 0, bufferLength, result))
  301. {
  302. end = true;
  303. break;
  304. }
  305. }
  306. if (!end && rem > 0)
  307. stream.readBytes(new byte[rem], 0, rem, result);
  308. return result.ToArray();
  309. }
  310. }
  311. internal static async Task<byte[]> ReadBytesAsync(this Stream stream, int length)
  312. {
  313. var buffer = new byte[length];
  314. var len = await stream.ReadAsync(buffer, 0, length).ConfigureAwait(false);
  315. var bytes = len < 1
  316. ? new byte[0]
  317. : len < length
  318. ? stream.readBytes(buffer, len, length - len)
  319. : buffer;
  320. return bytes;
  321. }
  322. internal static string RemovePrefix(this string value, params string[] prefixes)
  323. {
  324. var i = 0;
  325. foreach (var prefix in prefixes)
  326. {
  327. if (value.StartsWith(prefix))
  328. {
  329. i = prefix.Length;
  330. break;
  331. }
  332. }
  333. return i > 0
  334. ? value.Substring(i)
  335. : value;
  336. }
  337. internal static T[] Reverse<T>(this T[] array)
  338. {
  339. var len = array.Length;
  340. T[] reverse = new T[len];
  341. var end = len - 1;
  342. for (var i = 0; i <= end; i++)
  343. reverse[i] = array[end - i];
  344. return reverse;
  345. }
  346. internal static IEnumerable<string> SplitHeaderValue(
  347. this string value, params char[] separator)
  348. {
  349. var len = value.Length;
  350. var separators = new string(separator);
  351. var buffer = new StringBuilder(32);
  352. var quoted = false;
  353. var escaped = false;
  354. char c;
  355. for (var i = 0; i < len; i++)
  356. {
  357. c = value[i];
  358. if (c == '"')
  359. {
  360. if (escaped)
  361. escaped = !escaped;
  362. else
  363. quoted = !quoted;
  364. }
  365. else if (c == '\\')
  366. {
  367. if (i < len - 1 && value[i + 1] == '"')
  368. escaped = true;
  369. }
  370. else if (separators.Contains(c))
  371. {
  372. if (!quoted)
  373. {
  374. yield return buffer.ToString();
  375. buffer.Length = 0;
  376. continue;
  377. }
  378. }
  379. else {
  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().ToLower());
  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("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("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. Uri res;
  815. return Uri.TryCreate(
  816. uriString, uriString.MaybeUri() ? UriKind.Absolute : UriKind.Relative, out res)
  817. ? res
  818. : null;
  819. }
  820. /// <summary>
  821. /// URL-decodes the specified <see cref="string"/>.
  822. /// </summary>
  823. /// <returns>
  824. /// A <see cref="string"/> that receives the decoded string, or the <paramref name="value"/>
  825. /// if it's <see langword="null"/> or empty.
  826. /// </returns>
  827. /// <param name="value">
  828. /// A <see cref="string"/> to decode.
  829. /// </param>
  830. public static string UrlDecode(this string value)
  831. {
  832. return value == null || value.Length == 0
  833. ? value
  834. : WebUtility.UrlDecode(value);
  835. }
  836. #endregion
  837. }
  838. }