Convert.cs 95 KB

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