Ext.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  1. #region License
  2. /*
  3. * Ext.cs
  4. *
  5. * Some parts of this code are derived from Mono (http://www.mono-project.com):
  6. * - GetStatusDescription is derived from HttpListenerResponse.cs (System.Net)
  7. * - MaybeUri is derived from Uri.cs (System)
  8. * - isPredefinedScheme is derived from Uri.cs (System)
  9. *
  10. * The MIT License
  11. *
  12. * Copyright (c) 2001 Garrett Rooney
  13. * Copyright (c) 2003 Ian MacLean
  14. * Copyright (c) 2003 Ben Maurer
  15. * Copyright (c) 2003, 2005, 2009 Novell, Inc. (http://www.novell.com)
  16. * Copyright (c) 2009 Stephane Delcroix
  17. * Copyright (c) 2010-2023 sta.blockhead
  18. *
  19. * Permission is hereby granted, free of charge, to any person obtaining a copy
  20. * of this software and associated documentation files (the "Software"), to deal
  21. * in the Software without restriction, including without limitation the rights
  22. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  23. * copies of the Software, and to permit persons to whom the Software is
  24. * furnished to do so, subject to the following conditions:
  25. *
  26. * The above copyright notice and this permission notice shall be included in
  27. * all copies or substantial portions of the Software.
  28. *
  29. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  30. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  32. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  33. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  34. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  35. * THE SOFTWARE.
  36. */
  37. #endregion
  38. #region Contributors
  39. /*
  40. * Contributors:
  41. * - Liryna <liryna.stark@gmail.com>
  42. * - Nikola Kovacevic <nikolak@outlook.com>
  43. * - Chris Swiedler
  44. */
  45. #endregion
  46. using System;
  47. using System.Collections.Generic;
  48. using System.Collections.Specialized;
  49. using System.IO;
  50. using System.IO.Compression;
  51. using System.Net.Sockets;
  52. using System.Security.Cryptography.X509Certificates;
  53. using System.Text;
  54. using WebSocketSharp.Net;
  55. using WebSocketSharp.Net.WebSockets;
  56. using WebSocketSharp.Server;
  57. namespace WebSocketSharp
  58. {
  59. /// <summary>
  60. /// Provides a set of static methods for websocket-sharp.
  61. /// </summary>
  62. public static class Ext
  63. {
  64. #region Private Fields
  65. private static readonly byte[] _last = new byte[] { 0x00 };
  66. private static readonly int _maxRetry = 5;
  67. private const string _tspecials = "()<>@,;:\\\"/[]?={} \t";
  68. #endregion
  69. #region Private Methods
  70. private static byte[] compress (this byte[] data)
  71. {
  72. if (data.LongLength == 0)
  73. return data;
  74. using (var input = new MemoryStream (data))
  75. return input.compressToArray ();
  76. }
  77. private static MemoryStream compress (this Stream stream)
  78. {
  79. var ret = new MemoryStream ();
  80. if (stream.Length == 0)
  81. return ret;
  82. stream.Position = 0;
  83. var mode = CompressionMode.Compress;
  84. using (var ds = new DeflateStream (ret, mode, true)) {
  85. stream.CopyTo (ds, 1024);
  86. ds.Close (); // BFINAL set to 1.
  87. ret.Write (_last, 0, 1);
  88. ret.Position = 0;
  89. return ret;
  90. }
  91. }
  92. private static byte[] compressToArray (this Stream stream)
  93. {
  94. using (var output = stream.compress ()) {
  95. output.Close ();
  96. return output.ToArray ();
  97. }
  98. }
  99. private static byte[] decompress (this byte[] data)
  100. {
  101. if (data.LongLength == 0)
  102. return data;
  103. using (var input = new MemoryStream (data))
  104. return input.decompressToArray ();
  105. }
  106. private static MemoryStream decompress (this Stream stream)
  107. {
  108. var ret = new MemoryStream ();
  109. if (stream.Length == 0)
  110. return ret;
  111. stream.Position = 0;
  112. var mode = CompressionMode.Decompress;
  113. using (var ds = new DeflateStream (stream, mode, true)) {
  114. ds.CopyTo (ret, 1024);
  115. ret.Position = 0;
  116. return ret;
  117. }
  118. }
  119. private static byte[] decompressToArray (this Stream stream)
  120. {
  121. using (var output = stream.decompress ()) {
  122. output.Close ();
  123. return output.ToArray ();
  124. }
  125. }
  126. private static bool isPredefinedScheme (this string value)
  127. {
  128. var c = value[0];
  129. if (c == 'h')
  130. return value == "http" || value == "https";
  131. if (c == 'w')
  132. return value == "ws" || value == "wss";
  133. if (c == 'f')
  134. return value == "file" || value == "ftp";
  135. if (c == 'g')
  136. return value == "gopher";
  137. if (c == 'm')
  138. return value == "mailto";
  139. if (c == 'n') {
  140. c = value[1];
  141. return c == 'e'
  142. ? value == "news" || value == "net.pipe" || value == "net.tcp"
  143. : value == "nntp";
  144. }
  145. return false;
  146. }
  147. #endregion
  148. #region Internal Methods
  149. internal static byte[] Append (this ushort code, string reason)
  150. {
  151. var codeAsBytes = code.ToByteArray (ByteOrder.Big);
  152. if (reason == null || reason.Length == 0)
  153. return codeAsBytes;
  154. var buff = new List<byte> (codeAsBytes);
  155. var reasonAsBytes = Encoding.UTF8.GetBytes (reason);
  156. buff.AddRange (reasonAsBytes);
  157. return buff.ToArray ();
  158. }
  159. internal static byte[] Compress (
  160. this byte[] data, CompressionMethod method
  161. )
  162. {
  163. return method == CompressionMethod.Deflate
  164. ? data.compress ()
  165. : data;
  166. }
  167. internal static Stream Compress (
  168. this Stream stream, CompressionMethod method
  169. )
  170. {
  171. return method == CompressionMethod.Deflate
  172. ? stream.compress ()
  173. : stream;
  174. }
  175. internal static bool Contains (this string value, params char[] anyOf)
  176. {
  177. return anyOf != null && anyOf.Length > 0
  178. ? value.IndexOfAny (anyOf) > -1
  179. : false;
  180. }
  181. internal static bool Contains (
  182. this NameValueCollection collection, string name
  183. )
  184. {
  185. return collection[name] != null;
  186. }
  187. internal static bool Contains (
  188. this NameValueCollection collection,
  189. string name,
  190. string value,
  191. StringComparison comparisonTypeForValue
  192. )
  193. {
  194. var val = collection[name];
  195. if (val == null)
  196. return false;
  197. foreach (var elm in val.Split (',')) {
  198. if (elm.Trim ().Equals (value, comparisonTypeForValue))
  199. return true;
  200. }
  201. return false;
  202. }
  203. internal static bool Contains<T> (
  204. this IEnumerable<T> source, Func<T, bool> condition
  205. )
  206. {
  207. foreach (T elm in source) {
  208. if (condition (elm))
  209. return true;
  210. }
  211. return false;
  212. }
  213. internal static bool ContainsTwice (this string[] values)
  214. {
  215. var len = values.Length;
  216. var end = len - 1;
  217. Func<int, bool> seek = null;
  218. seek = idx => {
  219. if (idx == end)
  220. return false;
  221. var val = values[idx];
  222. for (var i = idx + 1; i < len; i++) {
  223. if (values[i] == val)
  224. return true;
  225. }
  226. return seek (++idx);
  227. };
  228. return seek (0);
  229. }
  230. internal static T[] Copy<T> (this T[] sourceArray, int length)
  231. {
  232. var dest = new T[length];
  233. Array.Copy (sourceArray, 0, dest, 0, length);
  234. return dest;
  235. }
  236. internal static T[] Copy<T> (this T[] sourceArray, long length)
  237. {
  238. var dest = new T[length];
  239. Array.Copy (sourceArray, 0, dest, 0, length);
  240. return dest;
  241. }
  242. internal static void CopyTo (
  243. this Stream sourceStream, Stream destinationStream, int bufferLength
  244. )
  245. {
  246. var buff = new byte[bufferLength];
  247. while (true) {
  248. var nread = sourceStream.Read (buff, 0, bufferLength);
  249. if (nread <= 0)
  250. break;
  251. destinationStream.Write (buff, 0, nread);
  252. }
  253. }
  254. internal static void CopyToAsync (
  255. this Stream sourceStream,
  256. Stream destinationStream,
  257. int bufferLength,
  258. Action completed,
  259. Action<Exception> error
  260. )
  261. {
  262. var buff = new byte[bufferLength];
  263. AsyncCallback callback = null;
  264. callback =
  265. ar => {
  266. try {
  267. var nread = sourceStream.EndRead (ar);
  268. if (nread <= 0) {
  269. if (completed != null)
  270. completed ();
  271. return;
  272. }
  273. destinationStream.Write (buff, 0, nread);
  274. sourceStream.BeginRead (buff, 0, bufferLength, callback, null);
  275. }
  276. catch (Exception ex) {
  277. if (error != null)
  278. error (ex);
  279. }
  280. };
  281. try {
  282. sourceStream.BeginRead (buff, 0, bufferLength, callback, null);
  283. }
  284. catch (Exception ex) {
  285. if (error != null)
  286. error (ex);
  287. }
  288. }
  289. internal static byte[] Decompress (
  290. this byte[] data, CompressionMethod method
  291. )
  292. {
  293. return method == CompressionMethod.Deflate
  294. ? data.decompress ()
  295. : data;
  296. }
  297. internal static Stream Decompress (
  298. this Stream stream, CompressionMethod method
  299. )
  300. {
  301. return method == CompressionMethod.Deflate
  302. ? stream.decompress ()
  303. : stream;
  304. }
  305. internal static byte[] DecompressToArray (
  306. this Stream stream, CompressionMethod method
  307. )
  308. {
  309. return method == CompressionMethod.Deflate
  310. ? stream.decompressToArray ()
  311. : stream.ToByteArray ();
  312. }
  313. internal static void Emit (
  314. this EventHandler eventHandler, object sender, EventArgs e
  315. )
  316. {
  317. if (eventHandler == null)
  318. return;
  319. eventHandler (sender, e);
  320. }
  321. internal static void Emit<TEventArgs> (
  322. this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e
  323. )
  324. where TEventArgs : EventArgs
  325. {
  326. if (eventHandler == null)
  327. return;
  328. eventHandler (sender, e);
  329. }
  330. internal static string GetAbsolutePath (this Uri uri)
  331. {
  332. if (uri.IsAbsoluteUri)
  333. return uri.AbsolutePath;
  334. var original = uri.OriginalString;
  335. if (original[0] != '/')
  336. return null;
  337. var idx = original.IndexOfAny (new[] { '?', '#' });
  338. return idx > 0 ? original.Substring (0, idx) : original;
  339. }
  340. internal static CookieCollection GetCookies (
  341. this NameValueCollection headers, bool response
  342. )
  343. {
  344. var val = headers[response ? "Set-Cookie" : "Cookie"];
  345. return val != null
  346. ? CookieCollection.Parse (val, response)
  347. : new CookieCollection ();
  348. }
  349. internal static string GetDnsSafeHost (this Uri uri, bool bracketIPv6)
  350. {
  351. return bracketIPv6 && uri.HostNameType == UriHostNameType.IPv6
  352. ? uri.Host
  353. : uri.DnsSafeHost;
  354. }
  355. internal static string GetErrorMessage (this ushort code)
  356. {
  357. switch (code) {
  358. case 1002:
  359. return "A protocol error has occurred.";
  360. case 1003:
  361. return "Unsupported data has been received.";
  362. case 1006:
  363. return "An abnormal error has occurred.";
  364. case 1007:
  365. return "Invalid data has been received.";
  366. case 1008:
  367. return "A policy violation has occurred.";
  368. case 1009:
  369. return "A too big message has been received.";
  370. case 1010:
  371. return "The client did not receive expected extension(s).";
  372. case 1011:
  373. return "The server got an internal error.";
  374. case 1015:
  375. return "An error has occurred during a TLS handshake.";
  376. default:
  377. return String.Empty;
  378. }
  379. }
  380. internal static string GetErrorMessage (this CloseStatusCode code)
  381. {
  382. return ((ushort) code).GetErrorMessage ();
  383. }
  384. internal static string GetName (this string nameAndValue, char separator)
  385. {
  386. var idx = nameAndValue.IndexOf (separator);
  387. return idx > 0 ? nameAndValue.Substring (0, idx).Trim () : null;
  388. }
  389. internal static string GetUTF8DecodedString (this byte[] bytes)
  390. {
  391. try {
  392. return Encoding.UTF8.GetString (bytes);
  393. }
  394. catch {
  395. return null;
  396. }
  397. }
  398. internal static byte[] GetUTF8EncodedBytes (this string s)
  399. {
  400. try {
  401. return Encoding.UTF8.GetBytes (s);
  402. }
  403. catch {
  404. return null;
  405. }
  406. }
  407. internal static string GetValue (this string nameAndValue, char separator)
  408. {
  409. return nameAndValue.GetValue (separator, false);
  410. }
  411. internal static string GetValue (
  412. this string nameAndValue, char separator, bool unquote
  413. )
  414. {
  415. var idx = nameAndValue.IndexOf (separator);
  416. if (idx < 0 || idx == nameAndValue.Length - 1)
  417. return null;
  418. var val = nameAndValue.Substring (idx + 1).Trim ();
  419. return unquote ? val.Unquote () : val;
  420. }
  421. internal static bool IsCompressionExtension (
  422. this string value, CompressionMethod method
  423. )
  424. {
  425. var extStr = method.ToExtensionString ();
  426. var compType = StringComparison.Ordinal;
  427. return value.StartsWith (extStr, compType);
  428. }
  429. internal static bool IsEqualTo (
  430. this int value, char c, Action<int> beforeComparing
  431. )
  432. {
  433. beforeComparing (value);
  434. return value == c - 0;
  435. }
  436. internal static bool IsHttpMethod (this string value)
  437. {
  438. return value == "GET"
  439. || value == "HEAD"
  440. || value == "POST"
  441. || value == "PUT"
  442. || value == "DELETE"
  443. || value == "CONNECT"
  444. || value == "OPTIONS"
  445. || value == "TRACE";
  446. }
  447. internal static bool IsPortNumber (this int value)
  448. {
  449. return value > 0 && value < 65536;
  450. }
  451. internal static bool IsReserved (this CloseStatusCode code)
  452. {
  453. return ((ushort) code).IsReservedStatusCode ();
  454. }
  455. internal static bool IsReservedStatusCode (this ushort code)
  456. {
  457. return code == 1004
  458. || code == 1005
  459. || code == 1006
  460. || code == 1015;
  461. }
  462. internal static bool IsSupportedOpcode (this byte opcode)
  463. {
  464. return Enum.IsDefined (typeof (Opcode), opcode);
  465. }
  466. internal static bool IsText (this string value)
  467. {
  468. var len = value.Length;
  469. for (var i = 0; i < len; i++) {
  470. var c = value[i];
  471. if (c < 0x20) {
  472. if ("\r\n\t".IndexOf (c) == -1)
  473. return false;
  474. if (c == '\n') {
  475. i++;
  476. if (i == len)
  477. break;
  478. c = value[i];
  479. if (" \t".IndexOf (c) == -1)
  480. return false;
  481. }
  482. continue;
  483. }
  484. if (c == 0x7f)
  485. return false;
  486. }
  487. return true;
  488. }
  489. internal static bool IsToken (this string value)
  490. {
  491. foreach (var c in value) {
  492. if (c < 0x20)
  493. return false;
  494. if (c > 0x7e)
  495. return false;
  496. if (_tspecials.IndexOf (c) > -1)
  497. return false;
  498. }
  499. return true;
  500. }
  501. internal static bool KeepsAlive (
  502. this NameValueCollection headers, Version version
  503. )
  504. {
  505. var compType = StringComparison.OrdinalIgnoreCase;
  506. return version < HttpVersion.Version11
  507. ? headers.Contains ("Connection", "keep-alive", compType)
  508. : !headers.Contains ("Connection", "close", compType);
  509. }
  510. internal static bool MaybeUri (this string value)
  511. {
  512. var idx = value.IndexOf (':');
  513. if (idx < 2 || idx > 9)
  514. return false;
  515. var schm = value.Substring (0, idx);
  516. return schm.isPredefinedScheme ();
  517. }
  518. internal static string Quote (this string value)
  519. {
  520. var fmt = "\"{0}\"";
  521. var val = value.Replace ("\"", "\\\"");
  522. return String.Format (fmt, val);
  523. }
  524. internal static byte[] ReadBytes (this Stream stream, int length)
  525. {
  526. var ret = new byte[length];
  527. var offset = 0;
  528. var retry = 0;
  529. while (length > 0) {
  530. var nread = stream.Read (ret, offset, length);
  531. if (nread <= 0) {
  532. if (retry < _maxRetry) {
  533. retry++;
  534. continue;
  535. }
  536. return ret.SubArray (0, offset);
  537. }
  538. retry = 0;
  539. offset += nread;
  540. length -= nread;
  541. }
  542. return ret;
  543. }
  544. internal static byte[] ReadBytes (
  545. this Stream stream, long length, int bufferLength
  546. )
  547. {
  548. using (var dest = new MemoryStream ()) {
  549. var buff = new byte[bufferLength];
  550. var retry = 0;
  551. while (length > 0) {
  552. if (length < bufferLength)
  553. bufferLength = (int) length;
  554. var nread = stream.Read (buff, 0, bufferLength);
  555. if (nread <= 0) {
  556. if (retry < _maxRetry) {
  557. retry++;
  558. continue;
  559. }
  560. break;
  561. }
  562. retry = 0;
  563. dest.Write (buff, 0, nread);
  564. length -= nread;
  565. }
  566. dest.Close ();
  567. return dest.ToArray ();
  568. }
  569. }
  570. internal static void ReadBytesAsync (
  571. this Stream stream,
  572. int length,
  573. Action<byte[]> completed,
  574. Action<Exception> error
  575. )
  576. {
  577. var ret = new byte[length];
  578. var offset = 0;
  579. var retry = 0;
  580. AsyncCallback callback = null;
  581. callback =
  582. ar => {
  583. try {
  584. var nread = stream.EndRead (ar);
  585. if (nread <= 0) {
  586. if (retry < _maxRetry) {
  587. retry++;
  588. stream.BeginRead (ret, offset, length, callback, null);
  589. return;
  590. }
  591. if (completed != null)
  592. completed (ret.SubArray (0, offset));
  593. return;
  594. }
  595. if (nread == length) {
  596. if (completed != null)
  597. completed (ret);
  598. return;
  599. }
  600. retry = 0;
  601. offset += nread;
  602. length -= nread;
  603. stream.BeginRead (ret, offset, length, callback, null);
  604. }
  605. catch (Exception ex) {
  606. if (error != null)
  607. error (ex);
  608. }
  609. };
  610. try {
  611. stream.BeginRead (ret, offset, length, callback, null);
  612. }
  613. catch (Exception ex) {
  614. if (error != null)
  615. error (ex);
  616. }
  617. }
  618. internal static void ReadBytesAsync (
  619. this Stream stream,
  620. long length,
  621. int bufferLength,
  622. Action<byte[]> completed,
  623. Action<Exception> error
  624. )
  625. {
  626. Console.WriteLine(("Into ReadBytesAsync"));
  627. var dest = new MemoryStream ();
  628. var retry = 0;
  629. Action<long> read = null;
  630. read =
  631. len => {
  632. Console.WriteLine("Into Read()");
  633. if (len < bufferLength)
  634. bufferLength = (int) len;
  635. var buff = new byte[bufferLength];
  636. stream.BeginRead (
  637. buff,
  638. 0,
  639. bufferLength,
  640. ar => {
  641. try {
  642. var nread = stream.EndRead (ar);
  643. if (nread <= 0) {
  644. if (retry < _maxRetry) {
  645. retry++;
  646. read (len);
  647. return;
  648. }
  649. if (completed != null) {
  650. dest.Close ();
  651. var ret = dest.ToArray ();
  652. completed (ret);
  653. }
  654. dest.Dispose ();
  655. return;
  656. }
  657. dest.Write (buff, 0, nread);
  658. if (nread == len) {
  659. if (completed != null) {
  660. dest.Close ();
  661. var ret = dest.ToArray ();
  662. completed (ret);
  663. }
  664. dest.Dispose ();
  665. return;
  666. }
  667. retry = 0;
  668. read (len - nread);
  669. }
  670. catch (Exception ex) {
  671. dest.Dispose ();
  672. if (error != null)
  673. error (ex);
  674. }
  675. },
  676. null
  677. );
  678. };
  679. try {
  680. read (length);
  681. }
  682. catch (Exception ex) {
  683. dest.Dispose ();
  684. if (error != null)
  685. error (ex);
  686. }
  687. }
  688. internal static T[] Reverse<T> (this T[] array)
  689. {
  690. var len = array.LongLength;
  691. var ret = new T[len];
  692. var end = len - 1;
  693. for (long i = 0; i <= end; i++)
  694. ret[i] = array[end - i];
  695. return ret;
  696. }
  697. internal static IEnumerable<string> SplitHeaderValue (
  698. this string value, params char[] separators
  699. )
  700. {
  701. var len = value.Length;
  702. var end = len - 1;
  703. var buff = new StringBuilder (32);
  704. var escaped = false;
  705. var quoted = false;
  706. for (var i = 0; i <= end; i++) {
  707. var c = value[i];
  708. buff.Append (c);
  709. if (c == '"') {
  710. if (escaped) {
  711. escaped = false;
  712. continue;
  713. }
  714. quoted = !quoted;
  715. continue;
  716. }
  717. if (c == '\\') {
  718. if (i == end)
  719. break;
  720. if (value[i + 1] == '"')
  721. escaped = true;
  722. continue;
  723. }
  724. if (Array.IndexOf (separators, c) > -1) {
  725. if (quoted)
  726. continue;
  727. buff.Length -= 1;
  728. yield return buff.ToString ();
  729. buff.Length = 0;
  730. continue;
  731. }
  732. }
  733. yield return buff.ToString ();
  734. }
  735. internal static byte[] ToByteArray (this Stream stream)
  736. {
  737. stream.Position = 0;
  738. using (var buff = new MemoryStream ()) {
  739. stream.CopyTo (buff, 1024);
  740. buff.Close ();
  741. return buff.ToArray ();
  742. }
  743. }
  744. internal static byte[] ToByteArray (this ushort value, ByteOrder order)
  745. {
  746. var ret = BitConverter.GetBytes (value);
  747. if (!order.IsHostOrder ())
  748. Array.Reverse (ret);
  749. return ret;
  750. }
  751. internal static byte[] ToByteArray (this ulong value, ByteOrder order)
  752. {
  753. var ret = BitConverter.GetBytes (value);
  754. if (!order.IsHostOrder ())
  755. Array.Reverse (ret);
  756. return ret;
  757. }
  758. internal static CompressionMethod ToCompressionMethod (this string value)
  759. {
  760. var methods = Enum.GetValues (typeof (CompressionMethod));
  761. foreach (CompressionMethod method in methods) {
  762. if (method.ToExtensionString () == value)
  763. return method;
  764. }
  765. return CompressionMethod.None;
  766. }
  767. internal static string ToExtensionString (
  768. this CompressionMethod method, params string[] parameters
  769. )
  770. {
  771. if (method == CompressionMethod.None)
  772. return String.Empty;
  773. var name = method.ToString ().ToLower ();
  774. var ename = String.Format ("permessage-{0}", name);
  775. if (parameters == null || parameters.Length == 0)
  776. return ename;
  777. var eparams = parameters.ToString ("; ");
  778. return String.Format ("{0}; {1}", ename, eparams);
  779. }
  780. internal static int ToInt32 (this string numericString)
  781. {
  782. return Int32.Parse (numericString);
  783. }
  784. internal static System.Net.IPAddress ToIPAddress (this string value)
  785. {
  786. if (value == null || value.Length == 0)
  787. return null;
  788. System.Net.IPAddress addr;
  789. if (System.Net.IPAddress.TryParse (value, out addr))
  790. return addr;
  791. try {
  792. var addrs = System.Net.Dns.GetHostAddresses (value);
  793. return addrs[0];
  794. }
  795. catch {
  796. return null;
  797. }
  798. }
  799. internal static List<TSource> ToList<TSource> (
  800. this IEnumerable<TSource> source
  801. )
  802. {
  803. return new List<TSource> (source);
  804. }
  805. internal static string ToString (
  806. this System.Net.IPAddress address, bool bracketIPv6
  807. )
  808. {
  809. return bracketIPv6
  810. && address.AddressFamily == AddressFamily.InterNetworkV6
  811. ? String.Format ("[{0}]", address)
  812. : address.ToString ();
  813. }
  814. internal static ushort ToUInt16 (this byte[] source, ByteOrder sourceOrder)
  815. {
  816. var val = source.ToHostOrder (sourceOrder);
  817. return BitConverter.ToUInt16 (val, 0);
  818. }
  819. internal static ulong ToUInt64 (this byte[] source, ByteOrder sourceOrder)
  820. {
  821. var val = source.ToHostOrder (sourceOrder);
  822. return BitConverter.ToUInt64 (val, 0);
  823. }
  824. internal static Version ToVersion (this string versionString)
  825. {
  826. return new Version (versionString);
  827. }
  828. internal static IEnumerable<string> TrimEach (
  829. this IEnumerable<string> source
  830. )
  831. {
  832. foreach (var elm in source)
  833. yield return elm.Trim ();
  834. }
  835. internal static string TrimSlashFromEnd (this string value)
  836. {
  837. var ret = value.TrimEnd ('/');
  838. return ret.Length > 0 ? ret : "/";
  839. }
  840. internal static string TrimSlashOrBackslashFromEnd (this string value)
  841. {
  842. var ret = value.TrimEnd ('/', '\\');
  843. return ret.Length > 0 ? ret : value[0].ToString ();
  844. }
  845. internal static bool TryCreateVersion (
  846. this string versionString, out Version result
  847. )
  848. {
  849. result = null;
  850. try {
  851. result = new Version (versionString);
  852. }
  853. catch {
  854. return false;
  855. }
  856. return true;
  857. }
  858. internal static bool TryCreateWebSocketUri (
  859. this string uriString, out Uri result, out string message
  860. )
  861. {
  862. result = null;
  863. message = null;
  864. var uri = uriString.ToUri ();
  865. if (uri == null) {
  866. message = "An invalid URI string.";
  867. return false;
  868. }
  869. if (!uri.IsAbsoluteUri) {
  870. message = "A relative URI.";
  871. return false;
  872. }
  873. var schm = uri.Scheme;
  874. var valid = schm == "ws" || schm == "wss";
  875. if (!valid) {
  876. message = "The scheme part is not 'ws' or 'wss'.";
  877. return false;
  878. }
  879. var port = uri.Port;
  880. if (port == 0) {
  881. message = "The port part is zero.";
  882. return false;
  883. }
  884. if (uri.Fragment.Length > 0) {
  885. message = "It includes the fragment component.";
  886. return false;
  887. }
  888. if (port == -1) {
  889. port = schm == "ws" ? 80 : 443;
  890. uriString = String.Format (
  891. "{0}://{1}:{2}{3}",
  892. schm,
  893. uri.Host,
  894. port,
  895. uri.PathAndQuery
  896. );
  897. result = new Uri (uriString);
  898. }
  899. else {
  900. result = uri;
  901. }
  902. return true;
  903. }
  904. internal static bool TryGetUTF8DecodedString (
  905. this byte[] bytes, out string s
  906. )
  907. {
  908. s = null;
  909. try {
  910. s = Encoding.UTF8.GetString (bytes);
  911. }
  912. catch {
  913. return false;
  914. }
  915. return true;
  916. }
  917. internal static bool TryGetUTF8EncodedBytes (
  918. this string s, out byte[] bytes
  919. )
  920. {
  921. bytes = null;
  922. try {
  923. bytes = Encoding.UTF8.GetBytes (s);
  924. }
  925. catch {
  926. return false;
  927. }
  928. return true;
  929. }
  930. internal static bool TryOpenRead (
  931. this FileInfo fileInfo, out FileStream fileStream
  932. )
  933. {
  934. fileStream = null;
  935. try {
  936. fileStream = fileInfo.OpenRead ();
  937. }
  938. catch {
  939. return false;
  940. }
  941. return true;
  942. }
  943. internal static string Unquote (this string value)
  944. {
  945. var first = value.IndexOf ('"');
  946. if (first == -1)
  947. return value;
  948. var last = value.LastIndexOf ('"');
  949. if (last == first)
  950. return value;
  951. var len = last - first - 1;
  952. return len > 0
  953. ? value.Substring (first + 1, len).Replace ("\\\"", "\"")
  954. : String.Empty;
  955. }
  956. internal static bool Upgrades (
  957. this NameValueCollection headers, string protocol
  958. )
  959. {
  960. var compType = StringComparison.OrdinalIgnoreCase;
  961. return headers.Contains ("Upgrade", protocol, compType)
  962. && headers.Contains ("Connection", "Upgrade", compType);
  963. }
  964. internal static string UrlDecode (this string value, Encoding encoding)
  965. {
  966. return value.IndexOfAny (new[] { '%', '+' }) > -1
  967. ? HttpUtility.UrlDecode (value, encoding)
  968. : value;
  969. }
  970. internal static string UrlEncode (this string value, Encoding encoding)
  971. {
  972. return HttpUtility.UrlEncode (value, encoding);
  973. }
  974. internal static void WriteBytes (
  975. this Stream stream, byte[] bytes, int bufferLength
  976. )
  977. {
  978. using (var src = new MemoryStream (bytes))
  979. src.CopyTo (stream, bufferLength);
  980. }
  981. internal static void WriteBytesAsync (
  982. this Stream stream,
  983. byte[] bytes,
  984. int bufferLength,
  985. Action completed,
  986. Action<Exception> error
  987. )
  988. {
  989. var src = new MemoryStream (bytes);
  990. src.CopyToAsync (
  991. stream,
  992. bufferLength,
  993. () => {
  994. if (completed != null)
  995. completed ();
  996. src.Dispose ();
  997. },
  998. ex => {
  999. src.Dispose ();
  1000. if (error != null)
  1001. error (ex);
  1002. }
  1003. );
  1004. }
  1005. #endregion
  1006. #region Public Methods
  1007. /// <summary>
  1008. /// Gets the description of the specified HTTP status code.
  1009. /// </summary>
  1010. /// <returns>
  1011. /// A <see cref="string"/> that represents the description of
  1012. /// the HTTP status code.
  1013. /// </returns>
  1014. /// <param name="code">
  1015. /// <para>
  1016. /// One of the <see cref="HttpStatusCode"/> enum values.
  1017. /// </para>
  1018. /// <para>
  1019. /// It specifies the HTTP status code.
  1020. /// </para>
  1021. /// </param>
  1022. public static string GetDescription (this HttpStatusCode code)
  1023. {
  1024. return ((int) code).GetStatusDescription ();
  1025. }
  1026. /// <summary>
  1027. /// Gets the description of the specified HTTP status code.
  1028. /// </summary>
  1029. /// <returns>
  1030. /// <para>
  1031. /// A <see cref="string"/> that represents the description of
  1032. /// the HTTP status code.
  1033. /// </para>
  1034. /// <para>
  1035. /// An empty string if the description is not present.
  1036. /// </para>
  1037. /// </returns>
  1038. /// <param name="code">
  1039. /// An <see cref="int"/> that specifies the HTTP status code.
  1040. /// </param>
  1041. public static string GetStatusDescription (this int code)
  1042. {
  1043. switch (code) {
  1044. case 100: return "Continue";
  1045. case 101: return "Switching Protocols";
  1046. case 102: return "Processing";
  1047. case 200: return "OK";
  1048. case 201: return "Created";
  1049. case 202: return "Accepted";
  1050. case 203: return "Non-Authoritative Information";
  1051. case 204: return "No Content";
  1052. case 205: return "Reset Content";
  1053. case 206: return "Partial Content";
  1054. case 207: return "Multi-Status";
  1055. case 300: return "Multiple Choices";
  1056. case 301: return "Moved Permanently";
  1057. case 302: return "Found";
  1058. case 303: return "See Other";
  1059. case 304: return "Not Modified";
  1060. case 305: return "Use Proxy";
  1061. case 307: return "Temporary Redirect";
  1062. case 400: return "Bad Request";
  1063. case 401: return "Unauthorized";
  1064. case 402: return "Payment Required";
  1065. case 403: return "Forbidden";
  1066. case 404: return "Not Found";
  1067. case 405: return "Method Not Allowed";
  1068. case 406: return "Not Acceptable";
  1069. case 407: return "Proxy Authentication Required";
  1070. case 408: return "Request Timeout";
  1071. case 409: return "Conflict";
  1072. case 410: return "Gone";
  1073. case 411: return "Length Required";
  1074. case 412: return "Precondition Failed";
  1075. case 413: return "Request Entity Too Large";
  1076. case 414: return "Request-Uri Too Long";
  1077. case 415: return "Unsupported Media Type";
  1078. case 416: return "Requested Range Not Satisfiable";
  1079. case 417: return "Expectation Failed";
  1080. case 422: return "Unprocessable Entity";
  1081. case 423: return "Locked";
  1082. case 424: return "Failed Dependency";
  1083. case 500: return "Internal Server Error";
  1084. case 501: return "Not Implemented";
  1085. case 502: return "Bad Gateway";
  1086. case 503: return "Service Unavailable";
  1087. case 504: return "Gateway Timeout";
  1088. case 505: return "Http Version Not Supported";
  1089. case 507: return "Insufficient Storage";
  1090. }
  1091. return String.Empty;
  1092. }
  1093. /// <summary>
  1094. /// Determines whether the specified ushort is in the range of
  1095. /// the status code for the WebSocket connection close.
  1096. /// </summary>
  1097. /// <remarks>
  1098. /// <para>
  1099. /// The ranges are the following:
  1100. /// </para>
  1101. /// <list type="bullet">
  1102. /// <item>
  1103. /// <term>
  1104. /// 1000-2999: These numbers are reserved for definition by
  1105. /// the WebSocket protocol.
  1106. /// </term>
  1107. /// </item>
  1108. /// <item>
  1109. /// <term>
  1110. /// 3000-3999: These numbers are reserved for use by libraries,
  1111. /// frameworks, and applications.
  1112. /// </term>
  1113. /// </item>
  1114. /// <item>
  1115. /// <term>
  1116. /// 4000-4999: These numbers are reserved for private use.
  1117. /// </term>
  1118. /// </item>
  1119. /// </list>
  1120. /// </remarks>
  1121. /// <returns>
  1122. /// <c>true</c> if <paramref name="value"/> is in the range of
  1123. /// the status code for the close; otherwise, <c>false</c>.
  1124. /// </returns>
  1125. /// <param name="value">
  1126. /// A <see cref="ushort"/> to test.
  1127. /// </param>
  1128. public static bool IsCloseStatusCode (this ushort value)
  1129. {
  1130. return value > 999 && value < 5000;
  1131. }
  1132. /// <summary>
  1133. /// Determines whether the specified string is enclosed in
  1134. /// the specified character.
  1135. /// </summary>
  1136. /// <returns>
  1137. /// <c>true</c> if <paramref name="value"/> is enclosed in
  1138. /// <paramref name="c"/>; otherwise, <c>false</c>.
  1139. /// </returns>
  1140. /// <param name="value">
  1141. /// A <see cref="string"/> to test.
  1142. /// </param>
  1143. /// <param name="c">
  1144. /// A <see cref="char"/> to find.
  1145. /// </param>
  1146. public static bool IsEnclosedIn (this string value, char c)
  1147. {
  1148. if (value == null)
  1149. return false;
  1150. var len = value.Length;
  1151. return len > 1 ? value[0] == c && value[len - 1] == c : false;
  1152. }
  1153. /// <summary>
  1154. /// Determines whether the specified byte order is host (this computer
  1155. /// architecture) byte order.
  1156. /// </summary>
  1157. /// <returns>
  1158. /// <c>true</c> if <paramref name="order"/> is host byte order; otherwise,
  1159. /// <c>false</c>.
  1160. /// </returns>
  1161. /// <param name="order">
  1162. /// One of the <see cref="ByteOrder"/> enum values to test.
  1163. /// </param>
  1164. public static bool IsHostOrder (this ByteOrder order)
  1165. {
  1166. // true: !(true ^ true) or !(false ^ false)
  1167. // false: !(true ^ false) or !(false ^ true)
  1168. return !(BitConverter.IsLittleEndian ^ (order == ByteOrder.Little));
  1169. }
  1170. /// <summary>
  1171. /// Determines whether the specified IP address is a local IP address.
  1172. /// </summary>
  1173. /// <remarks>
  1174. /// This local means NOT REMOTE for the current host.
  1175. /// </remarks>
  1176. /// <returns>
  1177. /// <c>true</c> if <paramref name="address"/> is a local IP address;
  1178. /// otherwise, <c>false</c>.
  1179. /// </returns>
  1180. /// <param name="address">
  1181. /// A <see cref="System.Net.IPAddress"/> to test.
  1182. /// </param>
  1183. /// <exception cref="ArgumentNullException">
  1184. /// <paramref name="address"/> is <see langword="null"/>.
  1185. /// </exception>
  1186. public static bool IsLocal (this System.Net.IPAddress address)
  1187. {
  1188. if (address == null)
  1189. throw new ArgumentNullException ("address");
  1190. if (address.Equals (System.Net.IPAddress.Any))
  1191. return true;
  1192. if (address.Equals (System.Net.IPAddress.Loopback))
  1193. return true;
  1194. if (Socket.OSSupportsIPv6) {
  1195. if (address.Equals (System.Net.IPAddress.IPv6Any))
  1196. return true;
  1197. if (address.Equals (System.Net.IPAddress.IPv6Loopback))
  1198. return true;
  1199. }
  1200. var name = System.Net.Dns.GetHostName ();
  1201. var addrs = System.Net.Dns.GetHostAddresses (name);
  1202. foreach (var addr in addrs) {
  1203. if (address.Equals (addr))
  1204. return true;
  1205. }
  1206. return false;
  1207. }
  1208. /// <summary>
  1209. /// Determines whether the specified string is <see langword="null"/> or
  1210. /// an empty string.
  1211. /// </summary>
  1212. /// <returns>
  1213. /// <c>true</c> if <paramref name="value"/> is <see langword="null"/> or
  1214. /// an empty string; otherwise, <c>false</c>.
  1215. /// </returns>
  1216. /// <param name="value">
  1217. /// A <see cref="string"/> to test.
  1218. /// </param>
  1219. public static bool IsNullOrEmpty (this string value)
  1220. {
  1221. return value == null || value.Length == 0;
  1222. }
  1223. /// <summary>
  1224. /// Retrieves a sub-array from the specified array. A sub-array starts at
  1225. /// the specified index in the array.
  1226. /// </summary>
  1227. /// <returns>
  1228. /// An array of T that receives a sub-array.
  1229. /// </returns>
  1230. /// <param name="array">
  1231. /// An array of T from which to retrieve a sub-array.
  1232. /// </param>
  1233. /// <param name="startIndex">
  1234. /// An <see cref="int"/> that specifies the zero-based index in the array
  1235. /// at which retrieving starts.
  1236. /// </param>
  1237. /// <param name="length">
  1238. /// An <see cref="int"/> that specifies the number of elements to retrieve.
  1239. /// </param>
  1240. /// <typeparam name="T">
  1241. /// The type of elements in the array.
  1242. /// </typeparam>
  1243. /// <exception cref="ArgumentNullException">
  1244. /// <paramref name="array"/> is <see langword="null"/>.
  1245. /// </exception>
  1246. /// <exception cref="ArgumentOutOfRangeException">
  1247. /// <para>
  1248. /// <paramref name="startIndex"/> is less than zero.
  1249. /// </para>
  1250. /// <para>
  1251. /// -or-
  1252. /// </para>
  1253. /// <para>
  1254. /// <paramref name="startIndex"/> is greater than the end of the array.
  1255. /// </para>
  1256. /// <para>
  1257. /// -or-
  1258. /// </para>
  1259. /// <para>
  1260. /// <paramref name="length"/> is less than zero.
  1261. /// </para>
  1262. /// <para>
  1263. /// -or-
  1264. /// </para>
  1265. /// <para>
  1266. /// <paramref name="length"/> is greater than the number of elements from
  1267. /// <paramref name="startIndex"/> to the end of the array.
  1268. /// </para>
  1269. /// </exception>
  1270. public static T[] SubArray<T> (this T[] array, int startIndex, int length)
  1271. {
  1272. if (array == null)
  1273. throw new ArgumentNullException ("array");
  1274. var len = array.Length;
  1275. if (len == 0) {
  1276. if (startIndex != 0)
  1277. throw new ArgumentOutOfRangeException ("startIndex");
  1278. if (length != 0)
  1279. throw new ArgumentOutOfRangeException ("length");
  1280. return array;
  1281. }
  1282. if (startIndex < 0 || startIndex >= len)
  1283. throw new ArgumentOutOfRangeException ("startIndex");
  1284. if (length < 0 || length > len - startIndex)
  1285. throw new ArgumentOutOfRangeException ("length");
  1286. if (length == 0)
  1287. return new T[0];
  1288. if (length == len)
  1289. return array;
  1290. var ret = new T[length];
  1291. Array.Copy (array, startIndex, ret, 0, length);
  1292. return ret;
  1293. }
  1294. /// <summary>
  1295. /// Retrieves a sub-array from the specified array. A sub-array starts at
  1296. /// the specified index in the array.
  1297. /// </summary>
  1298. /// <returns>
  1299. /// An array of T that receives a sub-array.
  1300. /// </returns>
  1301. /// <param name="array">
  1302. /// An array of T from which to retrieve a sub-array.
  1303. /// </param>
  1304. /// <param name="startIndex">
  1305. /// A <see cref="long"/> that specifies the zero-based index in the array
  1306. /// at which retrieving starts.
  1307. /// </param>
  1308. /// <param name="length">
  1309. /// A <see cref="long"/> that specifies the number of elements to retrieve.
  1310. /// </param>
  1311. /// <typeparam name="T">
  1312. /// The type of elements in the array.
  1313. /// </typeparam>
  1314. /// <exception cref="ArgumentNullException">
  1315. /// <paramref name="array"/> is <see langword="null"/>.
  1316. /// </exception>
  1317. /// <exception cref="ArgumentOutOfRangeException">
  1318. /// <para>
  1319. /// <paramref name="startIndex"/> is less than zero.
  1320. /// </para>
  1321. /// <para>
  1322. /// -or-
  1323. /// </para>
  1324. /// <para>
  1325. /// <paramref name="startIndex"/> is greater than the end of the array.
  1326. /// </para>
  1327. /// <para>
  1328. /// -or-
  1329. /// </para>
  1330. /// <para>
  1331. /// <paramref name="length"/> is less than zero.
  1332. /// </para>
  1333. /// <para>
  1334. /// -or-
  1335. /// </para>
  1336. /// <para>
  1337. /// <paramref name="length"/> is greater than the number of elements from
  1338. /// <paramref name="startIndex"/> to the end of the array.
  1339. /// </para>
  1340. /// </exception>
  1341. public static T[] SubArray<T> (this T[] array, long startIndex, long length)
  1342. {
  1343. if (array == null)
  1344. throw new ArgumentNullException ("array");
  1345. var len = array.LongLength;
  1346. if (len == 0) {
  1347. if (startIndex != 0)
  1348. throw new ArgumentOutOfRangeException ("startIndex");
  1349. if (length != 0)
  1350. throw new ArgumentOutOfRangeException ("length");
  1351. return array;
  1352. }
  1353. if (startIndex < 0 || startIndex >= len)
  1354. throw new ArgumentOutOfRangeException ("startIndex");
  1355. if (length < 0 || length > len - startIndex)
  1356. throw new ArgumentOutOfRangeException ("length");
  1357. if (length == 0)
  1358. return new T[0];
  1359. if (length == len)
  1360. return array;
  1361. var ret = new T[length];
  1362. Array.Copy (array, startIndex, ret, 0, length);
  1363. return ret;
  1364. }
  1365. /// <summary>
  1366. /// Executes the specified delegate <paramref name="n"/> times.
  1367. /// </summary>
  1368. /// <param name="n">
  1369. /// An <see cref="int"/> that specifies the number of times to execute.
  1370. /// </param>
  1371. /// <param name="action">
  1372. /// <para>
  1373. /// An <c>Action&lt;int&gt;</c> delegate to execute.
  1374. /// </para>
  1375. /// <para>
  1376. /// The <see cref="int"/> parameter is the zero-based count of iteration.
  1377. /// </para>
  1378. /// </param>
  1379. public static void Times (this int n, Action<int> action)
  1380. {
  1381. if (n <= 0)
  1382. return;
  1383. if (action == null)
  1384. return;
  1385. for (int i = 0; i < n; i++)
  1386. action (i);
  1387. }
  1388. /// <summary>
  1389. /// Executes the specified delegate <paramref name="n"/> times.
  1390. /// </summary>
  1391. /// <param name="n">
  1392. /// A <see cref="long"/> that specifies the number of times to execute.
  1393. /// </param>
  1394. /// <param name="action">
  1395. /// <para>
  1396. /// An <c>Action&lt;long&gt;</c> delegate to execute.
  1397. /// </para>
  1398. /// <para>
  1399. /// The <see cref="long"/> parameter is the zero-based count of iteration.
  1400. /// </para>
  1401. /// </param>
  1402. public static void Times (this long n, Action<long> action)
  1403. {
  1404. if (n <= 0)
  1405. return;
  1406. if (action == null)
  1407. return;
  1408. for (long i = 0; i < n; i++)
  1409. action (i);
  1410. }
  1411. /// <summary>
  1412. /// Converts the order of elements in the specified byte array to
  1413. /// host (this computer architecture) byte order.
  1414. /// </summary>
  1415. /// <returns>
  1416. /// <para>
  1417. /// An array of <see cref="byte"/> converted from
  1418. /// <paramref name="source"/>.
  1419. /// </para>
  1420. /// <para>
  1421. /// <paramref name="source"/> if the number of elements in
  1422. /// it is less than 2 or <paramref name="sourceOrder"/> is
  1423. /// same as host byte order.
  1424. /// </para>
  1425. /// </returns>
  1426. /// <param name="source">
  1427. /// An array of <see cref="byte"/> to convert.
  1428. /// </param>
  1429. /// <param name="sourceOrder">
  1430. /// <para>
  1431. /// One of the <see cref="ByteOrder"/> enum values.
  1432. /// </para>
  1433. /// <para>
  1434. /// It specifies the order of elements in <paramref name="source"/>.
  1435. /// </para>
  1436. /// </param>
  1437. /// <exception cref="ArgumentNullException">
  1438. /// <paramref name="source"/> is <see langword="null"/>.
  1439. /// </exception>
  1440. public static byte[] ToHostOrder (this byte[] source, ByteOrder sourceOrder)
  1441. {
  1442. if (source == null)
  1443. throw new ArgumentNullException ("source");
  1444. if (source.Length < 2)
  1445. return source;
  1446. if (sourceOrder.IsHostOrder ())
  1447. return source;
  1448. return source.Reverse ();
  1449. }
  1450. /// <summary>
  1451. /// Converts the specified array to a string.
  1452. /// </summary>
  1453. /// <returns>
  1454. /// <para>
  1455. /// A <see cref="string"/> converted by concatenating each element of
  1456. /// <paramref name="array"/> across <paramref name="separator"/>.
  1457. /// </para>
  1458. /// <para>
  1459. /// An empty string if <paramref name="array"/> is an empty array.
  1460. /// </para>
  1461. /// </returns>
  1462. /// <param name="array">
  1463. /// An array of T to convert.
  1464. /// </param>
  1465. /// <param name="separator">
  1466. /// A <see cref="string"/> used to separate each element of
  1467. /// <paramref name="array"/>.
  1468. /// </param>
  1469. /// <typeparam name="T">
  1470. /// The type of elements in <paramref name="array"/>.
  1471. /// </typeparam>
  1472. /// <exception cref="ArgumentNullException">
  1473. /// <paramref name="array"/> is <see langword="null"/>.
  1474. /// </exception>
  1475. public static string ToString<T> (this T[] array, string separator)
  1476. {
  1477. if (array == null)
  1478. throw new ArgumentNullException ("array");
  1479. var len = array.Length;
  1480. if (len == 0)
  1481. return String.Empty;
  1482. var buff = new StringBuilder (64);
  1483. var end = len - 1;
  1484. for (var i = 0; i < end; i++)
  1485. buff.AppendFormat ("{0}{1}", array[i], separator);
  1486. buff.AppendFormat ("{0}", array[end]);
  1487. return buff.ToString ();
  1488. }
  1489. /// <summary>
  1490. /// Converts the specified string to a <see cref="Uri"/>.
  1491. /// </summary>
  1492. /// <returns>
  1493. /// <para>
  1494. /// A <see cref="Uri"/> converted from <paramref name="value"/>.
  1495. /// </para>
  1496. /// <para>
  1497. /// <see langword="null"/> if the conversion has failed.
  1498. /// </para>
  1499. /// </returns>
  1500. /// <param name="value">
  1501. /// A <see cref="string"/> to convert.
  1502. /// </param>
  1503. public static Uri ToUri (this string value)
  1504. {
  1505. if (value == null || value.Length == 0)
  1506. return null;
  1507. var kind = value.MaybeUri () ? UriKind.Absolute : UriKind.Relative;
  1508. Uri ret;
  1509. Uri.TryCreate (value, kind, out ret);
  1510. return ret;
  1511. }
  1512. #endregion
  1513. }
  1514. }