Decimal.DecCalc.cs 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699
  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.Diagnostics;
  5. using System.Numerics;
  6. using System.Runtime.CompilerServices;
  7. using System.Runtime.InteropServices;
  8. using Internal.Runtime.CompilerServices;
  9. using X86 = System.Runtime.Intrinsics.X86;
  10. namespace System
  11. {
  12. public partial struct Decimal
  13. {
  14. // Low level accessors used by a DecCalc and formatting
  15. internal uint High => (uint)hi;
  16. internal uint Low => (uint)lo;
  17. internal uint Mid => (uint)mid;
  18. internal bool IsNegative => flags < 0;
  19. internal int Scale => (byte)(flags >> ScaleShift);
  20. #if BIGENDIAN
  21. private ulong Low64 => ((ulong)Mid << 32) | Low;
  22. #else
  23. private ulong Low64 => Unsafe.As<int, ulong>(ref Unsafe.AsRef(in lo));
  24. #endif
  25. private static ref DecCalc AsMutable(ref decimal d) => ref Unsafe.As<decimal, DecCalc>(ref d);
  26. #region APIs need by number formatting.
  27. internal static uint DecDivMod1E9(ref decimal value)
  28. {
  29. return DecCalc.DecDivMod1E9(ref AsMutable(ref value));
  30. }
  31. #endregion
  32. /// <summary>
  33. /// Class that contains all the mathematical calculations for decimal. Most of which have been ported from oleaut32.
  34. /// </summary>
  35. [StructLayout(LayoutKind.Explicit)]
  36. private struct DecCalc
  37. {
  38. // NOTE: Do not change the offsets of these fields. This structure must have the same layout as Decimal.
  39. [FieldOffset(0)]
  40. private uint uflags;
  41. [FieldOffset(4)]
  42. private uint uhi;
  43. [FieldOffset(8)]
  44. private uint ulo;
  45. [FieldOffset(12)]
  46. private uint umid;
  47. /// <summary>
  48. /// The low and mid fields combined in little-endian order
  49. /// </summary>
  50. [FieldOffset(8)]
  51. private ulong ulomidLE;
  52. private uint High
  53. {
  54. get => uhi;
  55. set => uhi = value;
  56. }
  57. private uint Low
  58. {
  59. get => ulo;
  60. set => ulo = value;
  61. }
  62. private uint Mid
  63. {
  64. get => umid;
  65. set => umid = value;
  66. }
  67. private bool IsNegative => (int)uflags < 0;
  68. private int Scale => (byte)(uflags >> ScaleShift);
  69. private ulong Low64
  70. {
  71. #if BIGENDIAN
  72. get { return ((ulong)umid << 32) | ulo; }
  73. set { umid = (uint)(value >> 32); ulo = (uint)value; }
  74. #else
  75. get => ulomidLE;
  76. set => ulomidLE = value;
  77. #endif
  78. }
  79. private const uint SignMask = 0x80000000;
  80. private const uint ScaleMask = 0x00FF0000;
  81. private const int DEC_SCALE_MAX = 28;
  82. private const uint TenToPowerNine = 1000000000;
  83. private const ulong TenToPowerEighteen = 1000000000000000000;
  84. // The maximum power of 10 that a 32 bit integer can store
  85. private const int MaxInt32Scale = 9;
  86. // The maximum power of 10 that a 64 bit integer can store
  87. private const int MaxInt64Scale = 19;
  88. // Fast access for 10^n where n is 0-9
  89. private static readonly uint[] s_powers10 = new uint[] {
  90. 1,
  91. 10,
  92. 100,
  93. 1000,
  94. 10000,
  95. 100000,
  96. 1000000,
  97. 10000000,
  98. 100000000,
  99. 1000000000
  100. };
  101. // Fast access for 10^n where n is 1-19
  102. private static readonly ulong[] s_ulongPowers10 = new ulong[] {
  103. 10,
  104. 100,
  105. 1000,
  106. 10000,
  107. 100000,
  108. 1000000,
  109. 10000000,
  110. 100000000,
  111. 1000000000,
  112. 10000000000,
  113. 100000000000,
  114. 1000000000000,
  115. 10000000000000,
  116. 100000000000000,
  117. 1000000000000000,
  118. 10000000000000000,
  119. 100000000000000000,
  120. 1000000000000000000,
  121. 10000000000000000000,
  122. };
  123. private static readonly double[] s_doublePowers10 = new double[] {
  124. 1, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  125. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  126. 1e20, 1e21, 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28, 1e29,
  127. 1e30, 1e31, 1e32, 1e33, 1e34, 1e35, 1e36, 1e37, 1e38, 1e39,
  128. 1e40, 1e41, 1e42, 1e43, 1e44, 1e45, 1e46, 1e47, 1e48, 1e49,
  129. 1e50, 1e51, 1e52, 1e53, 1e54, 1e55, 1e56, 1e57, 1e58, 1e59,
  130. 1e60, 1e61, 1e62, 1e63, 1e64, 1e65, 1e66, 1e67, 1e68, 1e69,
  131. 1e70, 1e71, 1e72, 1e73, 1e74, 1e75, 1e76, 1e77, 1e78, 1e79,
  132. 1e80
  133. };
  134. // Used to fill uninitialized stack variables with non-zero pattern in debug builds
  135. [Conditional("DEBUG")]
  136. private static unsafe void DebugPoison<T>(ref T s) where T : unmanaged
  137. {
  138. MemoryMarshal.AsBytes(MemoryMarshal.CreateSpan(ref s, 1)).Fill(0xCD);
  139. }
  140. #region Decimal Math Helpers
  141. private static unsafe uint GetExponent(float f)
  142. {
  143. // Based on pulling out the exp from this single struct layout
  144. // typedef struct {
  145. // ULONG mant:23;
  146. // ULONG exp:8;
  147. // ULONG sign:1;
  148. // } SNGSTRUCT;
  149. return (byte)(*(uint*)&f >> 23);
  150. }
  151. private static unsafe uint GetExponent(double d)
  152. {
  153. // Based on pulling out the exp from this double struct layout
  154. // typedef struct {
  155. // DWORDLONG mant:52;
  156. // DWORDLONG signexp:12;
  157. // } DBLSTRUCT;
  158. return (uint)(*(ulong*)&d >> 52) & 0x7FFu;
  159. }
  160. private static ulong UInt32x32To64(uint a, uint b)
  161. {
  162. return (ulong)a * (ulong)b;
  163. }
  164. private static void UInt64x64To128(ulong a, ulong b, ref DecCalc result)
  165. {
  166. ulong low = UInt32x32To64((uint)a, (uint)b); // lo partial prod
  167. ulong mid = UInt32x32To64((uint)a, (uint)(b >> 32)); // mid 1 partial prod
  168. ulong high = UInt32x32To64((uint)(a >> 32), (uint)(b >> 32));
  169. high += mid >> 32;
  170. low += mid <<= 32;
  171. if (low < mid) // test for carry
  172. high++;
  173. mid = UInt32x32To64((uint)(a >> 32), (uint)b);
  174. high += mid >> 32;
  175. low += mid <<= 32;
  176. if (low < mid) // test for carry
  177. high++;
  178. if (high > uint.MaxValue)
  179. Number.ThrowOverflowException(TypeCode.Decimal);
  180. result.Low64 = low;
  181. result.High = (uint)high;
  182. }
  183. /// <summary>
  184. /// Do full divide, yielding 96-bit result and 32-bit remainder.
  185. /// </summary>
  186. /// <param name="bufNum">96-bit dividend as array of uints, least-sig first</param>
  187. /// <param name="den">32-bit divisor</param>
  188. /// <returns>Returns remainder. Quotient overwrites dividend.</returns>
  189. private static uint Div96By32(ref Buf12 bufNum, uint den)
  190. {
  191. // TODO: https://github.com/dotnet/coreclr/issues/3439
  192. ulong tmp, div;
  193. if (bufNum.U2 != 0)
  194. {
  195. tmp = bufNum.High64;
  196. div = tmp / den;
  197. bufNum.High64 = div;
  198. tmp = ((tmp - (uint)div * den) << 32) | bufNum.U0;
  199. if (tmp == 0)
  200. return 0;
  201. uint div32 = (uint)(tmp / den);
  202. bufNum.U0 = div32;
  203. return (uint)tmp - div32 * den;
  204. }
  205. tmp = bufNum.Low64;
  206. if (tmp == 0)
  207. return 0;
  208. div = tmp / den;
  209. bufNum.Low64 = div;
  210. return (uint)(tmp - div * den);
  211. }
  212. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  213. private static bool Div96ByConst(ref ulong high64, ref uint low, uint pow)
  214. {
  215. #if BIT64
  216. ulong div64 = high64 / pow;
  217. uint div = (uint)((((high64 - div64 * pow) << 32) + low) / pow);
  218. if (low == div * pow)
  219. {
  220. high64 = div64;
  221. low = div;
  222. return true;
  223. }
  224. #else
  225. // 32-bit RyuJIT doesn't convert 64-bit division by constant into multiplication by reciprocal. Do half-width divisions instead.
  226. Debug.Assert(pow <= ushort.MaxValue);
  227. uint num, mid32, low16, div;
  228. if (high64 <= uint.MaxValue)
  229. {
  230. num = (uint)high64;
  231. mid32 = num / pow;
  232. num = (num - mid32 * pow) << 16;
  233. num += low >> 16;
  234. low16 = num / pow;
  235. num = (num - low16 * pow) << 16;
  236. num += (ushort)low;
  237. div = num / pow;
  238. if (num == div * pow)
  239. {
  240. high64 = mid32;
  241. low = (low16 << 16) + div;
  242. return true;
  243. }
  244. }
  245. else
  246. {
  247. num = (uint)(high64 >> 32);
  248. uint high32 = num / pow;
  249. num = (num - high32 * pow) << 16;
  250. num += (uint)high64 >> 16;
  251. mid32 = num / pow;
  252. num = (num - mid32 * pow) << 16;
  253. num += (ushort)high64;
  254. div = num / pow;
  255. num = (num - div * pow) << 16;
  256. mid32 = div + (mid32 << 16);
  257. num += low >> 16;
  258. low16 = num / pow;
  259. num = (num - low16 * pow) << 16;
  260. num += (ushort)low;
  261. div = num / pow;
  262. if (num == div * pow)
  263. {
  264. high64 = ((ulong)high32 << 32) | mid32;
  265. low = (low16 << 16) + div;
  266. return true;
  267. }
  268. }
  269. #endif
  270. return false;
  271. }
  272. /// <summary>
  273. /// Normalize (unscale) the number by trying to divide out 10^8, 10^4, 10^2, and 10^1.
  274. /// If a division by one of these powers returns a zero remainder, then we keep the quotient.
  275. /// </summary>
  276. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  277. private static void Unscale(ref uint low, ref ulong high64, ref int scale)
  278. {
  279. // Since 10 = 2 * 5, there must be a factor of 2 for every power of 10 we can extract.
  280. // We use this as a quick test on whether to try a given power.
  281. #if BIT64
  282. while ((byte)low == 0 && scale >= 8 && Div96ByConst(ref high64, ref low, 100000000))
  283. scale -= 8;
  284. if ((low & 0xF) == 0 && scale >= 4 && Div96ByConst(ref high64, ref low, 10000))
  285. scale -= 4;
  286. #else
  287. while ((low & 0xF) == 0 && scale >= 4 && Div96ByConst(ref high64, ref low, 10000))
  288. scale -= 4;
  289. #endif
  290. if ((low & 3) == 0 && scale >= 2 && Div96ByConst(ref high64, ref low, 100))
  291. scale -= 2;
  292. if ((low & 1) == 0 && scale >= 1 && Div96ByConst(ref high64, ref low, 10))
  293. scale--;
  294. }
  295. /// <summary>
  296. /// Do partial divide, yielding 32-bit result and 64-bit remainder.
  297. /// Divisor must be larger than upper 64 bits of dividend.
  298. /// </summary>
  299. /// <param name="bufNum">96-bit dividend as array of uints, least-sig first</param>
  300. /// <param name="den">64-bit divisor</param>
  301. /// <returns>Returns quotient. Remainder overwrites lower 64-bits of dividend.</returns>
  302. private static uint Div96By64(ref Buf12 bufNum, ulong den)
  303. {
  304. Debug.Assert(den > bufNum.High64);
  305. uint quo;
  306. ulong num;
  307. uint num2 = bufNum.U2;
  308. if (num2 == 0)
  309. {
  310. num = bufNum.Low64;
  311. if (num < den)
  312. // Result is zero. Entire dividend is remainder.
  313. return 0;
  314. // TODO: https://github.com/dotnet/coreclr/issues/3439
  315. quo = (uint)(num / den);
  316. num -= quo * den; // remainder
  317. bufNum.Low64 = num;
  318. return quo;
  319. }
  320. uint denHigh32 = (uint)(den >> 32);
  321. if (num2 >= denHigh32)
  322. {
  323. // Divide would overflow. Assume a quotient of 2^32, and set
  324. // up remainder accordingly.
  325. //
  326. num = bufNum.Low64;
  327. num -= den << 32;
  328. quo = 0;
  329. // Remainder went negative. Add divisor back in until it's positive,
  330. // a max of 2 times.
  331. //
  332. do
  333. {
  334. quo--;
  335. num += den;
  336. } while (num >= den);
  337. bufNum.Low64 = num;
  338. return quo;
  339. }
  340. // Hardware divide won't overflow
  341. //
  342. ulong num64 = bufNum.High64;
  343. if (num64 < denHigh32)
  344. // Result is zero. Entire dividend is remainder.
  345. //
  346. return 0;
  347. // TODO: https://github.com/dotnet/coreclr/issues/3439
  348. quo = (uint)(num64 / denHigh32);
  349. num = bufNum.U0 | ((num64 - quo * denHigh32) << 32); // remainder
  350. // Compute full remainder, rem = dividend - (quo * divisor).
  351. //
  352. ulong prod = UInt32x32To64(quo, (uint)den); // quo * lo divisor
  353. num -= prod;
  354. if (num > ~prod)
  355. {
  356. // Remainder went negative. Add divisor back in until it's positive,
  357. // a max of 2 times.
  358. //
  359. do
  360. {
  361. quo--;
  362. num += den;
  363. } while (num >= den);
  364. }
  365. bufNum.Low64 = num;
  366. return quo;
  367. }
  368. /// <summary>
  369. /// Do partial divide, yielding 32-bit result and 96-bit remainder.
  370. /// Top divisor uint must be larger than top dividend uint. This is
  371. /// assured in the initial call because the divisor is normalized
  372. /// and the dividend can't be. In subsequent calls, the remainder
  373. /// is multiplied by 10^9 (max), so it can be no more than 1/4 of
  374. /// the divisor which is effectively multiplied by 2^32 (4 * 10^9).
  375. /// </summary>
  376. /// <param name="bufNum">128-bit dividend as array of uints, least-sig first</param>
  377. /// <param name="bufDen">96-bit divisor</param>
  378. /// <returns>Returns quotient. Remainder overwrites lower 96-bits of dividend.</returns>
  379. private static uint Div128By96(ref Buf16 bufNum, ref Buf12 bufDen)
  380. {
  381. Debug.Assert(bufDen.U2 > bufNum.U3);
  382. ulong dividend = bufNum.High64;
  383. uint den = bufDen.U2;
  384. if (dividend < den)
  385. // Result is zero. Entire dividend is remainder.
  386. //
  387. return 0;
  388. // TODO: https://github.com/dotnet/coreclr/issues/3439
  389. uint quo = (uint)(dividend / den);
  390. uint remainder = (uint)dividend - quo * den;
  391. // Compute full remainder, rem = dividend - (quo * divisor).
  392. //
  393. ulong prod1 = UInt32x32To64(quo, bufDen.U0); // quo * lo divisor
  394. ulong prod2 = UInt32x32To64(quo, bufDen.U1); // quo * mid divisor
  395. prod2 += prod1 >> 32;
  396. prod1 = (uint)prod1 | (prod2 << 32);
  397. prod2 >>= 32;
  398. ulong num = bufNum.Low64;
  399. num -= prod1;
  400. remainder -= (uint)prod2;
  401. // Propagate carries
  402. //
  403. if (num > ~prod1)
  404. {
  405. remainder--;
  406. if (remainder < ~(uint)prod2)
  407. goto PosRem;
  408. }
  409. else if (remainder <= ~(uint)prod2)
  410. goto PosRem;
  411. {
  412. // Remainder went negative. Add divisor back in until it's positive,
  413. // a max of 2 times.
  414. //
  415. prod1 = bufDen.Low64;
  416. while (true)
  417. {
  418. quo--;
  419. num += prod1;
  420. remainder += den;
  421. if (num < prod1)
  422. {
  423. // Detected carry. Check for carry out of top
  424. // before adding it in.
  425. //
  426. if (remainder++ < den)
  427. break;
  428. }
  429. if (remainder < den)
  430. break; // detected carry
  431. }
  432. }
  433. PosRem:
  434. bufNum.Low64 = num;
  435. bufNum.U2 = remainder;
  436. return quo;
  437. }
  438. /// <summary>
  439. /// Multiply the two numbers. The low 96 bits of the result overwrite
  440. /// the input. The last 32 bits of the product are the return value.
  441. /// </summary>
  442. /// <param name="bufNum">96-bit number as array of uints, least-sig first</param>
  443. /// <param name="power">Scale factor to multiply by</param>
  444. /// <returns>Returns highest 32 bits of product</returns>
  445. private static uint IncreaseScale(ref Buf12 bufNum, uint power)
  446. {
  447. ulong tmp = UInt32x32To64(bufNum.U0, power);
  448. bufNum.U0 = (uint)tmp;
  449. tmp >>= 32;
  450. tmp += UInt32x32To64(bufNum.U1, power);
  451. bufNum.U1 = (uint)tmp;
  452. tmp >>= 32;
  453. tmp += UInt32x32To64(bufNum.U2, power);
  454. bufNum.U2 = (uint)tmp;
  455. return (uint)(tmp >> 32);
  456. }
  457. private static void IncreaseScale64(ref Buf12 bufNum, uint power)
  458. {
  459. ulong tmp = UInt32x32To64(bufNum.U0, power);
  460. bufNum.U0 = (uint)tmp;
  461. tmp >>= 32;
  462. tmp += UInt32x32To64(bufNum.U1, power);
  463. bufNum.High64 = tmp;
  464. }
  465. /// <summary>
  466. /// See if we need to scale the result to fit it in 96 bits.
  467. /// Perform needed scaling. Adjust scale factor accordingly.
  468. /// </summary>
  469. /// <param name="bufRes">Array of uints with value, least-significant first</param>
  470. /// <param name="hiRes">Index of last non-zero value in bufRes</param>
  471. /// <param name="scale">Scale factor for this value, range 0 - 2 * DEC_SCALE_MAX</param>
  472. /// <returns>Returns new scale factor. bufRes updated in place, always 3 uints.</returns>
  473. private static unsafe int ScaleResult(Buf24* bufRes, uint hiRes, int scale)
  474. {
  475. Debug.Assert(hiRes < bufRes->Length);
  476. uint* result = (uint*)bufRes;
  477. // See if we need to scale the result. The combined scale must
  478. // be <= DEC_SCALE_MAX and the upper 96 bits must be zero.
  479. //
  480. // Start by figuring a lower bound on the scaling needed to make
  481. // the upper 96 bits zero. hiRes is the index into result[]
  482. // of the highest non-zero uint.
  483. //
  484. int newScale = 0;
  485. if (hiRes > 2)
  486. {
  487. newScale = (int)hiRes * 32 - 64 - 1;
  488. newScale -= BitOperations.LeadingZeroCount(result[hiRes]);
  489. // Multiply bit position by log10(2) to figure it's power of 10.
  490. // We scale the log by 256. log(2) = .30103, * 256 = 77. Doing this
  491. // with a multiply saves a 96-byte lookup table. The power returned
  492. // is <= the power of the number, so we must add one power of 10
  493. // to make it's integer part zero after dividing by 256.
  494. //
  495. // Note: the result of this multiplication by an approximation of
  496. // log10(2) have been exhaustively checked to verify it gives the
  497. // correct result. (There were only 95 to check...)
  498. //
  499. newScale = ((newScale * 77) >> 8) + 1;
  500. // newScale = min scale factor to make high 96 bits zero, 0 - 29.
  501. // This reduces the scale factor of the result. If it exceeds the
  502. // current scale of the result, we'll overflow.
  503. //
  504. if (newScale > scale)
  505. goto ThrowOverflow;
  506. }
  507. // Make sure we scale by enough to bring the current scale factor
  508. // into valid range.
  509. //
  510. if (newScale < scale - DEC_SCALE_MAX)
  511. newScale = scale - DEC_SCALE_MAX;
  512. if (newScale != 0)
  513. {
  514. // Scale by the power of 10 given by newScale. Note that this is
  515. // NOT guaranteed to bring the number within 96 bits -- it could
  516. // be 1 power of 10 short.
  517. //
  518. scale -= newScale;
  519. uint sticky = 0;
  520. uint quotient, remainder = 0;
  521. while (true)
  522. {
  523. sticky |= remainder; // record remainder as sticky bit
  524. uint power;
  525. // Scaling loop specialized for each power of 10 because division by constant is an order of magnitude faster (especially for 64-bit division that's actually done by 128bit DIV on x64)
  526. switch (newScale)
  527. {
  528. case 1:
  529. power = DivByConst(result, hiRes, out quotient, out remainder, 10);
  530. break;
  531. case 2:
  532. power = DivByConst(result, hiRes, out quotient, out remainder, 100);
  533. break;
  534. case 3:
  535. power = DivByConst(result, hiRes, out quotient, out remainder, 1000);
  536. break;
  537. case 4:
  538. power = DivByConst(result, hiRes, out quotient, out remainder, 10000);
  539. break;
  540. #if BIT64
  541. case 5:
  542. power = DivByConst(result, hiRes, out quotient, out remainder, 100000);
  543. break;
  544. case 6:
  545. power = DivByConst(result, hiRes, out quotient, out remainder, 1000000);
  546. break;
  547. case 7:
  548. power = DivByConst(result, hiRes, out quotient, out remainder, 10000000);
  549. break;
  550. case 8:
  551. power = DivByConst(result, hiRes, out quotient, out remainder, 100000000);
  552. break;
  553. default:
  554. power = DivByConst(result, hiRes, out quotient, out remainder, TenToPowerNine);
  555. break;
  556. #else
  557. default:
  558. goto case 4;
  559. #endif
  560. }
  561. result[hiRes] = quotient;
  562. // If first quotient was 0, update hiRes.
  563. //
  564. if (quotient == 0 && hiRes != 0)
  565. hiRes--;
  566. #if BIT64
  567. newScale -= MaxInt32Scale;
  568. #else
  569. newScale -= 4;
  570. #endif
  571. if (newScale > 0)
  572. continue; // scale some more
  573. // If we scaled enough, hiRes would be 2 or less. If not,
  574. // divide by 10 more.
  575. //
  576. if (hiRes > 2)
  577. {
  578. if (scale == 0)
  579. goto ThrowOverflow;
  580. newScale = 1;
  581. scale--;
  582. continue; // scale by 10
  583. }
  584. // Round final result. See if remainder >= 1/2 of divisor.
  585. // If remainder == 1/2 divisor, round up if odd or sticky bit set.
  586. //
  587. power >>= 1; // power of 10 always even
  588. if (power <= remainder && (power < remainder || ((result[0] & 1) | sticky) != 0) && ++result[0] == 0)
  589. {
  590. uint cur = 0;
  591. do
  592. {
  593. Debug.Assert(cur + 1 < bufRes->Length);
  594. }
  595. while (++result[++cur] == 0);
  596. if (cur > 2)
  597. {
  598. // The rounding caused us to carry beyond 96 bits.
  599. // Scale by 10 more.
  600. //
  601. if (scale == 0)
  602. goto ThrowOverflow;
  603. hiRes = cur;
  604. sticky = 0; // no sticky bit
  605. remainder = 0; // or remainder
  606. newScale = 1;
  607. scale--;
  608. continue; // scale by 10
  609. }
  610. }
  611. break;
  612. } // while (true)
  613. }
  614. return scale;
  615. ThrowOverflow:
  616. Number.ThrowOverflowException(TypeCode.Decimal);
  617. return 0;
  618. }
  619. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  620. private static unsafe uint DivByConst(uint* result, uint hiRes, out uint quotient, out uint remainder, uint power)
  621. {
  622. uint high = result[hiRes];
  623. remainder = high - (quotient = high / power) * power;
  624. for (uint i = hiRes - 1; (int)i >= 0; i--)
  625. {
  626. #if BIT64
  627. ulong num = result[i] + ((ulong)remainder << 32);
  628. remainder = (uint)num - (result[i] = (uint)(num / power)) * power;
  629. #else
  630. // 32-bit RyuJIT doesn't convert 64-bit division by constant into multiplication by reciprocal. Do half-width divisions instead.
  631. Debug.Assert(power <= ushort.MaxValue);
  632. #if BIGENDIAN
  633. const int low16 = 2, high16 = 0;
  634. #else
  635. const int low16 = 0, high16 = 2;
  636. #endif
  637. // byte* is used here because Roslyn doesn't do constant propagation for pointer arithmetic
  638. uint num = *(ushort*)((byte*)result + i * 4 + high16) + (remainder << 16);
  639. uint div = num / power;
  640. remainder = num - div * power;
  641. *(ushort*)((byte*)result + i * 4 + high16) = (ushort)div;
  642. num = *(ushort*)((byte*)result + i * 4 + low16) + (remainder << 16);
  643. div = num / power;
  644. remainder = num - div * power;
  645. *(ushort*)((byte*)result + i * 4 + low16) = (ushort)div;
  646. #endif
  647. }
  648. return power;
  649. }
  650. /// <summary>
  651. /// Adjust the quotient to deal with an overflow.
  652. /// We need to divide by 10, feed in the high bit to undo the overflow and then round as required.
  653. /// </summary>
  654. private static int OverflowUnscale(ref Buf12 bufQuo, int scale, bool sticky)
  655. {
  656. if (--scale < 0)
  657. Number.ThrowOverflowException(TypeCode.Decimal);
  658. Debug.Assert(bufQuo.U2 == 0);
  659. // We have overflown, so load the high bit with a one.
  660. const ulong highbit = 1UL << 32;
  661. bufQuo.U2 = (uint)(highbit / 10);
  662. ulong tmp = ((highbit % 10) << 32) + bufQuo.U1;
  663. uint div = (uint)(tmp / 10);
  664. bufQuo.U1 = div;
  665. tmp = ((tmp - div * 10) << 32) + bufQuo.U0;
  666. div = (uint)(tmp / 10);
  667. bufQuo.U0 = div;
  668. uint remainder = (uint)(tmp - div * 10);
  669. // The remainder is the last digit that does not fit, so we can use it to work out if we need to round up
  670. if (remainder > 5 || remainder == 5 && (sticky || (bufQuo.U0 & 1) != 0))
  671. Add32To96(ref bufQuo, 1);
  672. return scale;
  673. }
  674. /// <summary>
  675. /// Determine the max power of 10, &lt;= 9, that the quotient can be scaled
  676. /// up by and still fit in 96 bits.
  677. /// </summary>
  678. /// <param name="bufQuo">96-bit quotient</param>
  679. /// <param name="scale ">Scale factor of quotient, range -DEC_SCALE_MAX to DEC_SCALE_MAX-1</param>
  680. /// <returns>power of 10 to scale by</returns>
  681. private static int SearchScale(ref Buf12 bufQuo, int scale)
  682. {
  683. const uint OVFL_MAX_9_HI = 4;
  684. const uint OVFL_MAX_8_HI = 42;
  685. const uint OVFL_MAX_7_HI = 429;
  686. const uint OVFL_MAX_6_HI = 4294;
  687. const uint OVFL_MAX_5_HI = 42949;
  688. const uint OVFL_MAX_4_HI = 429496;
  689. const uint OVFL_MAX_3_HI = 4294967;
  690. const uint OVFL_MAX_2_HI = 42949672;
  691. const uint OVFL_MAX_1_HI = 429496729;
  692. const ulong OVFL_MAX_9_MIDLO = 5441186219426131129;
  693. uint resHi = bufQuo.U2;
  694. ulong resMidLo = bufQuo.Low64;
  695. int curScale = 0;
  696. // Quick check to stop us from trying to scale any more.
  697. //
  698. if (resHi > OVFL_MAX_1_HI)
  699. {
  700. goto HaveScale;
  701. }
  702. PowerOvfl[] powerOvfl = PowerOvflValues;
  703. if (scale > DEC_SCALE_MAX - 9)
  704. {
  705. // We can't scale by 10^9 without exceeding the max scale factor.
  706. // See if we can scale to the max. If not, we'll fall into
  707. // standard search for scale factor.
  708. //
  709. curScale = DEC_SCALE_MAX - scale;
  710. if (resHi < powerOvfl[curScale - 1].Hi)
  711. goto HaveScale;
  712. }
  713. else if (resHi < OVFL_MAX_9_HI || resHi == OVFL_MAX_9_HI && resMidLo <= OVFL_MAX_9_MIDLO)
  714. return 9;
  715. // Search for a power to scale by < 9. Do a binary search.
  716. //
  717. if (resHi > OVFL_MAX_5_HI)
  718. {
  719. if (resHi > OVFL_MAX_3_HI)
  720. {
  721. curScale = 2;
  722. if (resHi > OVFL_MAX_2_HI)
  723. curScale--;
  724. }
  725. else
  726. {
  727. curScale = 4;
  728. if (resHi > OVFL_MAX_4_HI)
  729. curScale--;
  730. }
  731. }
  732. else
  733. {
  734. if (resHi > OVFL_MAX_7_HI)
  735. {
  736. curScale = 6;
  737. if (resHi > OVFL_MAX_6_HI)
  738. curScale--;
  739. }
  740. else
  741. {
  742. curScale = 8;
  743. if (resHi > OVFL_MAX_8_HI)
  744. curScale--;
  745. }
  746. }
  747. // In all cases, we already found we could not use the power one larger.
  748. // So if we can use this power, it is the biggest, and we're done. If
  749. // we can't use this power, the one below it is correct for all cases
  750. // unless it's 10^1 -- we might have to go to 10^0 (no scaling).
  751. //
  752. if (resHi == powerOvfl[curScale - 1].Hi && resMidLo > powerOvfl[curScale - 1].MidLo)
  753. curScale--;
  754. HaveScale:
  755. // curScale = largest power of 10 we can scale by without overflow,
  756. // curScale < 9. See if this is enough to make scale factor
  757. // positive if it isn't already.
  758. //
  759. if (curScale + scale < 0)
  760. Number.ThrowOverflowException(TypeCode.Decimal);
  761. return curScale;
  762. }
  763. /// <summary>
  764. /// Add a 32-bit uint to an array of 3 uints representing a 96-bit integer.
  765. /// </summary>
  766. /// <returns>Returns false if there is an overflow</returns>
  767. private static bool Add32To96(ref Buf12 bufNum, uint value)
  768. {
  769. if ((bufNum.Low64 += value) < value)
  770. {
  771. if (++bufNum.U2 == 0)
  772. return false;
  773. }
  774. return true;
  775. }
  776. /// <summary>
  777. /// Adds or subtracts two decimal values.
  778. /// On return, d1 contains the result of the operation and d2 is trashed.
  779. /// </summary>
  780. /// <param name="sign">True means subtract and false means add.</param>
  781. internal static unsafe void DecAddSub(ref DecCalc d1, ref DecCalc d2, bool sign)
  782. {
  783. ulong low64 = d1.Low64;
  784. uint high = d1.High, flags = d1.uflags, d2flags = d2.uflags;
  785. uint xorflags = d2flags ^ flags;
  786. sign ^= (xorflags & SignMask) != 0;
  787. if ((xorflags & ScaleMask) == 0)
  788. {
  789. // Scale factors are equal, no alignment necessary.
  790. //
  791. goto AlignedAdd;
  792. }
  793. else
  794. {
  795. // Scale factors are not equal. Assume that a larger scale
  796. // factor (more decimal places) is likely to mean that number
  797. // is smaller. Start by guessing that the right operand has
  798. // the larger scale factor. The result will have the larger
  799. // scale factor.
  800. //
  801. uint d1flags = flags;
  802. flags = d2flags & ScaleMask | flags & SignMask; // scale factor of "smaller", but sign of "larger"
  803. int scale = (int)(flags - d1flags) >> ScaleShift;
  804. if (scale < 0)
  805. {
  806. // Guessed scale factor wrong. Swap operands.
  807. //
  808. scale = -scale;
  809. flags = d1flags;
  810. if (sign)
  811. flags ^= SignMask;
  812. low64 = d2.Low64;
  813. high = d2.High;
  814. d2 = d1;
  815. }
  816. uint power;
  817. ulong tmp64, tmpLow;
  818. // d1 will need to be multiplied by 10^scale so
  819. // it will have the same scale as d2. We could be
  820. // extending it to up to 192 bits of precision.
  821. // Scan for zeros in the upper words.
  822. //
  823. if (high == 0)
  824. {
  825. if (low64 <= uint.MaxValue)
  826. {
  827. if ((uint)low64 == 0)
  828. {
  829. // Left arg is zero, return right.
  830. //
  831. uint signFlags = flags & SignMask;
  832. if (sign)
  833. signFlags ^= SignMask;
  834. d1 = d2;
  835. d1.uflags = d2.uflags & ScaleMask | signFlags;
  836. return;
  837. }
  838. do
  839. {
  840. if (scale <= MaxInt32Scale)
  841. {
  842. low64 = UInt32x32To64((uint)low64, s_powers10[scale]);
  843. goto AlignedAdd;
  844. }
  845. scale -= MaxInt32Scale;
  846. low64 = UInt32x32To64((uint)low64, TenToPowerNine);
  847. } while (low64 <= uint.MaxValue);
  848. }
  849. do
  850. {
  851. power = TenToPowerNine;
  852. if (scale < MaxInt32Scale)
  853. power = s_powers10[scale];
  854. tmpLow = UInt32x32To64((uint)low64, power);
  855. tmp64 = UInt32x32To64((uint)(low64 >> 32), power) + (tmpLow >> 32);
  856. low64 = (uint)tmpLow + (tmp64 << 32);
  857. high = (uint)(tmp64 >> 32);
  858. if ((scale -= MaxInt32Scale) <= 0)
  859. goto AlignedAdd;
  860. } while (high == 0);
  861. }
  862. while (true)
  863. {
  864. // Scaling won't make it larger than 4 uints
  865. //
  866. power = TenToPowerNine;
  867. if (scale < MaxInt32Scale)
  868. power = s_powers10[scale];
  869. tmpLow = UInt32x32To64((uint)low64, power);
  870. tmp64 = UInt32x32To64((uint)(low64 >> 32), power) + (tmpLow >> 32);
  871. low64 = (uint)tmpLow + (tmp64 << 32);
  872. tmp64 >>= 32;
  873. tmp64 += UInt32x32To64(high, power);
  874. scale -= MaxInt32Scale;
  875. if (tmp64 > uint.MaxValue)
  876. break;
  877. high = (uint)tmp64;
  878. // Result fits in 96 bits. Use standard aligned add.
  879. if (scale <= 0)
  880. goto AlignedAdd;
  881. }
  882. // Have to scale by a bunch. Move the number to a buffer where it has room to grow as it's scaled.
  883. //
  884. Unsafe.SkipInit(out Buf24 bufNum);
  885. DebugPoison(ref bufNum);
  886. bufNum.Low64 = low64;
  887. bufNum.Mid64 = tmp64;
  888. uint hiProd = 3;
  889. // Scaling loop, up to 10^9 at a time. hiProd stays updated with index of highest non-zero uint.
  890. //
  891. for (; scale > 0; scale -= MaxInt32Scale)
  892. {
  893. power = TenToPowerNine;
  894. if (scale < MaxInt32Scale)
  895. power = s_powers10[scale];
  896. tmp64 = 0;
  897. uint* rgulNum = (uint*)&bufNum;
  898. for (uint cur = 0; ;)
  899. {
  900. Debug.Assert(cur < bufNum.Length);
  901. tmp64 += UInt32x32To64(rgulNum[cur], power);
  902. rgulNum[cur] = (uint)tmp64;
  903. cur++;
  904. tmp64 >>= 32;
  905. if (cur > hiProd)
  906. break;
  907. }
  908. if ((uint)tmp64 != 0)
  909. {
  910. // We're extending the result by another uint.
  911. Debug.Assert(hiProd + 1 < bufNum.Length);
  912. rgulNum[++hiProd] = (uint)tmp64;
  913. }
  914. }
  915. // Scaling complete, do the add. Could be subtract if signs differ.
  916. //
  917. tmp64 = bufNum.Low64;
  918. low64 = d2.Low64;
  919. uint tmpHigh = bufNum.U2;
  920. high = d2.High;
  921. if (sign)
  922. {
  923. // Signs differ, subtract.
  924. //
  925. low64 = tmp64 - low64;
  926. high = tmpHigh - high;
  927. // Propagate carry
  928. //
  929. if (low64 > tmp64)
  930. {
  931. high--;
  932. if (high < tmpHigh)
  933. goto NoCarry;
  934. }
  935. else if (high <= tmpHigh)
  936. goto NoCarry;
  937. // Carry the subtraction into the higher bits.
  938. //
  939. uint* number = (uint*)&bufNum;
  940. uint cur = 3;
  941. do
  942. {
  943. Debug.Assert(cur < bufNum.Length);
  944. } while (number[cur++]-- == 0);
  945. Debug.Assert(hiProd < bufNum.Length);
  946. if (number[hiProd] == 0 && --hiProd <= 2)
  947. goto ReturnResult;
  948. }
  949. else
  950. {
  951. // Signs the same, add.
  952. //
  953. low64 += tmp64;
  954. high += tmpHigh;
  955. // Propagate carry
  956. //
  957. if (low64 < tmp64)
  958. {
  959. high++;
  960. if (high > tmpHigh)
  961. goto NoCarry;
  962. }
  963. else if (high >= tmpHigh)
  964. goto NoCarry;
  965. uint* number = (uint*)&bufNum;
  966. for (uint cur = 3; ++number[cur++] == 0;)
  967. {
  968. Debug.Assert(cur < bufNum.Length);
  969. if (hiProd < cur)
  970. {
  971. number[cur] = 1;
  972. hiProd = cur;
  973. break;
  974. }
  975. }
  976. }
  977. NoCarry:
  978. bufNum.Low64 = low64;
  979. bufNum.U2 = high;
  980. scale = ScaleResult(&bufNum, hiProd, (byte)(flags >> ScaleShift));
  981. flags = (flags & ~ScaleMask) | ((uint)scale << ScaleShift);
  982. low64 = bufNum.Low64;
  983. high = bufNum.U2;
  984. goto ReturnResult;
  985. }
  986. SignFlip:
  987. {
  988. // Got negative result. Flip its sign.
  989. flags ^= SignMask;
  990. high = ~high;
  991. low64 = (ulong)-(long)low64;
  992. if (low64 == 0)
  993. high++;
  994. goto ReturnResult;
  995. }
  996. AlignedScale:
  997. {
  998. // The addition carried above 96 bits.
  999. // Divide the value by 10, dropping the scale factor.
  1000. //
  1001. if ((flags & ScaleMask) == 0)
  1002. Number.ThrowOverflowException(TypeCode.Decimal);
  1003. flags -= 1 << ScaleShift;
  1004. const uint den = 10;
  1005. ulong num = high + (1UL << 32);
  1006. high = (uint)(num / den);
  1007. num = ((num - high * den) << 32) + (low64 >> 32);
  1008. uint div = (uint)(num / den);
  1009. num = ((num - div * den) << 32) + (uint)low64;
  1010. low64 = div;
  1011. low64 <<= 32;
  1012. div = (uint)(num / den);
  1013. low64 += div;
  1014. div = (uint)num - div * den;
  1015. // See if we need to round up.
  1016. //
  1017. if (div >= 5 && (div > 5 || (low64 & 1) != 0))
  1018. {
  1019. if (++low64 == 0)
  1020. high++;
  1021. }
  1022. goto ReturnResult;
  1023. }
  1024. AlignedAdd:
  1025. {
  1026. ulong d1Low64 = low64;
  1027. uint d1High = high;
  1028. if (sign)
  1029. {
  1030. // Signs differ - subtract
  1031. //
  1032. low64 = d1Low64 - d2.Low64;
  1033. high = d1High - d2.High;
  1034. // Propagate carry
  1035. //
  1036. if (low64 > d1Low64)
  1037. {
  1038. high--;
  1039. if (high >= d1High)
  1040. goto SignFlip;
  1041. }
  1042. else if (high > d1High)
  1043. goto SignFlip;
  1044. }
  1045. else
  1046. {
  1047. // Signs are the same - add
  1048. //
  1049. low64 = d1Low64 + d2.Low64;
  1050. high = d1High + d2.High;
  1051. // Propagate carry
  1052. //
  1053. if (low64 < d1Low64)
  1054. {
  1055. high++;
  1056. if (high <= d1High)
  1057. goto AlignedScale;
  1058. }
  1059. else if (high < d1High)
  1060. goto AlignedScale;
  1061. }
  1062. goto ReturnResult;
  1063. }
  1064. ReturnResult:
  1065. d1.uflags = flags;
  1066. d1.High = high;
  1067. d1.Low64 = low64;
  1068. return;
  1069. }
  1070. #endregion
  1071. /// <summary>
  1072. /// Convert Decimal to Currency (similar to OleAut32 api.)
  1073. /// </summary>
  1074. internal static long VarCyFromDec(ref DecCalc pdecIn)
  1075. {
  1076. long value;
  1077. int scale = pdecIn.Scale - 4;
  1078. // Need to scale to get 4 decimal places. -4 <= scale <= 24.
  1079. //
  1080. if (scale < 0)
  1081. {
  1082. if (pdecIn.High != 0)
  1083. goto ThrowOverflow;
  1084. uint pwr = s_powers10[-scale];
  1085. ulong high = UInt32x32To64(pwr, pdecIn.Mid);
  1086. if (high > uint.MaxValue)
  1087. goto ThrowOverflow;
  1088. ulong low = UInt32x32To64(pwr, pdecIn.Low);
  1089. low += high <<= 32;
  1090. if (low < high)
  1091. goto ThrowOverflow;
  1092. value = (long)low;
  1093. }
  1094. else
  1095. {
  1096. if (scale != 0)
  1097. InternalRound(ref pdecIn, (uint)scale, MidpointRounding.ToEven);
  1098. if (pdecIn.High != 0)
  1099. goto ThrowOverflow;
  1100. value = (long)pdecIn.Low64;
  1101. }
  1102. if (value < 0 && (value != long.MinValue || !pdecIn.IsNegative))
  1103. goto ThrowOverflow;
  1104. if (pdecIn.IsNegative)
  1105. value = -value;
  1106. return value;
  1107. ThrowOverflow:
  1108. throw new OverflowException(SR.Overflow_Currency);
  1109. }
  1110. /// <summary>
  1111. /// Decimal Compare updated to return values similar to ICompareTo
  1112. /// </summary>
  1113. internal static int VarDecCmp(in decimal d1, in decimal d2)
  1114. {
  1115. if ((d2.Low | d2.Mid | d2.High) == 0)
  1116. {
  1117. if ((d1.Low | d1.Mid | d1.High) == 0)
  1118. return 0;
  1119. return (d1.flags >> 31) | 1;
  1120. }
  1121. if ((d1.Low | d1.Mid | d1.High) == 0)
  1122. return -((d2.flags >> 31) | 1);
  1123. int sign = (d1.flags >> 31) - (d2.flags >> 31);
  1124. if (sign != 0)
  1125. return sign;
  1126. return VarDecCmpSub(in d1, in d2);
  1127. }
  1128. private static int VarDecCmpSub(in decimal d1, in decimal d2)
  1129. {
  1130. int flags = d2.flags;
  1131. int sign = (flags >> 31) | 1;
  1132. int scale = flags - d1.flags;
  1133. ulong low64 = d1.Low64;
  1134. uint high = d1.High;
  1135. ulong d2Low64 = d2.Low64;
  1136. uint d2High = d2.High;
  1137. if (scale != 0)
  1138. {
  1139. scale >>= ScaleShift;
  1140. // Scale factors are not equal. Assume that a larger scale factor (more decimal places) is likely to mean that number is smaller.
  1141. // Start by guessing that the right operand has the larger scale factor.
  1142. if (scale < 0)
  1143. {
  1144. // Guessed scale factor wrong. Swap operands.
  1145. scale = -scale;
  1146. sign = -sign;
  1147. ulong tmp64 = low64;
  1148. low64 = d2Low64;
  1149. d2Low64 = tmp64;
  1150. uint tmp = high;
  1151. high = d2High;
  1152. d2High = tmp;
  1153. }
  1154. // d1 will need to be multiplied by 10^scale so it will have the same scale as d2.
  1155. // Scaling loop, up to 10^9 at a time.
  1156. do
  1157. {
  1158. uint power = scale >= MaxInt32Scale ? TenToPowerNine : s_powers10[scale];
  1159. ulong tmpLow = UInt32x32To64((uint)low64, power);
  1160. ulong tmp = UInt32x32To64((uint)(low64 >> 32), power) + (tmpLow >> 32);
  1161. low64 = (uint)tmpLow + (tmp << 32);
  1162. tmp >>= 32;
  1163. tmp += UInt32x32To64(high, power);
  1164. // If the scaled value has more than 96 significant bits then it's greater than d2
  1165. if (tmp > uint.MaxValue)
  1166. return sign;
  1167. high = (uint)tmp;
  1168. } while ((scale -= MaxInt32Scale) > 0);
  1169. }
  1170. uint cmpHigh = high - d2High;
  1171. if (cmpHigh != 0)
  1172. {
  1173. // check for overflow
  1174. if (cmpHigh > high)
  1175. sign = -sign;
  1176. return sign;
  1177. }
  1178. ulong cmpLow64 = low64 - d2Low64;
  1179. if (cmpLow64 == 0)
  1180. sign = 0;
  1181. // check for overflow
  1182. else if (cmpLow64 > low64)
  1183. sign = -sign;
  1184. return sign;
  1185. }
  1186. /// <summary>
  1187. /// Decimal Multiply
  1188. /// </summary>
  1189. internal static unsafe void VarDecMul(ref DecCalc d1, ref DecCalc d2)
  1190. {
  1191. int scale = (byte)(d1.uflags + d2.uflags >> ScaleShift);
  1192. ulong tmp;
  1193. uint hiProd;
  1194. Unsafe.SkipInit(out Buf24 bufProd);
  1195. DebugPoison(ref bufProd);
  1196. if ((d1.High | d1.Mid) == 0)
  1197. {
  1198. if ((d2.High | d2.Mid) == 0)
  1199. {
  1200. // Upper 64 bits are zero.
  1201. //
  1202. ulong low64 = UInt32x32To64(d1.Low, d2.Low);
  1203. if (scale > DEC_SCALE_MAX)
  1204. {
  1205. // Result scale is too big. Divide result by power of 10 to reduce it.
  1206. // If the amount to divide by is > 19 the result is guaranteed
  1207. // less than 1/2. [max value in 64 bits = 1.84E19]
  1208. //
  1209. if (scale > DEC_SCALE_MAX + MaxInt64Scale)
  1210. goto ReturnZero;
  1211. scale -= DEC_SCALE_MAX + 1;
  1212. ulong power = s_ulongPowers10[scale];
  1213. // TODO: https://github.com/dotnet/coreclr/issues/3439
  1214. tmp = low64 / power;
  1215. ulong remainder = low64 - tmp * power;
  1216. low64 = tmp;
  1217. // Round result. See if remainder >= 1/2 of divisor.
  1218. // Divisor is a power of 10, so it is always even.
  1219. //
  1220. power >>= 1;
  1221. if (remainder >= power && (remainder > power || ((uint)low64 & 1) > 0))
  1222. low64++;
  1223. scale = DEC_SCALE_MAX;
  1224. }
  1225. d1.Low64 = low64;
  1226. d1.uflags = ((d2.uflags ^ d1.uflags) & SignMask) | ((uint)scale << ScaleShift);
  1227. return;
  1228. }
  1229. else
  1230. {
  1231. // Left value is 32-bit, result fits in 4 uints
  1232. tmp = UInt32x32To64(d1.Low, d2.Low);
  1233. bufProd.U0 = (uint)tmp;
  1234. tmp = UInt32x32To64(d1.Low, d2.Mid) + (tmp >> 32);
  1235. bufProd.U1 = (uint)tmp;
  1236. tmp >>= 32;
  1237. if (d2.High != 0)
  1238. {
  1239. tmp += UInt32x32To64(d1.Low, d2.High);
  1240. if (tmp > uint.MaxValue)
  1241. {
  1242. bufProd.Mid64 = tmp;
  1243. hiProd = 3;
  1244. goto SkipScan;
  1245. }
  1246. }
  1247. bufProd.U2 = (uint)tmp;
  1248. hiProd = 2;
  1249. }
  1250. }
  1251. else if ((d2.High | d2.Mid) == 0)
  1252. {
  1253. // Right value is 32-bit, result fits in 4 uints
  1254. tmp = UInt32x32To64(d2.Low, d1.Low);
  1255. bufProd.U0 = (uint)tmp;
  1256. tmp = UInt32x32To64(d2.Low, d1.Mid) + (tmp >> 32);
  1257. bufProd.U1 = (uint)tmp;
  1258. tmp >>= 32;
  1259. if (d1.High != 0)
  1260. {
  1261. tmp += UInt32x32To64(d2.Low, d1.High);
  1262. if (tmp > uint.MaxValue)
  1263. {
  1264. bufProd.Mid64 = tmp;
  1265. hiProd = 3;
  1266. goto SkipScan;
  1267. }
  1268. }
  1269. bufProd.U2 = (uint)tmp;
  1270. hiProd = 2;
  1271. }
  1272. else
  1273. {
  1274. // Both operands have bits set in the upper 64 bits.
  1275. //
  1276. // Compute and accumulate the 9 partial products into a
  1277. // 192-bit (24-byte) result.
  1278. //
  1279. // [l-h][l-m][l-l] left high, middle, low
  1280. // x [r-h][r-m][r-l] right high, middle, low
  1281. // ------------------------------
  1282. //
  1283. // [0-h][0-l] l-l * r-l
  1284. // [1ah][1al] l-l * r-m
  1285. // [1bh][1bl] l-m * r-l
  1286. // [2ah][2al] l-m * r-m
  1287. // [2bh][2bl] l-l * r-h
  1288. // [2ch][2cl] l-h * r-l
  1289. // [3ah][3al] l-m * r-h
  1290. // [3bh][3bl] l-h * r-m
  1291. // [4-h][4-l] l-h * r-h
  1292. // ------------------------------
  1293. // [p-5][p-4][p-3][p-2][p-1][p-0] prod[] array
  1294. //
  1295. tmp = UInt32x32To64(d1.Low, d2.Low);
  1296. bufProd.U0 = (uint)tmp;
  1297. ulong tmp2 = UInt32x32To64(d1.Low, d2.Mid) + (tmp >> 32);
  1298. tmp = UInt32x32To64(d1.Mid, d2.Low);
  1299. tmp += tmp2; // this could generate carry
  1300. bufProd.U1 = (uint)tmp;
  1301. if (tmp < tmp2) // detect carry
  1302. tmp2 = (tmp >> 32) | (1UL << 32);
  1303. else
  1304. tmp2 = tmp >> 32;
  1305. tmp = UInt32x32To64(d1.Mid, d2.Mid) + tmp2;
  1306. if ((d1.High | d2.High) > 0)
  1307. {
  1308. // Highest 32 bits is non-zero. Calculate 5 more partial products.
  1309. //
  1310. tmp2 = UInt32x32To64(d1.Low, d2.High);
  1311. tmp += tmp2; // this could generate carry
  1312. uint tmp3 = 0;
  1313. if (tmp < tmp2) // detect carry
  1314. tmp3 = 1;
  1315. tmp2 = UInt32x32To64(d1.High, d2.Low);
  1316. tmp += tmp2; // this could generate carry
  1317. bufProd.U2 = (uint)tmp;
  1318. if (tmp < tmp2) // detect carry
  1319. tmp3++;
  1320. tmp2 = ((ulong)tmp3 << 32) | (tmp >> 32);
  1321. tmp = UInt32x32To64(d1.Mid, d2.High);
  1322. tmp += tmp2; // this could generate carry
  1323. tmp3 = 0;
  1324. if (tmp < tmp2) // detect carry
  1325. tmp3 = 1;
  1326. tmp2 = UInt32x32To64(d1.High, d2.Mid);
  1327. tmp += tmp2; // this could generate carry
  1328. bufProd.U3 = (uint)tmp;
  1329. if (tmp < tmp2) // detect carry
  1330. tmp3++;
  1331. tmp = ((ulong)tmp3 << 32) | (tmp >> 32);
  1332. bufProd.High64 = UInt32x32To64(d1.High, d2.High) + tmp;
  1333. hiProd = 5;
  1334. }
  1335. else
  1336. {
  1337. bufProd.Mid64 = tmp;
  1338. hiProd = 3;
  1339. }
  1340. }
  1341. // Check for leading zero uints on the product
  1342. //
  1343. uint* product = (uint*)&bufProd;
  1344. while (product[(int)hiProd] == 0)
  1345. {
  1346. if (hiProd == 0)
  1347. goto ReturnZero;
  1348. hiProd--;
  1349. }
  1350. SkipScan:
  1351. if (hiProd > 2 || scale > DEC_SCALE_MAX)
  1352. {
  1353. scale = ScaleResult(&bufProd, hiProd, scale);
  1354. }
  1355. d1.Low64 = bufProd.Low64;
  1356. d1.High = bufProd.U2;
  1357. d1.uflags = ((d2.uflags ^ d1.uflags) & SignMask) | ((uint)scale << ScaleShift);
  1358. return;
  1359. ReturnZero:
  1360. d1 = default;
  1361. }
  1362. /// <summary>
  1363. /// Convert float to Decimal
  1364. /// </summary>
  1365. internal static void VarDecFromR4(float input, out DecCalc result)
  1366. {
  1367. result = default;
  1368. // The most we can scale by is 10^28, which is just slightly more
  1369. // than 2^93. So a float with an exponent of -94 could just
  1370. // barely reach 0.5, but smaller exponents will always round to zero.
  1371. //
  1372. const uint SNGBIAS = 126;
  1373. int exp = (int)(GetExponent(input) - SNGBIAS);
  1374. if (exp < -94)
  1375. return; // result should be zeroed out
  1376. if (exp > 96)
  1377. Number.ThrowOverflowException(TypeCode.Decimal);
  1378. uint flags = 0;
  1379. if (input < 0)
  1380. {
  1381. input = -input;
  1382. flags = SignMask;
  1383. }
  1384. // Round the input to a 7-digit integer. The R4 format has
  1385. // only 7 digits of precision, and we want to keep garbage digits
  1386. // out of the Decimal were making.
  1387. //
  1388. // Calculate max power of 10 input value could have by multiplying
  1389. // the exponent by log10(2). Using scaled integer multiplcation,
  1390. // log10(2) * 2 ^ 16 = .30103 * 65536 = 19728.3.
  1391. //
  1392. double dbl = input;
  1393. int power = 6 - ((exp * 19728) >> 16);
  1394. // power is between -22 and 35
  1395. if (power >= 0)
  1396. {
  1397. // We have less than 7 digits, scale input up.
  1398. //
  1399. if (power > DEC_SCALE_MAX)
  1400. power = DEC_SCALE_MAX;
  1401. dbl *= s_doublePowers10[power];
  1402. }
  1403. else
  1404. {
  1405. if (power != -1 || dbl >= 1E7)
  1406. dbl /= s_doublePowers10[-power];
  1407. else
  1408. power = 0; // didn't scale it
  1409. }
  1410. Debug.Assert(dbl < 1E7);
  1411. if (dbl < 1E6 && power < DEC_SCALE_MAX)
  1412. {
  1413. dbl *= 10;
  1414. power++;
  1415. Debug.Assert(dbl >= 1E6);
  1416. }
  1417. // Round to integer
  1418. //
  1419. uint mant;
  1420. // with SSE4.1 support ROUNDSD can be used
  1421. if (X86.Sse41.IsSupported)
  1422. mant = (uint)(int)Math.Round(dbl);
  1423. else
  1424. {
  1425. mant = (uint)(int)dbl;
  1426. dbl -= (int)mant; // difference between input & integer
  1427. if (dbl > 0.5 || dbl == 0.5 && (mant & 1) != 0)
  1428. mant++;
  1429. }
  1430. if (mant == 0)
  1431. return; // result should be zeroed out
  1432. if (power < 0)
  1433. {
  1434. // Add -power factors of 10, -power <= (29 - 7) = 22.
  1435. //
  1436. power = -power;
  1437. if (power < 10)
  1438. {
  1439. result.Low64 = UInt32x32To64(mant, s_powers10[power]);
  1440. }
  1441. else
  1442. {
  1443. // Have a big power of 10.
  1444. //
  1445. if (power > 18)
  1446. {
  1447. ulong low64 = UInt32x32To64(mant, s_powers10[power - 18]);
  1448. UInt64x64To128(low64, TenToPowerEighteen, ref result);
  1449. }
  1450. else
  1451. {
  1452. ulong low64 = UInt32x32To64(mant, s_powers10[power - 9]);
  1453. ulong hi64 = UInt32x32To64(TenToPowerNine, (uint)(low64 >> 32));
  1454. low64 = UInt32x32To64(TenToPowerNine, (uint)low64);
  1455. result.Low = (uint)low64;
  1456. hi64 += low64 >> 32;
  1457. result.Mid = (uint)hi64;
  1458. hi64 >>= 32;
  1459. result.High = (uint)hi64;
  1460. }
  1461. }
  1462. }
  1463. else
  1464. {
  1465. // Factor out powers of 10 to reduce the scale, if possible.
  1466. // The maximum number we could factor out would be 6. This
  1467. // comes from the fact we have a 7-digit number, and the
  1468. // MSD must be non-zero -- but the lower 6 digits could be
  1469. // zero. Note also the scale factor is never negative, so
  1470. // we can't scale by any more than the power we used to
  1471. // get the integer.
  1472. //
  1473. int lmax = power;
  1474. if (lmax > 6)
  1475. lmax = 6;
  1476. if ((mant & 0xF) == 0 && lmax >= 4)
  1477. {
  1478. const uint den = 10000;
  1479. uint div = mant / den;
  1480. if (mant == div * den)
  1481. {
  1482. mant = div;
  1483. power -= 4;
  1484. lmax -= 4;
  1485. }
  1486. }
  1487. if ((mant & 3) == 0 && lmax >= 2)
  1488. {
  1489. const uint den = 100;
  1490. uint div = mant / den;
  1491. if (mant == div * den)
  1492. {
  1493. mant = div;
  1494. power -= 2;
  1495. lmax -= 2;
  1496. }
  1497. }
  1498. if ((mant & 1) == 0 && lmax >= 1)
  1499. {
  1500. const uint den = 10;
  1501. uint div = mant / den;
  1502. if (mant == div * den)
  1503. {
  1504. mant = div;
  1505. power--;
  1506. }
  1507. }
  1508. flags |= (uint)power << ScaleShift;
  1509. result.Low = mant;
  1510. }
  1511. result.uflags = flags;
  1512. }
  1513. /// <summary>
  1514. /// Convert double to Decimal
  1515. /// </summary>
  1516. internal static void VarDecFromR8(double input, out DecCalc result)
  1517. {
  1518. result = default;
  1519. // The most we can scale by is 10^28, which is just slightly more
  1520. // than 2^93. So a float with an exponent of -94 could just
  1521. // barely reach 0.5, but smaller exponents will always round to zero.
  1522. //
  1523. const uint DBLBIAS = 1022;
  1524. int exp = (int)(GetExponent(input) - DBLBIAS);
  1525. if (exp < -94)
  1526. return; // result should be zeroed out
  1527. if (exp > 96)
  1528. Number.ThrowOverflowException(TypeCode.Decimal);
  1529. uint flags = 0;
  1530. if (input < 0)
  1531. {
  1532. input = -input;
  1533. flags = SignMask;
  1534. }
  1535. // Round the input to a 15-digit integer. The R8 format has
  1536. // only 15 digits of precision, and we want to keep garbage digits
  1537. // out of the Decimal were making.
  1538. //
  1539. // Calculate max power of 10 input value could have by multiplying
  1540. // the exponent by log10(2). Using scaled integer multiplcation,
  1541. // log10(2) * 2 ^ 16 = .30103 * 65536 = 19728.3.
  1542. //
  1543. double dbl = input;
  1544. int power = 14 - ((exp * 19728) >> 16);
  1545. // power is between -14 and 43
  1546. if (power >= 0)
  1547. {
  1548. // We have less than 15 digits, scale input up.
  1549. //
  1550. if (power > DEC_SCALE_MAX)
  1551. power = DEC_SCALE_MAX;
  1552. dbl *= s_doublePowers10[power];
  1553. }
  1554. else
  1555. {
  1556. if (power != -1 || dbl >= 1E15)
  1557. dbl /= s_doublePowers10[-power];
  1558. else
  1559. power = 0; // didn't scale it
  1560. }
  1561. Debug.Assert(dbl < 1E15);
  1562. if (dbl < 1E14 && power < DEC_SCALE_MAX)
  1563. {
  1564. dbl *= 10;
  1565. power++;
  1566. Debug.Assert(dbl >= 1E14);
  1567. }
  1568. // Round to int64
  1569. //
  1570. ulong mant;
  1571. // with SSE4.1 support ROUNDSD can be used
  1572. if (X86.Sse41.IsSupported)
  1573. mant = (ulong)(long)Math.Round(dbl);
  1574. else
  1575. {
  1576. mant = (ulong)(long)dbl;
  1577. dbl -= (long)mant; // difference between input & integer
  1578. if (dbl > 0.5 || dbl == 0.5 && (mant & 1) != 0)
  1579. mant++;
  1580. }
  1581. if (mant == 0)
  1582. return; // result should be zeroed out
  1583. if (power < 0)
  1584. {
  1585. // Add -power factors of 10, -power <= (29 - 15) = 14.
  1586. //
  1587. power = -power;
  1588. if (power < 10)
  1589. {
  1590. uint pow10 = s_powers10[power];
  1591. ulong low64 = UInt32x32To64((uint)mant, pow10);
  1592. ulong hi64 = UInt32x32To64((uint)(mant >> 32), pow10);
  1593. result.Low = (uint)low64;
  1594. hi64 += low64 >> 32;
  1595. result.Mid = (uint)hi64;
  1596. hi64 >>= 32;
  1597. result.High = (uint)hi64;
  1598. }
  1599. else
  1600. {
  1601. // Have a big power of 10.
  1602. //
  1603. Debug.Assert(power <= 14);
  1604. UInt64x64To128(mant, s_ulongPowers10[power - 1], ref result);
  1605. }
  1606. }
  1607. else
  1608. {
  1609. // Factor out powers of 10 to reduce the scale, if possible.
  1610. // The maximum number we could factor out would be 14. This
  1611. // comes from the fact we have a 15-digit number, and the
  1612. // MSD must be non-zero -- but the lower 14 digits could be
  1613. // zero. Note also the scale factor is never negative, so
  1614. // we can't scale by any more than the power we used to
  1615. // get the integer.
  1616. //
  1617. int lmax = power;
  1618. if (lmax > 14)
  1619. lmax = 14;
  1620. if ((byte)mant == 0 && lmax >= 8)
  1621. {
  1622. const uint den = 100000000;
  1623. ulong div = mant / den;
  1624. if ((uint)mant == (uint)(div * den))
  1625. {
  1626. mant = div;
  1627. power -= 8;
  1628. lmax -= 8;
  1629. }
  1630. }
  1631. if (((uint)mant & 0xF) == 0 && lmax >= 4)
  1632. {
  1633. const uint den = 10000;
  1634. ulong div = mant / den;
  1635. if ((uint)mant == (uint)(div * den))
  1636. {
  1637. mant = div;
  1638. power -= 4;
  1639. lmax -= 4;
  1640. }
  1641. }
  1642. if (((uint)mant & 3) == 0 && lmax >= 2)
  1643. {
  1644. const uint den = 100;
  1645. ulong div = mant / den;
  1646. if ((uint)mant == (uint)(div * den))
  1647. {
  1648. mant = div;
  1649. power -= 2;
  1650. lmax -= 2;
  1651. }
  1652. }
  1653. if (((uint)mant & 1) == 0 && lmax >= 1)
  1654. {
  1655. const uint den = 10;
  1656. ulong div = mant / den;
  1657. if ((uint)mant == (uint)(div * den))
  1658. {
  1659. mant = div;
  1660. power--;
  1661. }
  1662. }
  1663. flags |= (uint)power << ScaleShift;
  1664. result.Low64 = mant;
  1665. }
  1666. result.uflags = flags;
  1667. }
  1668. /// <summary>
  1669. /// Convert Decimal to float
  1670. /// </summary>
  1671. internal static float VarR4FromDec(in decimal value)
  1672. {
  1673. return (float)VarR8FromDec(in value);
  1674. }
  1675. /// <summary>
  1676. /// Convert Decimal to double
  1677. /// </summary>
  1678. internal static double VarR8FromDec(in decimal value)
  1679. {
  1680. // Value taken via reverse engineering the double that corresponds to 2^64. (oleaut32 has ds2to64 = DEFDS(0, 0, DBLBIAS + 65, 0))
  1681. const double ds2to64 = 1.8446744073709552e+019;
  1682. double dbl = ((double)value.Low64 +
  1683. (double)value.High * ds2to64) / s_doublePowers10[value.Scale];
  1684. if (value.IsNegative)
  1685. dbl = -dbl;
  1686. return dbl;
  1687. }
  1688. internal static int GetHashCode(in decimal d)
  1689. {
  1690. if ((d.Low | d.Mid | d.High) == 0)
  1691. return 0;
  1692. uint flags = (uint)d.flags;
  1693. if ((flags & ScaleMask) == 0 || (d.Low & 1) != 0)
  1694. return (int)(flags ^ d.High ^ d.Mid ^ d.Low);
  1695. int scale = (byte)(flags >> ScaleShift);
  1696. uint low = d.Low;
  1697. ulong high64 = ((ulong)d.High << 32) | d.Mid;
  1698. Unscale(ref low, ref high64, ref scale);
  1699. flags = (flags & ~ScaleMask) | (uint)scale << ScaleShift;
  1700. return (int)(flags ^ (uint)(high64 >> 32) ^ (uint)high64 ^ low);
  1701. }
  1702. /// <summary>
  1703. /// Divides two decimal values.
  1704. /// On return, d1 contains the result of the operation.
  1705. /// </summary>
  1706. internal static unsafe void VarDecDiv(ref DecCalc d1, ref DecCalc d2)
  1707. {
  1708. Unsafe.SkipInit(out Buf12 bufQuo);
  1709. DebugPoison(ref bufQuo);
  1710. uint power;
  1711. int curScale;
  1712. int scale = (sbyte)(d1.uflags - d2.uflags >> ScaleShift);
  1713. bool unscale = false;
  1714. uint tmp;
  1715. if ((d2.High | d2.Mid) == 0)
  1716. {
  1717. // Divisor is only 32 bits. Easy divide.
  1718. //
  1719. uint den = d2.Low;
  1720. if (den == 0)
  1721. throw new DivideByZeroException();
  1722. bufQuo.Low64 = d1.Low64;
  1723. bufQuo.U2 = d1.High;
  1724. uint remainder = Div96By32(ref bufQuo, den);
  1725. while (true)
  1726. {
  1727. if (remainder == 0)
  1728. {
  1729. if (scale < 0)
  1730. {
  1731. curScale = Math.Min(9, -scale);
  1732. goto HaveScale;
  1733. }
  1734. break;
  1735. }
  1736. // We need to unscale if and only if we have a non-zero remainder
  1737. unscale = true;
  1738. // We have computed a quotient based on the natural scale
  1739. // ( <dividend scale> - <divisor scale> ). We have a non-zero
  1740. // remainder, so now we should increase the scale if possible to
  1741. // include more quotient bits.
  1742. //
  1743. // If it doesn't cause overflow, we'll loop scaling by 10^9 and
  1744. // computing more quotient bits as long as the remainder stays
  1745. // non-zero. If scaling by that much would cause overflow, we'll
  1746. // drop out of the loop and scale by as much as we can.
  1747. //
  1748. // Scaling by 10^9 will overflow if bufQuo[2].bufQuo[1] >= 2^32 / 10^9
  1749. // = 4.294 967 296. So the upper limit is bufQuo[2] == 4 and
  1750. // bufQuo[1] == 0.294 967 296 * 2^32 = 1,266,874,889.7+. Since
  1751. // quotient bits in bufQuo[0] could be all 1's, then 1,266,874,888
  1752. // is the largest value in bufQuo[1] (when bufQuo[2] == 4) that is
  1753. // assured not to overflow.
  1754. //
  1755. if (scale == DEC_SCALE_MAX || (curScale = SearchScale(ref bufQuo, scale)) == 0)
  1756. {
  1757. // No more scaling to be done, but remainder is non-zero.
  1758. // Round quotient.
  1759. //
  1760. tmp = remainder << 1;
  1761. if (tmp < remainder || tmp >= den && (tmp > den || (bufQuo.U0 & 1) != 0))
  1762. goto RoundUp;
  1763. break;
  1764. }
  1765. HaveScale:
  1766. power = s_powers10[curScale];
  1767. scale += curScale;
  1768. if (IncreaseScale(ref bufQuo, power) != 0)
  1769. goto ThrowOverflow;
  1770. ulong num = UInt32x32To64(remainder, power);
  1771. // TODO: https://github.com/dotnet/coreclr/issues/3439
  1772. uint div = (uint)(num / den);
  1773. remainder = (uint)num - div * den;
  1774. if (!Add32To96(ref bufQuo, div))
  1775. {
  1776. scale = OverflowUnscale(ref bufQuo, scale, remainder != 0);
  1777. break;
  1778. }
  1779. } // while (true)
  1780. }
  1781. else
  1782. {
  1783. // Divisor has bits set in the upper 64 bits.
  1784. //
  1785. // Divisor must be fully normalized (shifted so bit 31 of the most
  1786. // significant uint is 1). Locate the MSB so we know how much to
  1787. // normalize by. The dividend will be shifted by the same amount so
  1788. // the quotient is not changed.
  1789. //
  1790. tmp = d2.High;
  1791. if (tmp == 0)
  1792. tmp = d2.Mid;
  1793. curScale = BitOperations.LeadingZeroCount(tmp);
  1794. // Shift both dividend and divisor left by curScale.
  1795. //
  1796. Unsafe.SkipInit(out Buf16 bufRem);
  1797. DebugPoison(ref bufRem);
  1798. bufRem.Low64 = d1.Low64 << curScale;
  1799. bufRem.High64 = (d1.Mid + ((ulong)d1.High << 32)) >> (32 - curScale);
  1800. ulong divisor = d2.Low64 << curScale;
  1801. if (d2.High == 0)
  1802. {
  1803. // Have a 64-bit divisor in sdlDivisor. The remainder
  1804. // (currently 96 bits spread over 4 uints) will be < divisor.
  1805. //
  1806. bufQuo.U2 = 0;
  1807. bufQuo.U1 = Div96By64(ref *(Buf12*)&bufRem.U1, divisor);
  1808. bufQuo.U0 = Div96By64(ref *(Buf12*)&bufRem, divisor);
  1809. while (true)
  1810. {
  1811. if (bufRem.Low64 == 0)
  1812. {
  1813. if (scale < 0)
  1814. {
  1815. curScale = Math.Min(9, -scale);
  1816. goto HaveScale64;
  1817. }
  1818. break;
  1819. }
  1820. // We need to unscale if and only if we have a non-zero remainder
  1821. unscale = true;
  1822. // Remainder is non-zero. Scale up quotient and remainder by
  1823. // powers of 10 so we can compute more significant bits.
  1824. //
  1825. if (scale == DEC_SCALE_MAX || (curScale = SearchScale(ref bufQuo, scale)) == 0)
  1826. {
  1827. // No more scaling to be done, but remainder is non-zero.
  1828. // Round quotient.
  1829. //
  1830. ulong tmp64 = bufRem.Low64;
  1831. if ((long)tmp64 < 0 || (tmp64 <<= 1) > divisor ||
  1832. (tmp64 == divisor && (bufQuo.U0 & 1) != 0))
  1833. goto RoundUp;
  1834. break;
  1835. }
  1836. HaveScale64:
  1837. power = s_powers10[curScale];
  1838. scale += curScale;
  1839. if (IncreaseScale(ref bufQuo, power) != 0)
  1840. goto ThrowOverflow;
  1841. IncreaseScale64(ref *(Buf12*)&bufRem, power);
  1842. tmp = Div96By64(ref *(Buf12*)&bufRem, divisor);
  1843. if (!Add32To96(ref bufQuo, tmp))
  1844. {
  1845. scale = OverflowUnscale(ref bufQuo, scale, bufRem.Low64 != 0);
  1846. break;
  1847. }
  1848. } // while (true)
  1849. }
  1850. else
  1851. {
  1852. // Have a 96-bit divisor in bufDivisor.
  1853. //
  1854. // Start by finishing the shift left by curScale.
  1855. //
  1856. Unsafe.SkipInit(out Buf12 bufDivisor);
  1857. DebugPoison(ref bufDivisor);
  1858. bufDivisor.Low64 = divisor;
  1859. bufDivisor.U2 = (uint)((d2.Mid + ((ulong)d2.High << 32)) >> (32 - curScale));
  1860. // The remainder (currently 96 bits spread over 4 uints) will be < divisor.
  1861. //
  1862. bufQuo.Low64 = Div128By96(ref bufRem, ref bufDivisor);
  1863. bufQuo.U2 = 0;
  1864. while (true)
  1865. {
  1866. if ((bufRem.Low64 | bufRem.U2) == 0)
  1867. {
  1868. if (scale < 0)
  1869. {
  1870. curScale = Math.Min(9, -scale);
  1871. goto HaveScale96;
  1872. }
  1873. break;
  1874. }
  1875. // We need to unscale if and only if we have a non-zero remainder
  1876. unscale = true;
  1877. // Remainder is non-zero. Scale up quotient and remainder by
  1878. // powers of 10 so we can compute more significant bits.
  1879. //
  1880. if (scale == DEC_SCALE_MAX || (curScale = SearchScale(ref bufQuo, scale)) == 0)
  1881. {
  1882. // No more scaling to be done, but remainder is non-zero.
  1883. // Round quotient.
  1884. //
  1885. if ((int)bufRem.U2 < 0)
  1886. {
  1887. goto RoundUp;
  1888. }
  1889. tmp = bufRem.U1 >> 31;
  1890. bufRem.Low64 <<= 1;
  1891. bufRem.U2 = (bufRem.U2 << 1) + tmp;
  1892. if (bufRem.U2 > bufDivisor.U2 || bufRem.U2 == bufDivisor.U2 &&
  1893. (bufRem.Low64 > bufDivisor.Low64 || bufRem.Low64 == bufDivisor.Low64 &&
  1894. (bufQuo.U0 & 1) != 0))
  1895. goto RoundUp;
  1896. break;
  1897. }
  1898. HaveScale96:
  1899. power = s_powers10[curScale];
  1900. scale += curScale;
  1901. if (IncreaseScale(ref bufQuo, power) != 0)
  1902. goto ThrowOverflow;
  1903. bufRem.U3 = IncreaseScale(ref *(Buf12*)&bufRem, power);
  1904. tmp = Div128By96(ref bufRem, ref bufDivisor);
  1905. if (!Add32To96(ref bufQuo, tmp))
  1906. {
  1907. scale = OverflowUnscale(ref bufQuo, scale, (bufRem.Low64 | bufRem.High64) != 0);
  1908. break;
  1909. }
  1910. } // while (true)
  1911. }
  1912. }
  1913. Unscale:
  1914. if (unscale)
  1915. {
  1916. uint low = bufQuo.U0;
  1917. ulong high64 = bufQuo.High64;
  1918. Unscale(ref low, ref high64, ref scale);
  1919. d1.Low = low;
  1920. d1.Mid = (uint)high64;
  1921. d1.High = (uint)(high64 >> 32);
  1922. }
  1923. else
  1924. {
  1925. d1.Low64 = bufQuo.Low64;
  1926. d1.High = bufQuo.U2;
  1927. }
  1928. d1.uflags = ((d1.uflags ^ d2.uflags) & SignMask) | ((uint)scale << ScaleShift);
  1929. return;
  1930. RoundUp:
  1931. {
  1932. if (++bufQuo.Low64 == 0 && ++bufQuo.U2 == 0)
  1933. {
  1934. scale = OverflowUnscale(ref bufQuo, scale, true);
  1935. }
  1936. goto Unscale;
  1937. }
  1938. ThrowOverflow:
  1939. Number.ThrowOverflowException(TypeCode.Decimal);
  1940. }
  1941. /// <summary>
  1942. /// Computes the remainder between two decimals.
  1943. /// On return, d1 contains the result of the operation and d2 is trashed.
  1944. /// </summary>
  1945. internal static void VarDecMod(ref DecCalc d1, ref DecCalc d2)
  1946. {
  1947. if ((d2.ulo | d2.umid | d2.uhi) == 0)
  1948. throw new DivideByZeroException();
  1949. if ((d1.ulo | d1.umid | d1.uhi) == 0)
  1950. return;
  1951. // In the operation x % y the sign of y does not matter. Result will have the sign of x.
  1952. d2.uflags = (d2.uflags & ~SignMask) | (d1.uflags & SignMask);
  1953. int cmp = VarDecCmpSub(in Unsafe.As<DecCalc, decimal>(ref d1), in Unsafe.As<DecCalc, decimal>(ref d2));
  1954. if (cmp == 0)
  1955. {
  1956. d1.ulo = 0;
  1957. d1.umid = 0;
  1958. d1.uhi = 0;
  1959. if (d2.uflags > d1.uflags)
  1960. d1.uflags = d2.uflags;
  1961. return;
  1962. }
  1963. if ((cmp ^ (int)(d1.uflags & SignMask)) < 0)
  1964. return;
  1965. // The divisor is smaller than the dividend and both are non-zero. Calculate the integer remainder using the larger scaling factor.
  1966. int scale = (sbyte)(d1.uflags - d2.uflags >> ScaleShift);
  1967. if (scale > 0)
  1968. {
  1969. // Divisor scale can always be increased to dividend scale for remainder calculation.
  1970. do
  1971. {
  1972. uint power = scale >= MaxInt32Scale ? TenToPowerNine : s_powers10[scale];
  1973. ulong tmp = UInt32x32To64(d2.Low, power);
  1974. d2.Low = (uint)tmp;
  1975. tmp >>= 32;
  1976. tmp += (d2.Mid + ((ulong)d2.High << 32)) * power;
  1977. d2.Mid = (uint)tmp;
  1978. d2.High = (uint)(tmp >> 32);
  1979. } while ((scale -= MaxInt32Scale) > 0);
  1980. scale = 0;
  1981. }
  1982. do
  1983. {
  1984. if (scale < 0)
  1985. {
  1986. d1.uflags = d2.uflags;
  1987. // Try to scale up dividend to match divisor.
  1988. Unsafe.SkipInit(out Buf12 bufQuo);
  1989. DebugPoison(ref bufQuo);
  1990. bufQuo.Low64 = d1.Low64;
  1991. bufQuo.U2 = d1.High;
  1992. do
  1993. {
  1994. int iCurScale = SearchScale(ref bufQuo, DEC_SCALE_MAX + scale);
  1995. if (iCurScale == 0)
  1996. break;
  1997. uint power = iCurScale >= MaxInt32Scale ? TenToPowerNine : s_powers10[iCurScale];
  1998. scale += iCurScale;
  1999. ulong tmp = UInt32x32To64(bufQuo.U0, power);
  2000. bufQuo.U0 = (uint)tmp;
  2001. tmp >>= 32;
  2002. bufQuo.High64 = tmp + bufQuo.High64 * power;
  2003. if (power != TenToPowerNine)
  2004. break;
  2005. }
  2006. while (scale < 0);
  2007. d1.Low64 = bufQuo.Low64;
  2008. d1.High = bufQuo.U2;
  2009. }
  2010. if (d1.High == 0)
  2011. {
  2012. Debug.Assert(d2.High == 0);
  2013. Debug.Assert(scale == 0);
  2014. d1.Low64 %= d2.Low64;
  2015. return;
  2016. }
  2017. else if ((d2.High | d2.Mid) == 0)
  2018. {
  2019. uint den = d2.Low;
  2020. ulong tmp = ((ulong)d1.High << 32) | d1.Mid;
  2021. tmp = ((tmp % den) << 32) | d1.Low;
  2022. d1.Low64 = tmp % den;
  2023. d1.High = 0;
  2024. }
  2025. else
  2026. {
  2027. VarDecModFull(ref d1, ref d2, scale);
  2028. return;
  2029. }
  2030. } while (scale < 0);
  2031. }
  2032. private static unsafe void VarDecModFull(ref DecCalc d1, ref DecCalc d2, int scale)
  2033. {
  2034. // Divisor has bits set in the upper 64 bits.
  2035. //
  2036. // Divisor must be fully normalized (shifted so bit 31 of the most significant uint is 1).
  2037. // Locate the MSB so we know how much to normalize by.
  2038. // The dividend will be shifted by the same amount so the quotient is not changed.
  2039. //
  2040. uint tmp = d2.High;
  2041. if (tmp == 0)
  2042. tmp = d2.Mid;
  2043. int shift = BitOperations.LeadingZeroCount(tmp);
  2044. Unsafe.SkipInit(out Buf28 b);
  2045. DebugPoison(ref b);
  2046. b.Buf24.Low64 = d1.Low64 << shift;
  2047. b.Buf24.Mid64 = (d1.Mid + ((ulong)d1.High << 32)) >> (32 - shift);
  2048. // The dividend might need to be scaled up to 221 significant bits.
  2049. // Maximum scaling is required when the divisor is 2^64 with scale 28 and is left shifted 31 bits
  2050. // and the dividend is decimal.MaxValue: (2^96 - 1) * 10^28 << 31 = 221 bits.
  2051. uint high = 3;
  2052. while (scale < 0)
  2053. {
  2054. uint power = scale <= -MaxInt32Scale ? TenToPowerNine : s_powers10[-scale];
  2055. uint* buf = (uint*)&b;
  2056. ulong tmp64 = UInt32x32To64(b.Buf24.U0, power);
  2057. b.Buf24.U0 = (uint)tmp64;
  2058. for (int i = 1; i <= high; i++)
  2059. {
  2060. tmp64 >>= 32;
  2061. tmp64 += UInt32x32To64(buf[i], power);
  2062. buf[i] = (uint)tmp64;
  2063. }
  2064. // The high bit of the dividend must not be set.
  2065. if (tmp64 > int.MaxValue)
  2066. {
  2067. Debug.Assert(high + 1 < b.Length);
  2068. buf[++high] = (uint)(tmp64 >> 32);
  2069. }
  2070. scale += MaxInt32Scale;
  2071. }
  2072. if (d2.High == 0)
  2073. {
  2074. ulong divisor = d2.Low64 << shift;
  2075. switch (high)
  2076. {
  2077. case 6:
  2078. Div96By64(ref *(Buf12*)&b.Buf24.U4, divisor);
  2079. goto case 5;
  2080. case 5:
  2081. Div96By64(ref *(Buf12*)&b.Buf24.U3, divisor);
  2082. goto case 4;
  2083. case 4:
  2084. Div96By64(ref *(Buf12*)&b.Buf24.U2, divisor);
  2085. break;
  2086. }
  2087. Div96By64(ref *(Buf12*)&b.Buf24.U1, divisor);
  2088. Div96By64(ref *(Buf12*)&b, divisor);
  2089. d1.Low64 = b.Buf24.Low64 >> shift;
  2090. d1.High = 0;
  2091. }
  2092. else
  2093. {
  2094. Unsafe.SkipInit(out Buf12 bufDivisor);
  2095. DebugPoison(ref bufDivisor);
  2096. bufDivisor.Low64 = d2.Low64 << shift;
  2097. bufDivisor.U2 = (uint)((d2.Mid + ((ulong)d2.High << 32)) >> (32 - shift));
  2098. switch (high)
  2099. {
  2100. case 6:
  2101. Div128By96(ref *(Buf16*)&b.Buf24.U3, ref bufDivisor);
  2102. goto case 5;
  2103. case 5:
  2104. Div128By96(ref *(Buf16*)&b.Buf24.U2, ref bufDivisor);
  2105. goto case 4;
  2106. case 4:
  2107. Div128By96(ref *(Buf16*)&b.Buf24.U1, ref bufDivisor);
  2108. break;
  2109. }
  2110. Div128By96(ref *(Buf16*)&b, ref bufDivisor);
  2111. d1.Low64 = (b.Buf24.Low64 >> shift) + ((ulong)b.Buf24.U2 << (32 - shift) << 32);
  2112. d1.High = b.Buf24.U2 >> shift;
  2113. }
  2114. }
  2115. // Does an in-place round by the specified scale
  2116. internal static void InternalRound(ref DecCalc d, uint scale, MidpointRounding mode)
  2117. {
  2118. // the scale becomes the desired decimal count
  2119. d.uflags -= scale << ScaleShift;
  2120. uint remainder, sticky = 0, power;
  2121. // First divide the value by constant 10^9 up to three times
  2122. while (scale >= MaxInt32Scale)
  2123. {
  2124. scale -= MaxInt32Scale;
  2125. const uint divisor = TenToPowerNine;
  2126. uint n = d.uhi;
  2127. if (n == 0)
  2128. {
  2129. ulong tmp = d.Low64;
  2130. ulong div = tmp / divisor;
  2131. d.Low64 = div;
  2132. remainder = (uint)(tmp - div * divisor);
  2133. }
  2134. else
  2135. {
  2136. uint q;
  2137. d.uhi = q = n / divisor;
  2138. remainder = n - q * divisor;
  2139. n = d.umid;
  2140. if ((n | remainder) != 0)
  2141. {
  2142. d.umid = q = (uint)((((ulong)remainder << 32) | n) / divisor);
  2143. remainder = n - q * divisor;
  2144. }
  2145. n = d.ulo;
  2146. if ((n | remainder) != 0)
  2147. {
  2148. d.ulo = q = (uint)((((ulong)remainder << 32) | n) / divisor);
  2149. remainder = n - q * divisor;
  2150. }
  2151. }
  2152. power = divisor;
  2153. if (scale == 0)
  2154. goto checkRemainder;
  2155. sticky |= remainder;
  2156. }
  2157. {
  2158. power = s_powers10[scale];
  2159. // TODO: https://github.com/dotnet/coreclr/issues/3439
  2160. uint n = d.uhi;
  2161. if (n == 0)
  2162. {
  2163. ulong tmp = d.Low64;
  2164. if (tmp == 0)
  2165. {
  2166. if (mode <= MidpointRounding.ToZero)
  2167. goto done;
  2168. remainder = 0;
  2169. goto checkRemainder;
  2170. }
  2171. ulong div = tmp / power;
  2172. d.Low64 = div;
  2173. remainder = (uint)(tmp - div * power);
  2174. }
  2175. else
  2176. {
  2177. uint q;
  2178. d.uhi = q = n / power;
  2179. remainder = n - q * power;
  2180. n = d.umid;
  2181. if ((n | remainder) != 0)
  2182. {
  2183. d.umid = q = (uint)((((ulong)remainder << 32) | n) / power);
  2184. remainder = n - q * power;
  2185. }
  2186. n = d.ulo;
  2187. if ((n | remainder) != 0)
  2188. {
  2189. d.ulo = q = (uint)((((ulong)remainder << 32) | n) / power);
  2190. remainder = n - q * power;
  2191. }
  2192. }
  2193. }
  2194. checkRemainder:
  2195. if (mode == MidpointRounding.ToZero)
  2196. goto done;
  2197. else if (mode == MidpointRounding.ToEven)
  2198. {
  2199. // To do IEEE rounding, we add LSB of result to sticky bits so either causes round up if remainder * 2 == last divisor.
  2200. remainder <<= 1;
  2201. if ((sticky | d.ulo & 1) != 0)
  2202. remainder++;
  2203. if (power >= remainder)
  2204. goto done;
  2205. }
  2206. else if (mode == MidpointRounding.AwayFromZero)
  2207. {
  2208. // Round away from zero at the mid point.
  2209. remainder <<= 1;
  2210. if (power > remainder)
  2211. goto done;
  2212. }
  2213. else if (mode == MidpointRounding.ToNegativeInfinity)
  2214. {
  2215. // Round toward -infinity if we have chopped off a non-zero amount from a negative value.
  2216. if ((remainder | sticky) == 0 || !d.IsNegative)
  2217. goto done;
  2218. }
  2219. else
  2220. {
  2221. Debug.Assert(mode == MidpointRounding.ToPositiveInfinity);
  2222. // Round toward infinity if we have chopped off a non-zero amount from a positive value.
  2223. if ((remainder | sticky) == 0 || d.IsNegative)
  2224. goto done;
  2225. }
  2226. if (++d.Low64 == 0)
  2227. d.uhi++;
  2228. done:
  2229. return;
  2230. }
  2231. internal static uint DecDivMod1E9(ref DecCalc value)
  2232. {
  2233. ulong high64 = ((ulong)value.uhi << 32) + value.umid;
  2234. ulong div64 = high64 / TenToPowerNine;
  2235. value.uhi = (uint)(div64 >> 32);
  2236. value.umid = (uint)div64;
  2237. ulong num = ((high64 - (uint)div64 * TenToPowerNine) << 32) + value.ulo;
  2238. uint div = (uint)(num / TenToPowerNine);
  2239. value.ulo = div;
  2240. return (uint)num - div * TenToPowerNine;
  2241. }
  2242. private struct PowerOvfl
  2243. {
  2244. public readonly uint Hi;
  2245. public readonly ulong MidLo;
  2246. public PowerOvfl(uint hi, uint mid, uint lo)
  2247. {
  2248. Hi = hi;
  2249. MidLo = ((ulong)mid << 32) + lo;
  2250. }
  2251. }
  2252. private static readonly PowerOvfl[] PowerOvflValues = new[]
  2253. {
  2254. // This is a table of the largest values that can be in the upper two
  2255. // uints of a 96-bit number that will not overflow when multiplied
  2256. // by a given power. For the upper word, this is a table of
  2257. // 2^32 / 10^n for 1 <= n <= 8. For the lower word, this is the
  2258. // remaining fraction part * 2^32. 2^32 = 4294967296.
  2259. //
  2260. new PowerOvfl(429496729, 2576980377, 2576980377), // 10^1 remainder 0.6
  2261. new PowerOvfl(42949672, 4123168604, 687194767), // 10^2 remainder 0.16
  2262. new PowerOvfl(4294967, 1271310319, 2645699854), // 10^3 remainder 0.616
  2263. new PowerOvfl(429496, 3133608139, 694066715), // 10^4 remainder 0.1616
  2264. new PowerOvfl(42949, 2890341191, 2216890319), // 10^5 remainder 0.51616
  2265. new PowerOvfl(4294, 4154504685, 2369172679), // 10^6 remainder 0.551616
  2266. new PowerOvfl(429, 2133437386, 4102387834), // 10^7 remainder 0.9551616
  2267. new PowerOvfl(42, 4078814305, 410238783), // 10^8 remainder 0.09991616
  2268. };
  2269. [StructLayout(LayoutKind.Explicit)]
  2270. private struct Buf12
  2271. {
  2272. [FieldOffset(0 * 4)]
  2273. public uint U0;
  2274. [FieldOffset(1 * 4)]
  2275. public uint U1;
  2276. [FieldOffset(2 * 4)]
  2277. public uint U2;
  2278. [FieldOffset(0)]
  2279. private ulong ulo64LE;
  2280. [FieldOffset(4)]
  2281. private ulong uhigh64LE;
  2282. public ulong Low64
  2283. {
  2284. #if BIGENDIAN
  2285. get => ((ulong)U1 << 32) | U0;
  2286. set { U1 = (uint)(value >> 32); U0 = (uint)value; }
  2287. #else
  2288. get => ulo64LE;
  2289. set => ulo64LE = value;
  2290. #endif
  2291. }
  2292. /// <summary>
  2293. /// U1-U2 combined (overlaps with Low64)
  2294. /// </summary>
  2295. public ulong High64
  2296. {
  2297. #if BIGENDIAN
  2298. get => ((ulong)U2 << 32) | U1;
  2299. set { U2 = (uint)(value >> 32); U1 = (uint)value; }
  2300. #else
  2301. get => uhigh64LE;
  2302. set => uhigh64LE = value;
  2303. #endif
  2304. }
  2305. }
  2306. [StructLayout(LayoutKind.Explicit)]
  2307. private struct Buf16
  2308. {
  2309. [FieldOffset(0 * 4)]
  2310. public uint U0;
  2311. [FieldOffset(1 * 4)]
  2312. public uint U1;
  2313. [FieldOffset(2 * 4)]
  2314. public uint U2;
  2315. [FieldOffset(3 * 4)]
  2316. public uint U3;
  2317. [FieldOffset(0 * 8)]
  2318. private ulong ulo64LE;
  2319. [FieldOffset(1 * 8)]
  2320. private ulong uhigh64LE;
  2321. public ulong Low64
  2322. {
  2323. #if BIGENDIAN
  2324. get => ((ulong)U1 << 32) | U0;
  2325. set { U1 = (uint)(value >> 32); U0 = (uint)value; }
  2326. #else
  2327. get => ulo64LE;
  2328. set => ulo64LE = value;
  2329. #endif
  2330. }
  2331. public ulong High64
  2332. {
  2333. #if BIGENDIAN
  2334. get => ((ulong)U3 << 32) | U2;
  2335. set { U3 = (uint)(value >> 32); U2 = (uint)value; }
  2336. #else
  2337. get => uhigh64LE;
  2338. set => uhigh64LE = value;
  2339. #endif
  2340. }
  2341. }
  2342. [StructLayout(LayoutKind.Explicit)]
  2343. private struct Buf24
  2344. {
  2345. [FieldOffset(0 * 4)]
  2346. public uint U0;
  2347. [FieldOffset(1 * 4)]
  2348. public uint U1;
  2349. [FieldOffset(2 * 4)]
  2350. public uint U2;
  2351. [FieldOffset(3 * 4)]
  2352. public uint U3;
  2353. [FieldOffset(4 * 4)]
  2354. public uint U4;
  2355. [FieldOffset(5 * 4)]
  2356. public uint U5;
  2357. [FieldOffset(0 * 8)]
  2358. private ulong ulo64LE;
  2359. [FieldOffset(1 * 8)]
  2360. private ulong umid64LE;
  2361. [FieldOffset(2 * 8)]
  2362. private ulong uhigh64LE;
  2363. public ulong Low64
  2364. {
  2365. #if BIGENDIAN
  2366. get => ((ulong)U1 << 32) | U0;
  2367. set { U1 = (uint)(value >> 32); U0 = (uint)value; }
  2368. #else
  2369. get => ulo64LE;
  2370. set => ulo64LE = value;
  2371. #endif
  2372. }
  2373. public ulong Mid64
  2374. {
  2375. #if BIGENDIAN
  2376. get => ((ulong)U3 << 32) | U2;
  2377. set { U3 = (uint)(value >> 32); U2 = (uint)value; }
  2378. #else
  2379. get => umid64LE;
  2380. set => umid64LE = value;
  2381. #endif
  2382. }
  2383. public ulong High64
  2384. {
  2385. #if BIGENDIAN
  2386. get => ((ulong)U5 << 32) | U4;
  2387. set { U5 = (uint)(value >> 32); U4 = (uint)value; }
  2388. #else
  2389. get => uhigh64LE;
  2390. set => uhigh64LE = value;
  2391. #endif
  2392. }
  2393. public int Length => 6;
  2394. }
  2395. private struct Buf28
  2396. {
  2397. public Buf24 Buf24;
  2398. public uint U6;
  2399. public int Length => 7;
  2400. }
  2401. }
  2402. }
  2403. }