Convert.cs 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Globalization;
  6. using System.Threading;
  7. using System.Reflection;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. using System.Runtime.Versioning;
  11. using System.Security;
  12. using System.Diagnostics;
  13. namespace System
  14. {
  15. [Flags]
  16. public enum Base64FormattingOptions
  17. {
  18. None = 0,
  19. InsertLineBreaks = 1
  20. }
  21. // Returns the type code of this object. An implementation of this method
  22. // must not return TypeCode.Empty (which represents a null reference) or
  23. // TypeCode.Object (which represents an object that doesn't implement the
  24. // IConvertible interface). An implementation of this method should return
  25. // TypeCode.DBNull if the value of this object is a database null. For
  26. // example, a nullable integer type should return TypeCode.DBNull if the
  27. // value of the object is the database null. Otherwise, an implementation
  28. // of this method should return the TypeCode that best describes the
  29. // internal representation of the object.
  30. // The Value class provides conversion and querying methods for values. The
  31. // Value class contains static members only, and it is not possible to create
  32. // instances of the class.
  33. //
  34. // The statically typed conversion methods provided by the Value class are all
  35. // of the form:
  36. //
  37. // public static XXX ToXXX(YYY value)
  38. //
  39. // where XXX is the target type and YYY is the source type. The matrix below
  40. // shows the set of supported conversions. The set of conversions is symmetric
  41. // such that for every ToXXX(YYY) there is also a ToYYY(XXX).
  42. //
  43. // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Str
  44. // ----------------------------------------------------------------------
  45. // Boolean x x x x x x x x x x x x x
  46. // Char x x x x x x x x x x
  47. // SByte x x x x x x x x x x x x x x
  48. // Byte x x x x x x x x x x x x x x
  49. // Int16 x x x x x x x x x x x x x x
  50. // UInt16 x x x x x x x x x x x x x x
  51. // Int32 x x x x x x x x x x x x x x
  52. // UInt32 x x x x x x x x x x x x x x
  53. // Int64 x x x x x x x x x x x x x x
  54. // UInt64 x x x x x x x x x x x x x x
  55. // Single x x x x x x x x x x x x x
  56. // Double x x x x x x x x x x x x x
  57. // Decimal x x x x x x x x x x x x x
  58. // DateTime x x
  59. // String x x x x x x x x x x x x x x x
  60. // ----------------------------------------------------------------------
  61. //
  62. // For dynamic conversions, the Value class provides a set of methods of the
  63. // form:
  64. //
  65. // public static XXX ToXXX(object value)
  66. //
  67. // where XXX is the target type (Boolean, Char, SByte, Byte, Int16, UInt16,
  68. // Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime,
  69. // or String). The implementations of these methods all take the form:
  70. //
  71. // public static XXX toXXX(object value) {
  72. // return value == null? XXX.Default: ((IConvertible)value).ToXXX();
  73. // }
  74. //
  75. // The code first checks if the given value is a null reference (which is the
  76. // same as Value.Empty), in which case it returns the default value for type
  77. // XXX. Otherwise, a cast to IConvertible is performed, and the appropriate ToXXX()
  78. // method is invoked on the object. An InvalidCastException is thrown if the
  79. // cast to IConvertible fails, and that exception is simply allowed to propagate out
  80. // of the conversion method.
  81. // Constant representing the database null value. This value is used in
  82. // database applications to indicate the absence of a known value. Note
  83. // that Value.DBNull is NOT the same as a null object reference, which is
  84. // represented by Value.Empty.
  85. //
  86. // The Equals() method of DBNull always returns false, even when the
  87. // argument is itself DBNull.
  88. //
  89. // When passed Value.DBNull, the Value.GetTypeCode() method returns
  90. // TypeCode.DBNull.
  91. //
  92. // When passed Value.DBNull, the Value.ToXXX() methods all throw an
  93. // InvalidCastException.
  94. public static partial class Convert
  95. {
  96. //A typeof operation is fairly expensive (does a system call), so we'll cache these here
  97. //statically. These are exactly lined up with the TypeCode, eg. ConvertType[TypeCode.Int16]
  98. //will give you the type of an short.
  99. internal static readonly Type[] ConvertTypes = {
  100. typeof(System.Empty),
  101. typeof(object),
  102. typeof(System.DBNull),
  103. typeof(bool),
  104. typeof(char),
  105. typeof(sbyte),
  106. typeof(byte),
  107. typeof(short),
  108. typeof(ushort),
  109. typeof(int),
  110. typeof(uint),
  111. typeof(long),
  112. typeof(ulong),
  113. typeof(float),
  114. typeof(double),
  115. typeof(decimal),
  116. typeof(DateTime),
  117. typeof(object), //TypeCode is discontinuous so we need a placeholder.
  118. typeof(string)
  119. };
  120. // Need to special case Enum because typecode will be underlying type, e.g. Int32
  121. private static readonly Type EnumType = typeof(Enum);
  122. internal static readonly char[] base64Table = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
  123. 'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d',
  124. 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',
  125. 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7',
  126. '8','9','+','/','=' };
  127. private const int base64LineBreakPosition = 76;
  128. #if DEBUG
  129. private static bool TriggerAsserts = DoAsserts();
  130. private static bool DoAsserts()
  131. {
  132. Debug.Assert(ConvertTypes != null, "[Convert.cctor]ConvertTypes!=null");
  133. Debug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)");
  134. Debug.Assert(ConvertTypes[(int)TypeCode.Empty] == typeof(System.Empty),
  135. "[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)");
  136. Debug.Assert(ConvertTypes[(int)TypeCode.String] == typeof(string),
  137. "[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)");
  138. Debug.Assert(ConvertTypes[(int)TypeCode.Int32] == typeof(int),
  139. "[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)");
  140. return true;
  141. }
  142. #endif
  143. public static readonly object DBNull = System.DBNull.Value;
  144. // Returns the type code for the given object. If the argument is null,
  145. // the result is TypeCode.Empty. If the argument is not a value (i.e. if
  146. // the object does not implement IConvertible), the result is TypeCode.Object.
  147. // Otherwise, the result is the type code of the object, as determined by
  148. // the object's implementation of IConvertible.
  149. public static TypeCode GetTypeCode(object value)
  150. {
  151. if (value == null) return TypeCode.Empty;
  152. IConvertible temp = value as IConvertible;
  153. if (temp != null)
  154. {
  155. return temp.GetTypeCode();
  156. }
  157. return TypeCode.Object;
  158. }
  159. // Returns true if the given object is a database null. This operation
  160. // corresponds to "value.GetTypeCode() == TypeCode.DBNull".
  161. public static bool IsDBNull(object value)
  162. {
  163. if (value == System.DBNull.Value) return true;
  164. IConvertible convertible = value as IConvertible;
  165. return convertible != null ? convertible.GetTypeCode() == TypeCode.DBNull : false;
  166. }
  167. // Converts the given object to the given type. In general, this method is
  168. // equivalent to calling the Value.ToXXX(value) method for the given
  169. // typeCode and boxing the result.
  170. //
  171. // The method first checks if the given object implements IConvertible. If not,
  172. // the only permitted conversion is from a null to TypeCode.Empty, the
  173. // result of which is null.
  174. //
  175. // If the object does implement IConvertible, a check is made to see if the
  176. // object already has the given type code, in which case the object is
  177. // simply returned. Otherwise, the appropriate ToXXX() is invoked on the
  178. // object's implementation of IConvertible.
  179. public static object ChangeType(object value, TypeCode typeCode)
  180. {
  181. return ChangeType(value, typeCode, CultureInfo.CurrentCulture);
  182. }
  183. public static object ChangeType(object value, TypeCode typeCode, IFormatProvider provider)
  184. {
  185. if (value == null && (typeCode == TypeCode.Empty || typeCode == TypeCode.String || typeCode == TypeCode.Object))
  186. {
  187. return null;
  188. }
  189. IConvertible v = value as IConvertible;
  190. if (v == null)
  191. {
  192. throw new InvalidCastException(SR.InvalidCast_IConvertible);
  193. }
  194. // This line is invalid for things like Enums that return a TypeCode
  195. // of int, but the object can't actually be cast to an int.
  196. // if (v.GetTypeCode() == typeCode) return value;
  197. switch (typeCode)
  198. {
  199. case TypeCode.Boolean:
  200. return v.ToBoolean(provider);
  201. case TypeCode.Char:
  202. return v.ToChar(provider);
  203. case TypeCode.SByte:
  204. return v.ToSByte(provider);
  205. case TypeCode.Byte:
  206. return v.ToByte(provider);
  207. case TypeCode.Int16:
  208. return v.ToInt16(provider);
  209. case TypeCode.UInt16:
  210. return v.ToUInt16(provider);
  211. case TypeCode.Int32:
  212. return v.ToInt32(provider);
  213. case TypeCode.UInt32:
  214. return v.ToUInt32(provider);
  215. case TypeCode.Int64:
  216. return v.ToInt64(provider);
  217. case TypeCode.UInt64:
  218. return v.ToUInt64(provider);
  219. case TypeCode.Single:
  220. return v.ToSingle(provider);
  221. case TypeCode.Double:
  222. return v.ToDouble(provider);
  223. case TypeCode.Decimal:
  224. return v.ToDecimal(provider);
  225. case TypeCode.DateTime:
  226. return v.ToDateTime(provider);
  227. case TypeCode.String:
  228. return v.ToString(provider);
  229. case TypeCode.Object:
  230. return value;
  231. case TypeCode.DBNull:
  232. throw new InvalidCastException(SR.InvalidCast_DBNull);
  233. case TypeCode.Empty:
  234. throw new InvalidCastException(SR.InvalidCast_Empty);
  235. default:
  236. throw new ArgumentException(SR.Arg_UnknownTypeCode);
  237. }
  238. }
  239. internal static object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
  240. {
  241. Debug.Assert(value != null, "[Convert.DefaultToType]value!=null");
  242. if (targetType == null)
  243. {
  244. throw new ArgumentNullException(nameof(targetType));
  245. }
  246. if (ReferenceEquals(value.GetType(), targetType))
  247. {
  248. return value;
  249. }
  250. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Boolean]))
  251. return value.ToBoolean(provider);
  252. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Char]))
  253. return value.ToChar(provider);
  254. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.SByte]))
  255. return value.ToSByte(provider);
  256. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Byte]))
  257. return value.ToByte(provider);
  258. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Int16]))
  259. return value.ToInt16(provider);
  260. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.UInt16]))
  261. return value.ToUInt16(provider);
  262. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Int32]))
  263. return value.ToInt32(provider);
  264. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.UInt32]))
  265. return value.ToUInt32(provider);
  266. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Int64]))
  267. return value.ToInt64(provider);
  268. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.UInt64]))
  269. return value.ToUInt64(provider);
  270. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Single]))
  271. return value.ToSingle(provider);
  272. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Double]))
  273. return value.ToDouble(provider);
  274. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Decimal]))
  275. return value.ToDecimal(provider);
  276. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.DateTime]))
  277. return value.ToDateTime(provider);
  278. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.String]))
  279. return value.ToString(provider);
  280. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Object]))
  281. return (object)value;
  282. // Need to special case Enum because typecode will be underlying type, e.g. Int32
  283. if (ReferenceEquals(targetType, EnumType))
  284. return (Enum)value;
  285. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.DBNull]))
  286. throw new InvalidCastException(SR.InvalidCast_DBNull);
  287. if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Empty]))
  288. throw new InvalidCastException(SR.InvalidCast_Empty);
  289. throw new InvalidCastException(string.Format(SR.InvalidCast_FromTo, value.GetType().FullName, targetType.FullName));
  290. }
  291. public static object ChangeType(object value, Type conversionType)
  292. {
  293. return ChangeType(value, conversionType, CultureInfo.CurrentCulture);
  294. }
  295. public static object ChangeType(object value, Type conversionType, IFormatProvider provider)
  296. {
  297. if (conversionType is null)
  298. {
  299. throw new ArgumentNullException(nameof(conversionType));
  300. }
  301. if (value == null)
  302. {
  303. if (conversionType.IsValueType)
  304. {
  305. throw new InvalidCastException(SR.InvalidCast_CannotCastNullToValueType);
  306. }
  307. return null;
  308. }
  309. IConvertible ic = value as IConvertible;
  310. if (ic == null)
  311. {
  312. if (value.GetType() == conversionType)
  313. {
  314. return value;
  315. }
  316. throw new InvalidCastException(SR.InvalidCast_IConvertible);
  317. }
  318. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Boolean]))
  319. return ic.ToBoolean(provider);
  320. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Char]))
  321. return ic.ToChar(provider);
  322. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.SByte]))
  323. return ic.ToSByte(provider);
  324. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Byte]))
  325. return ic.ToByte(provider);
  326. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Int16]))
  327. return ic.ToInt16(provider);
  328. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.UInt16]))
  329. return ic.ToUInt16(provider);
  330. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Int32]))
  331. return ic.ToInt32(provider);
  332. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.UInt32]))
  333. return ic.ToUInt32(provider);
  334. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Int64]))
  335. return ic.ToInt64(provider);
  336. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.UInt64]))
  337. return ic.ToUInt64(provider);
  338. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Single]))
  339. return ic.ToSingle(provider);
  340. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Double]))
  341. return ic.ToDouble(provider);
  342. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Decimal]))
  343. return ic.ToDecimal(provider);
  344. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.DateTime]))
  345. return ic.ToDateTime(provider);
  346. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.String]))
  347. return ic.ToString(provider);
  348. if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Object]))
  349. return (object)value;
  350. return ic.ToType(conversionType, provider);
  351. }
  352. private static void ThrowCharOverflowException() { throw new OverflowException(SR.Overflow_Char); }
  353. private static void ThrowByteOverflowException() { throw new OverflowException(SR.Overflow_Byte); }
  354. private static void ThrowSByteOverflowException() { throw new OverflowException(SR.Overflow_SByte); }
  355. private static void ThrowInt16OverflowException() { throw new OverflowException(SR.Overflow_Int16); }
  356. private static void ThrowUInt16OverflowException() { throw new OverflowException(SR.Overflow_UInt16); }
  357. private static void ThrowInt32OverflowException() { throw new OverflowException(SR.Overflow_Int32); }
  358. private static void ThrowUInt32OverflowException() { throw new OverflowException(SR.Overflow_UInt32); }
  359. private static void ThrowInt64OverflowException() { throw new OverflowException(SR.Overflow_Int64); }
  360. private static void ThrowUInt64OverflowException() { throw new OverflowException(SR.Overflow_UInt64); }
  361. // Conversions to Boolean
  362. public static bool ToBoolean(object value)
  363. {
  364. return value == null ? false : ((IConvertible)value).ToBoolean(null);
  365. }
  366. public static bool ToBoolean(object value, IFormatProvider provider)
  367. {
  368. return value == null ? false : ((IConvertible)value).ToBoolean(provider);
  369. }
  370. public static bool ToBoolean(bool value)
  371. {
  372. return value;
  373. }
  374. [CLSCompliant(false)]
  375. public static bool ToBoolean(sbyte value)
  376. {
  377. return value != 0;
  378. }
  379. // To be consistent with IConvertible in the base data types else we get different semantics
  380. // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
  381. public static bool ToBoolean(char value)
  382. {
  383. return ((IConvertible)value).ToBoolean(null);
  384. }
  385. public static bool ToBoolean(byte value)
  386. {
  387. return value != 0;
  388. }
  389. public static bool ToBoolean(short value)
  390. {
  391. return value != 0;
  392. }
  393. [CLSCompliant(false)]
  394. public static bool ToBoolean(ushort value)
  395. {
  396. return value != 0;
  397. }
  398. public static bool ToBoolean(int value)
  399. {
  400. return value != 0;
  401. }
  402. [CLSCompliant(false)]
  403. public static bool ToBoolean(uint value)
  404. {
  405. return value != 0;
  406. }
  407. public static bool ToBoolean(long value)
  408. {
  409. return value != 0;
  410. }
  411. [CLSCompliant(false)]
  412. public static bool ToBoolean(ulong value)
  413. {
  414. return value != 0;
  415. }
  416. public static bool ToBoolean(string value)
  417. {
  418. if (value == null)
  419. return false;
  420. return bool.Parse(value);
  421. }
  422. public static bool ToBoolean(string value, IFormatProvider provider)
  423. {
  424. if (value == null)
  425. return false;
  426. return bool.Parse(value);
  427. }
  428. public static bool ToBoolean(float value)
  429. {
  430. return value != 0;
  431. }
  432. public static bool ToBoolean(double value)
  433. {
  434. return value != 0;
  435. }
  436. public static bool ToBoolean(decimal value)
  437. {
  438. return value != 0;
  439. }
  440. public static bool ToBoolean(DateTime value)
  441. {
  442. return ((IConvertible)value).ToBoolean(null);
  443. }
  444. // Disallowed conversions to Boolean
  445. // public static bool ToBoolean(TimeSpan value)
  446. // Conversions to Char
  447. public static char ToChar(object value)
  448. {
  449. return value == null ? (char)0 : ((IConvertible)value).ToChar(null);
  450. }
  451. public static char ToChar(object value, IFormatProvider provider)
  452. {
  453. return value == null ? (char)0 : ((IConvertible)value).ToChar(provider);
  454. }
  455. public static char ToChar(bool value)
  456. {
  457. return ((IConvertible)value).ToChar(null);
  458. }
  459. public static char ToChar(char value)
  460. {
  461. return value;
  462. }
  463. [CLSCompliant(false)]
  464. public static char ToChar(sbyte value)
  465. {
  466. if (value < 0) ThrowCharOverflowException();
  467. return (char)value;
  468. }
  469. public static char ToChar(byte value)
  470. {
  471. return (char)value;
  472. }
  473. public static char ToChar(short value)
  474. {
  475. if (value < 0) ThrowCharOverflowException();
  476. return (char)value;
  477. }
  478. [CLSCompliant(false)]
  479. public static char ToChar(ushort value)
  480. {
  481. return (char)value;
  482. }
  483. public static char ToChar(int value)
  484. {
  485. if (value < 0 || value > char.MaxValue) ThrowCharOverflowException();
  486. return (char)value;
  487. }
  488. [CLSCompliant(false)]
  489. public static char ToChar(uint value)
  490. {
  491. if (value > char.MaxValue) ThrowCharOverflowException();
  492. return (char)value;
  493. }
  494. public static char ToChar(long value)
  495. {
  496. if (value < 0 || value > char.MaxValue) ThrowCharOverflowException();
  497. return (char)value;
  498. }
  499. [CLSCompliant(false)]
  500. public static char ToChar(ulong value)
  501. {
  502. if (value > char.MaxValue) ThrowCharOverflowException();
  503. return (char)value;
  504. }
  505. //
  506. // @VariantSwitch
  507. // Remove FormatExceptions;
  508. //
  509. public static char ToChar(string value)
  510. {
  511. return ToChar(value, null);
  512. }
  513. public static char ToChar(string value, IFormatProvider provider)
  514. {
  515. if (value == null)
  516. throw new ArgumentNullException(nameof(value));
  517. if (value.Length != 1)
  518. throw new FormatException(SR.Format_NeedSingleChar);
  519. return value[0];
  520. }
  521. // To be consistent with IConvertible in the base data types else we get different semantics
  522. // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
  523. public static char ToChar(float value)
  524. {
  525. return ((IConvertible)value).ToChar(null);
  526. }
  527. // To be consistent with IConvertible in the base data types else we get different semantics
  528. // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
  529. public static char ToChar(double value)
  530. {
  531. return ((IConvertible)value).ToChar(null);
  532. }
  533. // To be consistent with IConvertible in the base data types else we get different semantics
  534. // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
  535. public static char ToChar(decimal value)
  536. {
  537. return ((IConvertible)value).ToChar(null);
  538. }
  539. public static char ToChar(DateTime value)
  540. {
  541. return ((IConvertible)value).ToChar(null);
  542. }
  543. // Disallowed conversions to Char
  544. // public static char ToChar(TimeSpan value)
  545. // Conversions to SByte
  546. [CLSCompliant(false)]
  547. public static sbyte ToSByte(object value)
  548. {
  549. return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte(null);
  550. }
  551. [CLSCompliant(false)]
  552. public static sbyte ToSByte(object value, IFormatProvider provider)
  553. {
  554. return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte(provider);
  555. }
  556. [CLSCompliant(false)]
  557. public static sbyte ToSByte(bool value)
  558. {
  559. return value ? (sbyte)bool.True : (sbyte)bool.False;
  560. }
  561. [CLSCompliant(false)]
  562. public static sbyte ToSByte(sbyte value)
  563. {
  564. return value;
  565. }
  566. [CLSCompliant(false)]
  567. public static sbyte ToSByte(char value)
  568. {
  569. if (value > sbyte.MaxValue) ThrowSByteOverflowException();
  570. return (sbyte)value;
  571. }
  572. [CLSCompliant(false)]
  573. public static sbyte ToSByte(byte value)
  574. {
  575. if (value > sbyte.MaxValue) ThrowSByteOverflowException();
  576. return (sbyte)value;
  577. }
  578. [CLSCompliant(false)]
  579. public static sbyte ToSByte(short value)
  580. {
  581. if (value < sbyte.MinValue || value > sbyte.MaxValue) ThrowSByteOverflowException();
  582. return (sbyte)value;
  583. }
  584. [CLSCompliant(false)]
  585. public static sbyte ToSByte(ushort value)
  586. {
  587. if (value > sbyte.MaxValue) ThrowSByteOverflowException();
  588. return (sbyte)value;
  589. }
  590. [CLSCompliant(false)]
  591. public static sbyte ToSByte(int value)
  592. {
  593. if (value < sbyte.MinValue || value > sbyte.MaxValue) ThrowSByteOverflowException();
  594. return (sbyte)value;
  595. }
  596. [CLSCompliant(false)]
  597. public static sbyte ToSByte(uint value)
  598. {
  599. if (value > sbyte.MaxValue) ThrowSByteOverflowException();
  600. return (sbyte)value;
  601. }
  602. [CLSCompliant(false)]
  603. public static sbyte ToSByte(long value)
  604. {
  605. if (value < sbyte.MinValue || value > sbyte.MaxValue) ThrowSByteOverflowException();
  606. return (sbyte)value;
  607. }
  608. [CLSCompliant(false)]
  609. public static sbyte ToSByte(ulong value)
  610. {
  611. if (value > (ulong)sbyte.MaxValue) ThrowSByteOverflowException();
  612. return (sbyte)value;
  613. }
  614. [CLSCompliant(false)]
  615. public static sbyte ToSByte(float value)
  616. {
  617. return ToSByte((double)value);
  618. }
  619. [CLSCompliant(false)]
  620. public static sbyte ToSByte(double value)
  621. {
  622. return ToSByte(ToInt32(value));
  623. }
  624. [CLSCompliant(false)]
  625. public static sbyte ToSByte(decimal value)
  626. {
  627. return decimal.ToSByte(decimal.Round(value, 0));
  628. }
  629. [CLSCompliant(false)]
  630. public static sbyte ToSByte(string value)
  631. {
  632. if (value == null)
  633. return 0;
  634. return sbyte.Parse(value, CultureInfo.CurrentCulture);
  635. }
  636. [CLSCompliant(false)]
  637. public static sbyte ToSByte(string value, IFormatProvider provider)
  638. {
  639. return sbyte.Parse(value, NumberStyles.Integer, provider);
  640. }
  641. [CLSCompliant(false)]
  642. public static sbyte ToSByte(DateTime value)
  643. {
  644. return ((IConvertible)value).ToSByte(null);
  645. }
  646. // Disallowed conversions to SByte
  647. // public static sbyte ToSByte(TimeSpan value)
  648. // Conversions to Byte
  649. public static byte ToByte(object value)
  650. {
  651. return value == null ? (byte)0 : ((IConvertible)value).ToByte(null);
  652. }
  653. public static byte ToByte(object value, IFormatProvider provider)
  654. {
  655. return value == null ? (byte)0 : ((IConvertible)value).ToByte(provider);
  656. }
  657. public static byte ToByte(bool value)
  658. {
  659. return value ? (byte)bool.True : (byte)bool.False;
  660. }
  661. public static byte ToByte(byte value)
  662. {
  663. return value;
  664. }
  665. public static byte ToByte(char value)
  666. {
  667. if (value > byte.MaxValue) ThrowByteOverflowException();
  668. return (byte)value;
  669. }
  670. [CLSCompliant(false)]
  671. public static byte ToByte(sbyte value)
  672. {
  673. if (value < byte.MinValue) ThrowByteOverflowException();
  674. return (byte)value;
  675. }
  676. public static byte ToByte(short value)
  677. {
  678. if (value < byte.MinValue || value > byte.MaxValue) ThrowByteOverflowException();
  679. return (byte)value;
  680. }
  681. [CLSCompliant(false)]
  682. public static byte ToByte(ushort value)
  683. {
  684. if (value > byte.MaxValue) ThrowByteOverflowException();
  685. return (byte)value;
  686. }
  687. public static byte ToByte(int value)
  688. {
  689. if (value < byte.MinValue || value > byte.MaxValue) ThrowByteOverflowException();
  690. return (byte)value;
  691. }
  692. [CLSCompliant(false)]
  693. public static byte ToByte(uint value)
  694. {
  695. if (value > byte.MaxValue) ThrowByteOverflowException();
  696. return (byte)value;
  697. }
  698. public static byte ToByte(long value)
  699. {
  700. if (value < byte.MinValue || value > byte.MaxValue) ThrowByteOverflowException();
  701. return (byte)value;
  702. }
  703. [CLSCompliant(false)]
  704. public static byte ToByte(ulong value)
  705. {
  706. if (value > byte.MaxValue) ThrowByteOverflowException();
  707. return (byte)value;
  708. }
  709. public static byte ToByte(float value)
  710. {
  711. return ToByte((double)value);
  712. }
  713. public static byte ToByte(double value)
  714. {
  715. return ToByte(ToInt32(value));
  716. }
  717. public static byte ToByte(decimal value)
  718. {
  719. return decimal.ToByte(decimal.Round(value, 0));
  720. }
  721. public static byte ToByte(string value)
  722. {
  723. if (value == null)
  724. return 0;
  725. return byte.Parse(value, CultureInfo.CurrentCulture);
  726. }
  727. public static byte ToByte(string value, IFormatProvider provider)
  728. {
  729. if (value == null)
  730. return 0;
  731. return byte.Parse(value, NumberStyles.Integer, provider);
  732. }
  733. public static byte ToByte(DateTime value)
  734. {
  735. return ((IConvertible)value).ToByte(null);
  736. }
  737. // Disallowed conversions to Byte
  738. // public static byte ToByte(TimeSpan value)
  739. // Conversions to Int16
  740. public static short ToInt16(object value)
  741. {
  742. return value == null ? (short)0 : ((IConvertible)value).ToInt16(null);
  743. }
  744. public static short ToInt16(object value, IFormatProvider provider)
  745. {
  746. return value == null ? (short)0 : ((IConvertible)value).ToInt16(provider);
  747. }
  748. public static short ToInt16(bool value)
  749. {
  750. return value ? (short)bool.True : (short)bool.False;
  751. }
  752. public static short ToInt16(char value)
  753. {
  754. if (value > short.MaxValue) ThrowInt16OverflowException();
  755. return (short)value;
  756. }
  757. [CLSCompliant(false)]
  758. public static short ToInt16(sbyte value)
  759. {
  760. return value;
  761. }
  762. public static short ToInt16(byte value)
  763. {
  764. return value;
  765. }
  766. [CLSCompliant(false)]
  767. public static short ToInt16(ushort value)
  768. {
  769. if (value > short.MaxValue) ThrowInt16OverflowException();
  770. return (short)value;
  771. }
  772. public static short ToInt16(int value)
  773. {
  774. if (value < short.MinValue || value > short.MaxValue) ThrowInt16OverflowException();
  775. return (short)value;
  776. }
  777. [CLSCompliant(false)]
  778. public static short ToInt16(uint value)
  779. {
  780. if (value > short.MaxValue) ThrowInt16OverflowException();
  781. return (short)value;
  782. }
  783. public static short ToInt16(short value)
  784. {
  785. return value;
  786. }
  787. public static short ToInt16(long value)
  788. {
  789. if (value < short.MinValue || value > short.MaxValue) ThrowInt16OverflowException();
  790. return (short)value;
  791. }
  792. [CLSCompliant(false)]
  793. public static short ToInt16(ulong value)
  794. {
  795. if (value > (ulong)short.MaxValue) ThrowInt16OverflowException();
  796. return (short)value;
  797. }
  798. public static short ToInt16(float value)
  799. {
  800. return ToInt16((double)value);
  801. }
  802. public static short ToInt16(double value)
  803. {
  804. return ToInt16(ToInt32(value));
  805. }
  806. public static short ToInt16(decimal value)
  807. {
  808. return decimal.ToInt16(decimal.Round(value, 0));
  809. }
  810. public static short ToInt16(string value)
  811. {
  812. if (value == null)
  813. return 0;
  814. return short.Parse(value, CultureInfo.CurrentCulture);
  815. }
  816. public static short ToInt16(string value, IFormatProvider provider)
  817. {
  818. if (value == null)
  819. return 0;
  820. return short.Parse(value, NumberStyles.Integer, provider);
  821. }
  822. public static short ToInt16(DateTime value)
  823. {
  824. return ((IConvertible)value).ToInt16(null);
  825. }
  826. // Disallowed conversions to Int16
  827. // public static short ToInt16(TimeSpan value)
  828. // Conversions to UInt16
  829. [CLSCompliant(false)]
  830. public static ushort ToUInt16(object value)
  831. {
  832. return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16(null);
  833. }
  834. [CLSCompliant(false)]
  835. public static ushort ToUInt16(object value, IFormatProvider provider)
  836. {
  837. return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16(provider);
  838. }
  839. [CLSCompliant(false)]
  840. public static ushort ToUInt16(bool value)
  841. {
  842. return value ? (ushort)bool.True : (ushort)bool.False;
  843. }
  844. [CLSCompliant(false)]
  845. public static ushort ToUInt16(char value)
  846. {
  847. return value;
  848. }
  849. [CLSCompliant(false)]
  850. public static ushort ToUInt16(sbyte value)
  851. {
  852. if (value < 0) ThrowUInt16OverflowException();
  853. return (ushort)value;
  854. }
  855. [CLSCompliant(false)]
  856. public static ushort ToUInt16(byte value)
  857. {
  858. return value;
  859. }
  860. [CLSCompliant(false)]
  861. public static ushort ToUInt16(short value)
  862. {
  863. if (value < 0) ThrowUInt16OverflowException();
  864. return (ushort)value;
  865. }
  866. [CLSCompliant(false)]
  867. public static ushort ToUInt16(int value)
  868. {
  869. if (value < 0 || value > ushort.MaxValue) ThrowUInt16OverflowException();
  870. return (ushort)value;
  871. }
  872. [CLSCompliant(false)]
  873. public static ushort ToUInt16(ushort value)
  874. {
  875. return value;
  876. }
  877. [CLSCompliant(false)]
  878. public static ushort ToUInt16(uint value)
  879. {
  880. if (value > ushort.MaxValue) ThrowUInt16OverflowException();
  881. return (ushort)value;
  882. }
  883. [CLSCompliant(false)]
  884. public static ushort ToUInt16(long value)
  885. {
  886. if (value < 0 || value > ushort.MaxValue) ThrowUInt16OverflowException();
  887. return (ushort)value;
  888. }
  889. [CLSCompliant(false)]
  890. public static ushort ToUInt16(ulong value)
  891. {
  892. if (value > ushort.MaxValue) ThrowUInt16OverflowException();
  893. return (ushort)value;
  894. }
  895. [CLSCompliant(false)]
  896. public static ushort ToUInt16(float value)
  897. {
  898. return ToUInt16((double)value);
  899. }
  900. [CLSCompliant(false)]
  901. public static ushort ToUInt16(double value)
  902. {
  903. return ToUInt16(ToInt32(value));
  904. }
  905. [CLSCompliant(false)]
  906. public static ushort ToUInt16(decimal value)
  907. {
  908. return decimal.ToUInt16(decimal.Round(value, 0));
  909. }
  910. [CLSCompliant(false)]
  911. public static ushort ToUInt16(string value)
  912. {
  913. if (value == null)
  914. return 0;
  915. return ushort.Parse(value, CultureInfo.CurrentCulture);
  916. }
  917. [CLSCompliant(false)]
  918. public static ushort ToUInt16(string value, IFormatProvider provider)
  919. {
  920. if (value == null)
  921. return 0;
  922. return ushort.Parse(value, NumberStyles.Integer, provider);
  923. }
  924. [CLSCompliant(false)]
  925. public static ushort ToUInt16(DateTime value)
  926. {
  927. return ((IConvertible)value).ToUInt16(null);
  928. }
  929. // Disallowed conversions to UInt16
  930. // public static ushort ToUInt16(TimeSpan value)
  931. // Conversions to Int32
  932. public static int ToInt32(object value)
  933. {
  934. return value == null ? 0 : ((IConvertible)value).ToInt32(null);
  935. }
  936. public static int ToInt32(object value, IFormatProvider provider)
  937. {
  938. return value == null ? 0 : ((IConvertible)value).ToInt32(provider);
  939. }
  940. public static int ToInt32(bool value)
  941. {
  942. return value ? bool.True : bool.False;
  943. }
  944. public static int ToInt32(char value)
  945. {
  946. return value;
  947. }
  948. [CLSCompliant(false)]
  949. public static int ToInt32(sbyte value)
  950. {
  951. return value;
  952. }
  953. public static int ToInt32(byte value)
  954. {
  955. return value;
  956. }
  957. public static int ToInt32(short value)
  958. {
  959. return value;
  960. }
  961. [CLSCompliant(false)]
  962. public static int ToInt32(ushort value)
  963. {
  964. return value;
  965. }
  966. [CLSCompliant(false)]
  967. public static int ToInt32(uint value)
  968. {
  969. if (value > int.MaxValue) ThrowInt32OverflowException();
  970. return (int)value;
  971. }
  972. public static int ToInt32(int value)
  973. {
  974. return value;
  975. }
  976. public static int ToInt32(long value)
  977. {
  978. if (value < int.MinValue || value > int.MaxValue) ThrowInt32OverflowException();
  979. return (int)value;
  980. }
  981. [CLSCompliant(false)]
  982. public static int ToInt32(ulong value)
  983. {
  984. if (value > int.MaxValue) ThrowInt32OverflowException();
  985. return (int)value;
  986. }
  987. public static int ToInt32(float value)
  988. {
  989. return ToInt32((double)value);
  990. }
  991. public static int ToInt32(double value)
  992. {
  993. if (value >= 0)
  994. {
  995. if (value < 2147483647.5)
  996. {
  997. int result = (int)value;
  998. double dif = value - result;
  999. if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++;
  1000. return result;
  1001. }
  1002. }
  1003. else
  1004. {
  1005. if (value >= -2147483648.5)
  1006. {
  1007. int result = (int)value;
  1008. double dif = value - result;
  1009. if (dif < -0.5 || dif == -0.5 && (result & 1) != 0) result--;
  1010. return result;
  1011. }
  1012. }
  1013. throw new OverflowException(SR.Overflow_Int32);
  1014. }
  1015. public static int ToInt32(decimal value)
  1016. {
  1017. return decimal.ToInt32(decimal.Round(value, 0));
  1018. }
  1019. public static int ToInt32(string value)
  1020. {
  1021. if (value == null)
  1022. return 0;
  1023. return int.Parse(value, CultureInfo.CurrentCulture);
  1024. }
  1025. public static int ToInt32(string value, IFormatProvider provider)
  1026. {
  1027. if (value == null)
  1028. return 0;
  1029. return int.Parse(value, NumberStyles.Integer, provider);
  1030. }
  1031. public static int ToInt32(DateTime value)
  1032. {
  1033. return ((IConvertible)value).ToInt32(null);
  1034. }
  1035. // Disallowed conversions to Int32
  1036. // public static int ToInt32(TimeSpan value)
  1037. // Conversions to UInt32
  1038. [CLSCompliant(false)]
  1039. public static uint ToUInt32(object value)
  1040. {
  1041. return value == null ? 0 : ((IConvertible)value).ToUInt32(null);
  1042. }
  1043. [CLSCompliant(false)]
  1044. public static uint ToUInt32(object value, IFormatProvider provider)
  1045. {
  1046. return value == null ? 0 : ((IConvertible)value).ToUInt32(provider);
  1047. }
  1048. [CLSCompliant(false)]
  1049. public static uint ToUInt32(bool value)
  1050. {
  1051. return value ? (uint)bool.True : (uint)bool.False;
  1052. }
  1053. [CLSCompliant(false)]
  1054. public static uint ToUInt32(char value)
  1055. {
  1056. return value;
  1057. }
  1058. [CLSCompliant(false)]
  1059. public static uint ToUInt32(sbyte value)
  1060. {
  1061. if (value < 0) ThrowUInt32OverflowException();
  1062. return (uint)value;
  1063. }
  1064. [CLSCompliant(false)]
  1065. public static uint ToUInt32(byte value)
  1066. {
  1067. return value;
  1068. }
  1069. [CLSCompliant(false)]
  1070. public static uint ToUInt32(short value)
  1071. {
  1072. if (value < 0) ThrowUInt32OverflowException();
  1073. return (uint)value;
  1074. }
  1075. [CLSCompliant(false)]
  1076. public static uint ToUInt32(ushort value)
  1077. {
  1078. return value;
  1079. }
  1080. [CLSCompliant(false)]
  1081. public static uint ToUInt32(int value)
  1082. {
  1083. if (value < 0) ThrowUInt32OverflowException();
  1084. return (uint)value;
  1085. }
  1086. [CLSCompliant(false)]
  1087. public static uint ToUInt32(uint value)
  1088. {
  1089. return value;
  1090. }
  1091. [CLSCompliant(false)]
  1092. public static uint ToUInt32(long value)
  1093. {
  1094. if (value < 0 || value > uint.MaxValue) ThrowUInt32OverflowException();
  1095. return (uint)value;
  1096. }
  1097. [CLSCompliant(false)]
  1098. public static uint ToUInt32(ulong value)
  1099. {
  1100. if (value > uint.MaxValue) ThrowUInt32OverflowException();
  1101. return (uint)value;
  1102. }
  1103. [CLSCompliant(false)]
  1104. public static uint ToUInt32(float value)
  1105. {
  1106. return ToUInt32((double)value);
  1107. }
  1108. [CLSCompliant(false)]
  1109. public static uint ToUInt32(double value)
  1110. {
  1111. if (value >= -0.5 && value < 4294967295.5)
  1112. {
  1113. uint result = (uint)value;
  1114. double dif = value - result;
  1115. if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++;
  1116. return result;
  1117. }
  1118. throw new OverflowException(SR.Overflow_UInt32);
  1119. }
  1120. [CLSCompliant(false)]
  1121. public static uint ToUInt32(decimal value)
  1122. {
  1123. return decimal.ToUInt32(decimal.Round(value, 0));
  1124. }
  1125. [CLSCompliant(false)]
  1126. public static uint ToUInt32(string value)
  1127. {
  1128. if (value == null)
  1129. return 0;
  1130. return uint.Parse(value, CultureInfo.CurrentCulture);
  1131. }
  1132. [CLSCompliant(false)]
  1133. public static uint ToUInt32(string value, IFormatProvider provider)
  1134. {
  1135. if (value == null)
  1136. return 0;
  1137. return uint.Parse(value, NumberStyles.Integer, provider);
  1138. }
  1139. [CLSCompliant(false)]
  1140. public static uint ToUInt32(DateTime value)
  1141. {
  1142. return ((IConvertible)value).ToUInt32(null);
  1143. }
  1144. // Disallowed conversions to UInt32
  1145. // public static uint ToUInt32(TimeSpan value)
  1146. // Conversions to Int64
  1147. public static long ToInt64(object value)
  1148. {
  1149. return value == null ? 0 : ((IConvertible)value).ToInt64(null);
  1150. }
  1151. public static long ToInt64(object value, IFormatProvider provider)
  1152. {
  1153. return value == null ? 0 : ((IConvertible)value).ToInt64(provider);
  1154. }
  1155. public static long ToInt64(bool value)
  1156. {
  1157. return value ? bool.True : bool.False;
  1158. }
  1159. public static long ToInt64(char value)
  1160. {
  1161. return value;
  1162. }
  1163. [CLSCompliant(false)]
  1164. public static long ToInt64(sbyte value)
  1165. {
  1166. return value;
  1167. }
  1168. public static long ToInt64(byte value)
  1169. {
  1170. return value;
  1171. }
  1172. public static long ToInt64(short value)
  1173. {
  1174. return value;
  1175. }
  1176. [CLSCompliant(false)]
  1177. public static long ToInt64(ushort value)
  1178. {
  1179. return value;
  1180. }
  1181. public static long ToInt64(int value)
  1182. {
  1183. return value;
  1184. }
  1185. [CLSCompliant(false)]
  1186. public static long ToInt64(uint value)
  1187. {
  1188. return value;
  1189. }
  1190. [CLSCompliant(false)]
  1191. public static long ToInt64(ulong value)
  1192. {
  1193. if (value > long.MaxValue) ThrowInt64OverflowException();
  1194. return (long)value;
  1195. }
  1196. public static long ToInt64(long value)
  1197. {
  1198. return value;
  1199. }
  1200. public static long ToInt64(float value)
  1201. {
  1202. return ToInt64((double)value);
  1203. }
  1204. public static long ToInt64(double value)
  1205. {
  1206. return checked((long)Math.Round(value));
  1207. }
  1208. public static long ToInt64(decimal value)
  1209. {
  1210. return decimal.ToInt64(decimal.Round(value, 0));
  1211. }
  1212. public static long ToInt64(string value)
  1213. {
  1214. if (value == null)
  1215. return 0;
  1216. return long.Parse(value, CultureInfo.CurrentCulture);
  1217. }
  1218. public static long ToInt64(string value, IFormatProvider provider)
  1219. {
  1220. if (value == null)
  1221. return 0;
  1222. return long.Parse(value, NumberStyles.Integer, provider);
  1223. }
  1224. public static long ToInt64(DateTime value)
  1225. {
  1226. return ((IConvertible)value).ToInt64(null);
  1227. }
  1228. // Disallowed conversions to Int64
  1229. // public static long ToInt64(TimeSpan value)
  1230. // Conversions to UInt64
  1231. [CLSCompliant(false)]
  1232. public static ulong ToUInt64(object value)
  1233. {
  1234. return value == null ? 0 : ((IConvertible)value).ToUInt64(null);
  1235. }
  1236. [CLSCompliant(false)]
  1237. public static ulong ToUInt64(object value, IFormatProvider provider)
  1238. {
  1239. return value == null ? 0 : ((IConvertible)value).ToUInt64(provider);
  1240. }
  1241. [CLSCompliant(false)]
  1242. public static ulong ToUInt64(bool value)
  1243. {
  1244. return value ? (ulong)bool.True : (ulong)bool.False;
  1245. }
  1246. [CLSCompliant(false)]
  1247. public static ulong ToUInt64(char value)
  1248. {
  1249. return value;
  1250. }
  1251. [CLSCompliant(false)]
  1252. public static ulong ToUInt64(sbyte value)
  1253. {
  1254. if (value < 0) ThrowUInt64OverflowException();
  1255. return (ulong)value;
  1256. }
  1257. [CLSCompliant(false)]
  1258. public static ulong ToUInt64(byte value)
  1259. {
  1260. return value;
  1261. }
  1262. [CLSCompliant(false)]
  1263. public static ulong ToUInt64(short value)
  1264. {
  1265. if (value < 0) ThrowUInt64OverflowException();
  1266. return (ulong)value;
  1267. }
  1268. [CLSCompliant(false)]
  1269. public static ulong ToUInt64(ushort value)
  1270. {
  1271. return value;
  1272. }
  1273. [CLSCompliant(false)]
  1274. public static ulong ToUInt64(int value)
  1275. {
  1276. if (value < 0) ThrowUInt64OverflowException();
  1277. return (ulong)value;
  1278. }
  1279. [CLSCompliant(false)]
  1280. public static ulong ToUInt64(uint value)
  1281. {
  1282. return value;
  1283. }
  1284. [CLSCompliant(false)]
  1285. public static ulong ToUInt64(long value)
  1286. {
  1287. if (value < 0) ThrowUInt64OverflowException();
  1288. return (ulong)value;
  1289. }
  1290. [CLSCompliant(false)]
  1291. public static ulong ToUInt64(ulong value)
  1292. {
  1293. return value;
  1294. }
  1295. [CLSCompliant(false)]
  1296. public static ulong ToUInt64(float value)
  1297. {
  1298. return ToUInt64((double)value);
  1299. }
  1300. [CLSCompliant(false)]
  1301. public static ulong ToUInt64(double value)
  1302. {
  1303. return checked((ulong)Math.Round(value));
  1304. }
  1305. [CLSCompliant(false)]
  1306. public static ulong ToUInt64(decimal value)
  1307. {
  1308. return decimal.ToUInt64(decimal.Round(value, 0));
  1309. }
  1310. [CLSCompliant(false)]
  1311. public static ulong ToUInt64(string value)
  1312. {
  1313. if (value == null)
  1314. return 0;
  1315. return ulong.Parse(value, CultureInfo.CurrentCulture);
  1316. }
  1317. [CLSCompliant(false)]
  1318. public static ulong ToUInt64(string value, IFormatProvider provider)
  1319. {
  1320. if (value == null)
  1321. return 0;
  1322. return ulong.Parse(value, NumberStyles.Integer, provider);
  1323. }
  1324. [CLSCompliant(false)]
  1325. public static ulong ToUInt64(DateTime value)
  1326. {
  1327. return ((IConvertible)value).ToUInt64(null);
  1328. }
  1329. // Disallowed conversions to UInt64
  1330. // public static ulong ToUInt64(TimeSpan value)
  1331. // Conversions to Single
  1332. public static float ToSingle(object value)
  1333. {
  1334. return value == null ? 0 : ((IConvertible)value).ToSingle(null);
  1335. }
  1336. public static float ToSingle(object value, IFormatProvider provider)
  1337. {
  1338. return value == null ? 0 : ((IConvertible)value).ToSingle(provider);
  1339. }
  1340. [CLSCompliant(false)]
  1341. public static float ToSingle(sbyte value)
  1342. {
  1343. return value;
  1344. }
  1345. public static float ToSingle(byte value)
  1346. {
  1347. return value;
  1348. }
  1349. public static float ToSingle(char value)
  1350. {
  1351. return ((IConvertible)value).ToSingle(null);
  1352. }
  1353. public static float ToSingle(short value)
  1354. {
  1355. return value;
  1356. }
  1357. [CLSCompliant(false)]
  1358. public static float ToSingle(ushort value)
  1359. {
  1360. return value;
  1361. }
  1362. public static float ToSingle(int value)
  1363. {
  1364. return value;
  1365. }
  1366. [CLSCompliant(false)]
  1367. public static float ToSingle(uint value)
  1368. {
  1369. return value;
  1370. }
  1371. public static float ToSingle(long value)
  1372. {
  1373. return value;
  1374. }
  1375. [CLSCompliant(false)]
  1376. public static float ToSingle(ulong value)
  1377. {
  1378. return value;
  1379. }
  1380. public static float ToSingle(float value)
  1381. {
  1382. return value;
  1383. }
  1384. public static float ToSingle(double value)
  1385. {
  1386. return (float)value;
  1387. }
  1388. public static float ToSingle(decimal value)
  1389. {
  1390. return (float)value;
  1391. }
  1392. public static float ToSingle(string value)
  1393. {
  1394. if (value == null)
  1395. return 0;
  1396. return float.Parse(value, CultureInfo.CurrentCulture);
  1397. }
  1398. public static float ToSingle(string value, IFormatProvider provider)
  1399. {
  1400. if (value == null)
  1401. return 0;
  1402. return float.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);
  1403. }
  1404. public static float ToSingle(bool value)
  1405. {
  1406. return value ? bool.True : bool.False;
  1407. }
  1408. public static float ToSingle(DateTime value)
  1409. {
  1410. return ((IConvertible)value).ToSingle(null);
  1411. }
  1412. // Disallowed conversions to Single
  1413. // public static float ToSingle(TimeSpan value)
  1414. // Conversions to Double
  1415. public static double ToDouble(object value)
  1416. {
  1417. return value == null ? 0 : ((IConvertible)value).ToDouble(null);
  1418. }
  1419. public static double ToDouble(object value, IFormatProvider provider)
  1420. {
  1421. return value == null ? 0 : ((IConvertible)value).ToDouble(provider);
  1422. }
  1423. [CLSCompliant(false)]
  1424. public static double ToDouble(sbyte value)
  1425. {
  1426. return value;
  1427. }
  1428. public static double ToDouble(byte value)
  1429. {
  1430. return value;
  1431. }
  1432. public static double ToDouble(short value)
  1433. {
  1434. return value;
  1435. }
  1436. public static double ToDouble(char value)
  1437. {
  1438. return ((IConvertible)value).ToDouble(null);
  1439. }
  1440. [CLSCompliant(false)]
  1441. public static double ToDouble(ushort value)
  1442. {
  1443. return value;
  1444. }
  1445. public static double ToDouble(int value)
  1446. {
  1447. return value;
  1448. }
  1449. [CLSCompliant(false)]
  1450. public static double ToDouble(uint value)
  1451. {
  1452. return value;
  1453. }
  1454. public static double ToDouble(long value)
  1455. {
  1456. return value;
  1457. }
  1458. [CLSCompliant(false)]
  1459. public static double ToDouble(ulong value)
  1460. {
  1461. return value;
  1462. }
  1463. public static double ToDouble(float value)
  1464. {
  1465. return value;
  1466. }
  1467. public static double ToDouble(double value)
  1468. {
  1469. return value;
  1470. }
  1471. public static double ToDouble(decimal value)
  1472. {
  1473. return (double)value;
  1474. }
  1475. public static double ToDouble(string value)
  1476. {
  1477. if (value == null)
  1478. return 0;
  1479. return double.Parse(value, CultureInfo.CurrentCulture);
  1480. }
  1481. public static double ToDouble(string value, IFormatProvider provider)
  1482. {
  1483. if (value == null)
  1484. return 0;
  1485. return double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);
  1486. }
  1487. public static double ToDouble(bool value)
  1488. {
  1489. return value ? bool.True : bool.False;
  1490. }
  1491. public static double ToDouble(DateTime value)
  1492. {
  1493. return ((IConvertible)value).ToDouble(null);
  1494. }
  1495. // Disallowed conversions to Double
  1496. // public static double ToDouble(TimeSpan value)
  1497. // Conversions to Decimal
  1498. public static decimal ToDecimal(object value)
  1499. {
  1500. return value == null ? 0 : ((IConvertible)value).ToDecimal(null);
  1501. }
  1502. public static decimal ToDecimal(object value, IFormatProvider provider)
  1503. {
  1504. return value == null ? 0 : ((IConvertible)value).ToDecimal(provider);
  1505. }
  1506. [CLSCompliant(false)]
  1507. public static decimal ToDecimal(sbyte value)
  1508. {
  1509. return value;
  1510. }
  1511. public static decimal ToDecimal(byte value)
  1512. {
  1513. return value;
  1514. }
  1515. public static decimal ToDecimal(char value)
  1516. {
  1517. return ((IConvertible)value).ToDecimal(null);
  1518. }
  1519. public static decimal ToDecimal(short value)
  1520. {
  1521. return value;
  1522. }
  1523. [CLSCompliant(false)]
  1524. public static decimal ToDecimal(ushort value)
  1525. {
  1526. return value;
  1527. }
  1528. public static decimal ToDecimal(int value)
  1529. {
  1530. return value;
  1531. }
  1532. [CLSCompliant(false)]
  1533. public static decimal ToDecimal(uint value)
  1534. {
  1535. return value;
  1536. }
  1537. public static decimal ToDecimal(long value)
  1538. {
  1539. return value;
  1540. }
  1541. [CLSCompliant(false)]
  1542. public static decimal ToDecimal(ulong value)
  1543. {
  1544. return value;
  1545. }
  1546. public static decimal ToDecimal(float value)
  1547. {
  1548. return (decimal)value;
  1549. }
  1550. public static decimal ToDecimal(double value)
  1551. {
  1552. return (decimal)value;
  1553. }
  1554. public static decimal ToDecimal(string value)
  1555. {
  1556. if (value == null)
  1557. return 0m;
  1558. return decimal.Parse(value, CultureInfo.CurrentCulture);
  1559. }
  1560. public static decimal ToDecimal(string value, IFormatProvider provider)
  1561. {
  1562. if (value == null)
  1563. return 0m;
  1564. return decimal.Parse(value, NumberStyles.Number, provider);
  1565. }
  1566. public static decimal ToDecimal(decimal value)
  1567. {
  1568. return value;
  1569. }
  1570. public static decimal ToDecimal(bool value)
  1571. {
  1572. return value ? bool.True : bool.False;
  1573. }
  1574. public static decimal ToDecimal(DateTime value)
  1575. {
  1576. return ((IConvertible)value).ToDecimal(null);
  1577. }
  1578. // Disallowed conversions to Decimal
  1579. // public static decimal ToDecimal(TimeSpan value)
  1580. // Conversions to DateTime
  1581. public static DateTime ToDateTime(DateTime value)
  1582. {
  1583. return value;
  1584. }
  1585. public static DateTime ToDateTime(object value)
  1586. {
  1587. return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime(null);
  1588. }
  1589. public static DateTime ToDateTime(object value, IFormatProvider provider)
  1590. {
  1591. return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime(provider);
  1592. }
  1593. public static DateTime ToDateTime(string value)
  1594. {
  1595. if (value == null)
  1596. return new DateTime(0);
  1597. return DateTime.Parse(value, CultureInfo.CurrentCulture);
  1598. }
  1599. public static DateTime ToDateTime(string value, IFormatProvider provider)
  1600. {
  1601. if (value == null)
  1602. return new DateTime(0);
  1603. return DateTime.Parse(value, provider);
  1604. }
  1605. [CLSCompliant(false)]
  1606. public static DateTime ToDateTime(sbyte value)
  1607. {
  1608. return ((IConvertible)value).ToDateTime(null);
  1609. }
  1610. public static DateTime ToDateTime(byte value)
  1611. {
  1612. return ((IConvertible)value).ToDateTime(null);
  1613. }
  1614. public static DateTime ToDateTime(short value)
  1615. {
  1616. return ((IConvertible)value).ToDateTime(null);
  1617. }
  1618. [CLSCompliant(false)]
  1619. public static DateTime ToDateTime(ushort value)
  1620. {
  1621. return ((IConvertible)value).ToDateTime(null);
  1622. }
  1623. public static DateTime ToDateTime(int value)
  1624. {
  1625. return ((IConvertible)value).ToDateTime(null);
  1626. }
  1627. [CLSCompliant(false)]
  1628. public static DateTime ToDateTime(uint value)
  1629. {
  1630. return ((IConvertible)value).ToDateTime(null);
  1631. }
  1632. public static DateTime ToDateTime(long value)
  1633. {
  1634. return ((IConvertible)value).ToDateTime(null);
  1635. }
  1636. [CLSCompliant(false)]
  1637. public static DateTime ToDateTime(ulong value)
  1638. {
  1639. return ((IConvertible)value).ToDateTime(null);
  1640. }
  1641. public static DateTime ToDateTime(bool value)
  1642. {
  1643. return ((IConvertible)value).ToDateTime(null);
  1644. }
  1645. public static DateTime ToDateTime(char value)
  1646. {
  1647. return ((IConvertible)value).ToDateTime(null);
  1648. }
  1649. public static DateTime ToDateTime(float value)
  1650. {
  1651. return ((IConvertible)value).ToDateTime(null);
  1652. }
  1653. public static DateTime ToDateTime(double value)
  1654. {
  1655. return ((IConvertible)value).ToDateTime(null);
  1656. }
  1657. public static DateTime ToDateTime(decimal value)
  1658. {
  1659. return ((IConvertible)value).ToDateTime(null);
  1660. }
  1661. // Disallowed conversions to DateTime
  1662. // public static DateTime ToDateTime(TimeSpan value)
  1663. // Conversions to String
  1664. public static string ToString(object value)
  1665. {
  1666. return ToString(value, null);
  1667. }
  1668. public static string ToString(object value, IFormatProvider provider)
  1669. {
  1670. IConvertible ic = value as IConvertible;
  1671. if (ic != null)
  1672. return ic.ToString(provider);
  1673. IFormattable formattable = value as IFormattable;
  1674. if (formattable != null)
  1675. return formattable.ToString(null, provider);
  1676. return value == null ? string.Empty : value.ToString();
  1677. }
  1678. public static string ToString(bool value)
  1679. {
  1680. return value.ToString();
  1681. }
  1682. public static string ToString(bool value, IFormatProvider provider)
  1683. {
  1684. return value.ToString();
  1685. }
  1686. public static string ToString(char value)
  1687. {
  1688. return char.ToString(value);
  1689. }
  1690. public static string ToString(char value, IFormatProvider provider)
  1691. {
  1692. return value.ToString();
  1693. }
  1694. [CLSCompliant(false)]
  1695. public static string ToString(sbyte value)
  1696. {
  1697. return value.ToString(CultureInfo.CurrentCulture);
  1698. }
  1699. [CLSCompliant(false)]
  1700. public static string ToString(sbyte value, IFormatProvider provider)
  1701. {
  1702. return value.ToString(provider);
  1703. }
  1704. public static string ToString(byte value)
  1705. {
  1706. return value.ToString(CultureInfo.CurrentCulture);
  1707. }
  1708. public static string ToString(byte value, IFormatProvider provider)
  1709. {
  1710. return value.ToString(provider);
  1711. }
  1712. public static string ToString(short value)
  1713. {
  1714. return value.ToString(CultureInfo.CurrentCulture);
  1715. }
  1716. public static string ToString(short value, IFormatProvider provider)
  1717. {
  1718. return value.ToString(provider);
  1719. }
  1720. [CLSCompliant(false)]
  1721. public static string ToString(ushort value)
  1722. {
  1723. return value.ToString(CultureInfo.CurrentCulture);
  1724. }
  1725. [CLSCompliant(false)]
  1726. public static string ToString(ushort value, IFormatProvider provider)
  1727. {
  1728. return value.ToString(provider);
  1729. }
  1730. public static string ToString(int value)
  1731. {
  1732. return value.ToString(CultureInfo.CurrentCulture);
  1733. }
  1734. public static string ToString(int value, IFormatProvider provider)
  1735. {
  1736. return value.ToString(provider);
  1737. }
  1738. [CLSCompliant(false)]
  1739. public static string ToString(uint value)
  1740. {
  1741. return value.ToString(CultureInfo.CurrentCulture);
  1742. }
  1743. [CLSCompliant(false)]
  1744. public static string ToString(uint value, IFormatProvider provider)
  1745. {
  1746. return value.ToString(provider);
  1747. }
  1748. public static string ToString(long value)
  1749. {
  1750. return value.ToString(CultureInfo.CurrentCulture);
  1751. }
  1752. public static string ToString(long value, IFormatProvider provider)
  1753. {
  1754. return value.ToString(provider);
  1755. }
  1756. [CLSCompliant(false)]
  1757. public static string ToString(ulong value)
  1758. {
  1759. return value.ToString(CultureInfo.CurrentCulture);
  1760. }
  1761. [CLSCompliant(false)]
  1762. public static string ToString(ulong value, IFormatProvider provider)
  1763. {
  1764. return value.ToString(provider);
  1765. }
  1766. public static string ToString(float value)
  1767. {
  1768. return value.ToString(CultureInfo.CurrentCulture);
  1769. }
  1770. public static string ToString(float value, IFormatProvider provider)
  1771. {
  1772. return value.ToString(provider);
  1773. }
  1774. public static string ToString(double value)
  1775. {
  1776. return value.ToString(CultureInfo.CurrentCulture);
  1777. }
  1778. public static string ToString(double value, IFormatProvider provider)
  1779. {
  1780. return value.ToString(provider);
  1781. }
  1782. public static string ToString(decimal value)
  1783. {
  1784. return value.ToString(CultureInfo.CurrentCulture);
  1785. }
  1786. public static string ToString(decimal value, IFormatProvider provider)
  1787. {
  1788. return value.ToString(provider);
  1789. }
  1790. public static string ToString(DateTime value)
  1791. {
  1792. return value.ToString();
  1793. }
  1794. public static string ToString(DateTime value, IFormatProvider provider)
  1795. {
  1796. return value.ToString(provider);
  1797. }
  1798. public static string ToString(string value)
  1799. {
  1800. return value;
  1801. }
  1802. public static string ToString(string value, IFormatProvider provider)
  1803. {
  1804. return value; // avoid the null check
  1805. }
  1806. //
  1807. // Conversions which understand Base XXX numbers.
  1808. //
  1809. // Parses value in base base. base can only
  1810. // be 2, 8, 10, or 16. If base is 16, the number may be preceded
  1811. // by 0x; any other leading or trailing characters cause an error.
  1812. //
  1813. public static byte ToByte(string value, int fromBase)
  1814. {
  1815. if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
  1816. {
  1817. throw new ArgumentException(SR.Arg_InvalidBase);
  1818. }
  1819. if (value == null)
  1820. {
  1821. return 0;
  1822. }
  1823. int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned);
  1824. if (r < byte.MinValue || r > byte.MaxValue)
  1825. ThrowByteOverflowException();
  1826. return (byte)r;
  1827. }
  1828. // Parses value in base fromBase. fromBase can only
  1829. // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
  1830. // by 0x; any other leading or trailing characters cause an error.
  1831. //
  1832. [CLSCompliant(false)]
  1833. public static sbyte ToSByte(string value, int fromBase)
  1834. {
  1835. if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
  1836. {
  1837. throw new ArgumentException(SR.Arg_InvalidBase);
  1838. }
  1839. if (value == null)
  1840. {
  1841. return 0;
  1842. }
  1843. int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI1);
  1844. if (fromBase != 10 && r <= byte.MaxValue)
  1845. return (sbyte)r;
  1846. if (r < sbyte.MinValue || r > sbyte.MaxValue)
  1847. ThrowSByteOverflowException();
  1848. return (sbyte)r;
  1849. }
  1850. // Parses value in base fromBase. fromBase can only
  1851. // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
  1852. // by 0x; any other leading or trailing characters cause an error.
  1853. //
  1854. public static short ToInt16(string value, int fromBase)
  1855. {
  1856. if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
  1857. {
  1858. throw new ArgumentException(SR.Arg_InvalidBase);
  1859. }
  1860. if (value == null)
  1861. {
  1862. return 0;
  1863. }
  1864. int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI2);
  1865. if (fromBase != 10 && r <= ushort.MaxValue)
  1866. return (short)r;
  1867. if (r < short.MinValue || r > short.MaxValue)
  1868. ThrowInt16OverflowException();
  1869. return (short)r;
  1870. }
  1871. // Parses value in base fromBase. fromBase can only
  1872. // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
  1873. // by 0x; any other leading or trailing characters cause an error.
  1874. //
  1875. [CLSCompliant(false)]
  1876. public static ushort ToUInt16(string value, int fromBase)
  1877. {
  1878. if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
  1879. {
  1880. throw new ArgumentException(SR.Arg_InvalidBase);
  1881. }
  1882. if (value == null)
  1883. {
  1884. return 0;
  1885. }
  1886. int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned);
  1887. if (r < ushort.MinValue || r > ushort.MaxValue)
  1888. ThrowUInt16OverflowException();
  1889. return (ushort)r;
  1890. }
  1891. // Parses value in base fromBase. fromBase can only
  1892. // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
  1893. // by 0x; any other leading or trailing characters cause an error.
  1894. //
  1895. public static int ToInt32(string value, int fromBase)
  1896. {
  1897. if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
  1898. {
  1899. throw new ArgumentException(SR.Arg_InvalidBase);
  1900. }
  1901. return value != null ?
  1902. ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight) :
  1903. 0;
  1904. }
  1905. // Parses value in base fromBase. fromBase can only
  1906. // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
  1907. // by 0x; any other leading or trailing characters cause an error.
  1908. //
  1909. [CLSCompliant(false)]
  1910. public static uint ToUInt32(string value, int fromBase)
  1911. {
  1912. if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
  1913. {
  1914. throw new ArgumentException(SR.Arg_InvalidBase);
  1915. }
  1916. return value != null ?
  1917. (uint)ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight) :
  1918. 0;
  1919. }
  1920. // Parses value in base fromBase. fromBase can only
  1921. // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
  1922. // by 0x; any other leading or trailing characters cause an error.
  1923. //
  1924. public static long ToInt64(string value, int fromBase)
  1925. {
  1926. if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
  1927. {
  1928. throw new ArgumentException(SR.Arg_InvalidBase);
  1929. }
  1930. return value != null ?
  1931. ParseNumbers.StringToLong(value.AsSpan(), fromBase, ParseNumbers.IsTight) :
  1932. 0;
  1933. }
  1934. // Parses value in base fromBase. fromBase can only
  1935. // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
  1936. // by 0x; any other leading or trailing characters cause an error.
  1937. //
  1938. [CLSCompliant(false)]
  1939. public static ulong ToUInt64(string value, int fromBase)
  1940. {
  1941. if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
  1942. {
  1943. throw new ArgumentException(SR.Arg_InvalidBase);
  1944. }
  1945. return value != null ?
  1946. (ulong)ParseNumbers.StringToLong(value.AsSpan(), fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight) :
  1947. 0;
  1948. }
  1949. // Convert the byte value to a string in base fromBase
  1950. public static string ToString(byte value, int toBase)
  1951. {
  1952. if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16)
  1953. {
  1954. throw new ArgumentException(SR.Arg_InvalidBase);
  1955. }
  1956. return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI1);
  1957. }
  1958. // Convert the Int16 value to a string in base fromBase
  1959. public static string ToString(short value, int toBase)
  1960. {
  1961. if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16)
  1962. {
  1963. throw new ArgumentException(SR.Arg_InvalidBase);
  1964. }
  1965. return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI2);
  1966. }
  1967. // Convert the Int32 value to a string in base toBase
  1968. public static string ToString(int value, int toBase)
  1969. {
  1970. if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16)
  1971. {
  1972. throw new ArgumentException(SR.Arg_InvalidBase);
  1973. }
  1974. return ParseNumbers.IntToString(value, toBase, -1, ' ', 0);
  1975. }
  1976. // Convert the Int64 value to a string in base toBase
  1977. public static string ToString(long value, int toBase)
  1978. {
  1979. if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16)
  1980. {
  1981. throw new ArgumentException(SR.Arg_InvalidBase);
  1982. }
  1983. return ParseNumbers.LongToString(value, toBase, -1, ' ', 0);
  1984. }
  1985. public static string ToBase64String(byte[] inArray)
  1986. {
  1987. if (inArray == null)
  1988. {
  1989. throw new ArgumentNullException(nameof(inArray));
  1990. }
  1991. return ToBase64String(new ReadOnlySpan<byte>(inArray), Base64FormattingOptions.None);
  1992. }
  1993. public static string ToBase64String(byte[] inArray, Base64FormattingOptions options)
  1994. {
  1995. if (inArray == null)
  1996. {
  1997. throw new ArgumentNullException(nameof(inArray));
  1998. }
  1999. return ToBase64String(new ReadOnlySpan<byte>(inArray), options);
  2000. }
  2001. public static string ToBase64String(byte[] inArray, int offset, int length)
  2002. {
  2003. return ToBase64String(inArray, offset, length, Base64FormattingOptions.None);
  2004. }
  2005. public static string ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options)
  2006. {
  2007. if (inArray == null)
  2008. throw new ArgumentNullException(nameof(inArray));
  2009. if (length < 0)
  2010. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
  2011. if (offset < 0)
  2012. throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_GenericPositive);
  2013. if (offset > (inArray.Length - length))
  2014. throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_OffsetLength);
  2015. return ToBase64String(new ReadOnlySpan<byte>(inArray, offset, length), options);
  2016. }
  2017. public static string ToBase64String(ReadOnlySpan<byte> bytes, Base64FormattingOptions options = Base64FormattingOptions.None)
  2018. {
  2019. if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks)
  2020. {
  2021. throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options));
  2022. }
  2023. if (bytes.Length == 0)
  2024. {
  2025. return string.Empty;
  2026. }
  2027. bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks);
  2028. string result = string.FastAllocateString(ToBase64_CalculateAndValidateOutputLength(bytes.Length, insertLineBreaks));
  2029. unsafe
  2030. {
  2031. fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes))
  2032. fixed (char* charsPtr = result)
  2033. {
  2034. int charsWritten = ConvertToBase64Array(charsPtr, bytesPtr, 0, bytes.Length, insertLineBreaks);
  2035. Debug.Assert(result.Length == charsWritten, $"Expected {result.Length} == {charsWritten}");
  2036. }
  2037. }
  2038. return result;
  2039. }
  2040. public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut)
  2041. {
  2042. return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None);
  2043. }
  2044. public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options)
  2045. {
  2046. //Do data verfication
  2047. if (inArray == null)
  2048. throw new ArgumentNullException(nameof(inArray));
  2049. if (outArray == null)
  2050. throw new ArgumentNullException(nameof(outArray));
  2051. if (length < 0)
  2052. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
  2053. if (offsetIn < 0)
  2054. throw new ArgumentOutOfRangeException(nameof(offsetIn), SR.ArgumentOutOfRange_GenericPositive);
  2055. if (offsetOut < 0)
  2056. throw new ArgumentOutOfRangeException(nameof(offsetOut), SR.ArgumentOutOfRange_GenericPositive);
  2057. if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks)
  2058. {
  2059. throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options));
  2060. }
  2061. int retVal;
  2062. int inArrayLength;
  2063. int outArrayLength;
  2064. int numElementsToCopy;
  2065. inArrayLength = inArray.Length;
  2066. if (offsetIn > (int)(inArrayLength - length))
  2067. throw new ArgumentOutOfRangeException(nameof(offsetIn), SR.ArgumentOutOfRange_OffsetLength);
  2068. if (inArrayLength == 0)
  2069. return 0;
  2070. bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks);
  2071. //This is the maximally required length that must be available in the char array
  2072. outArrayLength = outArray.Length;
  2073. // Length of the char buffer required
  2074. numElementsToCopy = ToBase64_CalculateAndValidateOutputLength(length, insertLineBreaks);
  2075. if (offsetOut > (int)(outArrayLength - numElementsToCopy))
  2076. throw new ArgumentOutOfRangeException(nameof(offsetOut), SR.ArgumentOutOfRange_OffsetOut);
  2077. fixed (char* outChars = &outArray[offsetOut])
  2078. {
  2079. fixed (byte* inData = &inArray[0])
  2080. {
  2081. retVal = ConvertToBase64Array(outChars, inData, offsetIn, length, insertLineBreaks);
  2082. }
  2083. }
  2084. return retVal;
  2085. }
  2086. public static unsafe bool TryToBase64Chars(ReadOnlySpan<byte> bytes, Span<char> chars, out int charsWritten, Base64FormattingOptions options = Base64FormattingOptions.None)
  2087. {
  2088. if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks)
  2089. {
  2090. throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options));
  2091. }
  2092. if (bytes.Length == 0)
  2093. {
  2094. charsWritten = 0;
  2095. return true;
  2096. }
  2097. bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks);
  2098. int charLengthRequired = ToBase64_CalculateAndValidateOutputLength(bytes.Length, insertLineBreaks);
  2099. if (charLengthRequired > chars.Length)
  2100. {
  2101. charsWritten = 0;
  2102. return false;
  2103. }
  2104. fixed (char* outChars = &MemoryMarshal.GetReference(chars))
  2105. fixed (byte* inData = &MemoryMarshal.GetReference(bytes))
  2106. {
  2107. charsWritten = ConvertToBase64Array(outChars, inData, 0, bytes.Length, insertLineBreaks);
  2108. return true;
  2109. }
  2110. }
  2111. private static unsafe int ConvertToBase64Array(char* outChars, byte* inData, int offset, int length, bool insertLineBreaks)
  2112. {
  2113. int lengthmod3 = length % 3;
  2114. int calcLength = offset + (length - lengthmod3);
  2115. int j = 0;
  2116. int charcount = 0;
  2117. //Convert three bytes at a time to base64 notation. This will consume 4 chars.
  2118. int i;
  2119. // get a pointer to the base64Table to avoid unnecessary range checking
  2120. fixed (char* base64 = &base64Table[0])
  2121. {
  2122. for (i = offset; i < calcLength; i += 3)
  2123. {
  2124. if (insertLineBreaks)
  2125. {
  2126. if (charcount == base64LineBreakPosition)
  2127. {
  2128. outChars[j++] = '\r';
  2129. outChars[j++] = '\n';
  2130. charcount = 0;
  2131. }
  2132. charcount += 4;
  2133. }
  2134. outChars[j] = base64[(inData[i] & 0xfc) >> 2];
  2135. outChars[j + 1] = base64[((inData[i] & 0x03) << 4) | ((inData[i + 1] & 0xf0) >> 4)];
  2136. outChars[j + 2] = base64[((inData[i + 1] & 0x0f) << 2) | ((inData[i + 2] & 0xc0) >> 6)];
  2137. outChars[j + 3] = base64[(inData[i + 2] & 0x3f)];
  2138. j += 4;
  2139. }
  2140. //Where we left off before
  2141. i = calcLength;
  2142. if (insertLineBreaks && (lengthmod3 != 0) && (charcount == base64LineBreakPosition))
  2143. {
  2144. outChars[j++] = '\r';
  2145. outChars[j++] = '\n';
  2146. }
  2147. switch (lengthmod3)
  2148. {
  2149. case 2: //One character padding needed
  2150. outChars[j] = base64[(inData[i] & 0xfc) >> 2];
  2151. outChars[j + 1] = base64[((inData[i] & 0x03) << 4) | ((inData[i + 1] & 0xf0) >> 4)];
  2152. outChars[j + 2] = base64[(inData[i + 1] & 0x0f) << 2];
  2153. outChars[j + 3] = base64[64]; //Pad
  2154. j += 4;
  2155. break;
  2156. case 1: // Two character padding needed
  2157. outChars[j] = base64[(inData[i] & 0xfc) >> 2];
  2158. outChars[j + 1] = base64[(inData[i] & 0x03) << 4];
  2159. outChars[j + 2] = base64[64]; //Pad
  2160. outChars[j + 3] = base64[64]; //Pad
  2161. j += 4;
  2162. break;
  2163. }
  2164. }
  2165. return j;
  2166. }
  2167. private static int ToBase64_CalculateAndValidateOutputLength(int inputLength, bool insertLineBreaks)
  2168. {
  2169. long outlen = ((long)inputLength) / 3 * 4; // the base length - we want integer division here.
  2170. outlen += ((inputLength % 3) != 0) ? 4 : 0; // at most 4 more chars for the remainder
  2171. if (outlen == 0)
  2172. return 0;
  2173. if (insertLineBreaks)
  2174. {
  2175. long newLines = outlen / base64LineBreakPosition;
  2176. if ((outlen % base64LineBreakPosition) == 0)
  2177. {
  2178. --newLines;
  2179. }
  2180. outlen += newLines * 2; // the number of line break chars we'll add, "\r\n"
  2181. }
  2182. // If we overflow an int then we cannot allocate enough
  2183. // memory to output the value so throw
  2184. if (outlen > int.MaxValue)
  2185. throw new OutOfMemoryException();
  2186. return (int)outlen;
  2187. }
  2188. /// <summary>
  2189. /// Converts the specified string, which encodes binary data as Base64 digits, to the equivalent byte array.
  2190. /// </summary>
  2191. /// <param name="s">The string to convert</param>
  2192. /// <returns>The array of bytes represented by the specified Base64 string.</returns>
  2193. public static byte[] FromBase64String(string s)
  2194. {
  2195. // "s" is an unfortunate parameter name, but we need to keep it for backward compat.
  2196. if (s == null)
  2197. throw new ArgumentNullException(nameof(s));
  2198. unsafe
  2199. {
  2200. fixed (char* sPtr = s)
  2201. {
  2202. return FromBase64CharPtr(sPtr, s.Length);
  2203. }
  2204. }
  2205. }
  2206. public static bool TryFromBase64String(string s, Span<byte> bytes, out int bytesWritten)
  2207. {
  2208. if (s == null)
  2209. {
  2210. throw new ArgumentNullException(nameof(s));
  2211. }
  2212. return TryFromBase64Chars(s.AsSpan(), bytes, out bytesWritten);
  2213. }
  2214. public static bool TryFromBase64Chars(ReadOnlySpan<char> chars, Span<byte> bytes, out int bytesWritten)
  2215. {
  2216. // This is actually local to one of the nested blocks but is being declared at the top as we don't want multiple stackallocs
  2217. // for each iteraton of the loop.
  2218. Span<char> tempBuffer = stackalloc char[4]; // Note: The tempBuffer size could be made larger than 4 but the size must be a multiple of 4.
  2219. bytesWritten = 0;
  2220. while (chars.Length != 0)
  2221. {
  2222. // Attempt to decode a segment that doesn't contain whitespace.
  2223. bool complete = TryDecodeFromUtf16(chars, bytes, out int consumedInThisIteration, out int bytesWrittenInThisIteration);
  2224. bytesWritten += bytesWrittenInThisIteration;
  2225. if (complete)
  2226. return true;
  2227. chars = chars.Slice(consumedInThisIteration);
  2228. bytes = bytes.Slice(bytesWrittenInThisIteration);
  2229. Debug.Assert(chars.Length != 0); // If TryDecodeFromUtf16() consumed the entire buffer, it could not have returned false.
  2230. if (chars[0].IsSpace())
  2231. {
  2232. // If we got here, the very first character not consumed was a whitespace. We can skip past any consecutive whitespace, then continue decoding.
  2233. int indexOfFirstNonSpace = 1;
  2234. for (; ; )
  2235. {
  2236. if (indexOfFirstNonSpace == chars.Length)
  2237. break;
  2238. if (!chars[indexOfFirstNonSpace].IsSpace())
  2239. break;
  2240. indexOfFirstNonSpace++;
  2241. }
  2242. chars = chars.Slice(indexOfFirstNonSpace);
  2243. if ((bytesWrittenInThisIteration % 3) != 0 && chars.Length != 0)
  2244. {
  2245. // If we got here, the last successfully decoded block encountered an end-marker, yet we have trailing non-whitespace characters.
  2246. // That is not allowed.
  2247. bytesWritten = default;
  2248. return false;
  2249. }
  2250. // We now loop again to decode the next run of non-space characters.
  2251. }
  2252. else
  2253. {
  2254. Debug.Assert(chars.Length != 0 && !chars[0].IsSpace());
  2255. // If we got here, it is possible that there is whitespace that occurred in the middle of a 4-byte chunk. That is, we still have
  2256. // up to three Base64 characters that were left undecoded by the fast-path helper because they didn't form a complete 4-byte chunk.
  2257. // This is hopefully the rare case (multiline-formatted base64 message with a non-space character width that's not a multiple of 4.)
  2258. // We'll filter out whitespace and copy the remaining characters into a temporary buffer.
  2259. CopyToTempBufferWithoutWhiteSpace(chars, tempBuffer, out int consumedFromChars, out int charsWritten);
  2260. if ((charsWritten & 0x3) != 0)
  2261. {
  2262. // Even after stripping out whitespace, the number of characters is not divisible by 4. This cannot be a legal Base64 string.
  2263. bytesWritten = default;
  2264. return false;
  2265. }
  2266. tempBuffer = tempBuffer.Slice(0, charsWritten);
  2267. if (!TryDecodeFromUtf16(tempBuffer, bytes, out int consumedFromTempBuffer, out int bytesWrittenFromTempBuffer))
  2268. {
  2269. bytesWritten = default;
  2270. return false;
  2271. }
  2272. bytesWritten += bytesWrittenFromTempBuffer;
  2273. chars = chars.Slice(consumedFromChars);
  2274. bytes = bytes.Slice(bytesWrittenFromTempBuffer);
  2275. if ((bytesWrittenFromTempBuffer % 3) != 0)
  2276. {
  2277. // If we got here, this decode contained one or more padding characters ('='). We can accept trailing whitespace after this
  2278. // but nothing else.
  2279. for (int i = 0; i < chars.Length; i++)
  2280. {
  2281. if (!chars[i].IsSpace())
  2282. {
  2283. bytesWritten = default;
  2284. return false;
  2285. }
  2286. }
  2287. return true;
  2288. }
  2289. // We now loop again to decode the next run of non-space characters.
  2290. }
  2291. }
  2292. return true;
  2293. }
  2294. private static void CopyToTempBufferWithoutWhiteSpace(ReadOnlySpan<char> chars, Span<char> tempBuffer, out int consumed, out int charsWritten)
  2295. {
  2296. Debug.Assert(tempBuffer.Length != 0); // We only bound-check after writing a character to the tempBuffer.
  2297. charsWritten = 0;
  2298. for (int i = 0; i < chars.Length; i++)
  2299. {
  2300. char c = chars[i];
  2301. if (!c.IsSpace())
  2302. {
  2303. tempBuffer[charsWritten++] = c;
  2304. if (charsWritten == tempBuffer.Length)
  2305. {
  2306. consumed = i + 1;
  2307. return;
  2308. }
  2309. }
  2310. }
  2311. consumed = chars.Length;
  2312. }
  2313. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2314. private static bool IsSpace(this char c) => c == ' ' || c == '\t' || c == '\r' || c == '\n';
  2315. /// <summary>
  2316. /// Converts the specified range of a Char array, which encodes binary data as Base64 digits, to the equivalent byte array.
  2317. /// </summary>
  2318. /// <param name="inArray">Chars representing Base64 encoding characters</param>
  2319. /// <param name="offset">A position within the input array.</param>
  2320. /// <param name="length">Number of element to convert.</param>
  2321. /// <returns>The array of bytes represented by the specified Base64 encoding characters.</returns>
  2322. public static byte[] FromBase64CharArray(char[] inArray, int offset, int length)
  2323. {
  2324. if (inArray == null)
  2325. throw new ArgumentNullException(nameof(inArray));
  2326. if (length < 0)
  2327. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
  2328. if (offset < 0)
  2329. throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_GenericPositive);
  2330. if (offset > inArray.Length - length)
  2331. throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_OffsetLength);
  2332. if (inArray.Length == 0)
  2333. {
  2334. return Array.Empty<byte>();
  2335. }
  2336. unsafe
  2337. {
  2338. fixed (char* inArrayPtr = &inArray[0])
  2339. {
  2340. return FromBase64CharPtr(inArrayPtr + offset, length);
  2341. }
  2342. }
  2343. }
  2344. /// <summary>
  2345. /// Convert Base64 encoding characters to bytes:
  2346. /// - Compute result length exactly by actually walking the input;
  2347. /// - Allocate new result array based on computation;
  2348. /// - Decode input into the new array;
  2349. /// </summary>
  2350. /// <param name="inputPtr">Pointer to the first input char</param>
  2351. /// <param name="inputLength">Number of input chars</param>
  2352. /// <returns></returns>
  2353. private static unsafe byte[] FromBase64CharPtr(char* inputPtr, int inputLength)
  2354. {
  2355. // The validity of parameters much be checked by callers, thus we are Critical here.
  2356. Debug.Assert(0 <= inputLength);
  2357. // We need to get rid of any trailing white spaces.
  2358. // Otherwise we would be rejecting input such as "abc= ":
  2359. while (inputLength > 0)
  2360. {
  2361. int lastChar = inputPtr[inputLength - 1];
  2362. if (lastChar != (int)' ' && lastChar != (int)'\n' && lastChar != (int)'\r' && lastChar != (int)'\t')
  2363. break;
  2364. inputLength--;
  2365. }
  2366. // Compute the output length:
  2367. int resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength);
  2368. Debug.Assert(0 <= resultLength);
  2369. // resultLength can be zero. We will still enter FromBase64_Decode and process the input.
  2370. // It may either simply write no bytes (e.g. input = " ") or throw (e.g. input = "ab").
  2371. // Create result byte blob:
  2372. byte[] decodedBytes = new byte[resultLength];
  2373. // Convert Base64 chars into bytes:
  2374. if (!TryFromBase64Chars(new ReadOnlySpan<char>(inputPtr, inputLength), decodedBytes, out int _))
  2375. throw new FormatException(SR.Format_BadBase64Char);
  2376. // Note that the number of bytes written can differ from resultLength if the caller is modifying the array
  2377. // as it is being converted. Silently ignore the failure.
  2378. // Consider throwing exception in an non in-place release.
  2379. // We are done:
  2380. return decodedBytes;
  2381. }
  2382. /// <summary>
  2383. /// Compute the number of bytes encoded in the specified Base 64 char array:
  2384. /// Walk the entire input counting white spaces and padding chars, then compute result length
  2385. /// based on 3 bytes per 4 chars.
  2386. /// </summary>
  2387. private static unsafe int FromBase64_ComputeResultLength(char* inputPtr, int inputLength)
  2388. {
  2389. const uint intEq = (uint)'=';
  2390. const uint intSpace = (uint)' ';
  2391. Debug.Assert(0 <= inputLength);
  2392. char* inputEndPtr = inputPtr + inputLength;
  2393. int usefulInputLength = inputLength;
  2394. int padding = 0;
  2395. while (inputPtr < inputEndPtr)
  2396. {
  2397. uint c = (uint)(*inputPtr);
  2398. inputPtr++;
  2399. // We want to be as fast as possible and filter out spaces with as few comparisons as possible.
  2400. // We end up accepting a number of illegal chars as legal white-space chars.
  2401. // This is ok: as soon as we hit them during actual decode we will recognise them as illegal and throw.
  2402. if (c <= intSpace)
  2403. usefulInputLength--;
  2404. else if (c == intEq)
  2405. {
  2406. usefulInputLength--;
  2407. padding++;
  2408. }
  2409. }
  2410. Debug.Assert(0 <= usefulInputLength);
  2411. // For legal input, we can assume that 0 <= padding < 3. But it may be more for illegal input.
  2412. // We will notice it at decode when we see a '=' at the wrong place.
  2413. Debug.Assert(0 <= padding);
  2414. // Perf: reuse the variable that stored the number of '=' to store the number of bytes encoded by the
  2415. // last group that contains the '=':
  2416. if (padding != 0)
  2417. {
  2418. if (padding == 1)
  2419. padding = 2;
  2420. else if (padding == 2)
  2421. padding = 1;
  2422. else
  2423. throw new FormatException(SR.Format_BadBase64Char);
  2424. }
  2425. // Done:
  2426. return (usefulInputLength / 4) * 3 + padding;
  2427. }
  2428. } // class Convert
  2429. } // namespace