Convert.cs 95 KB

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