Convert.cs 96 KB

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