decimal_rs/
decimal.rs

1// Copyright 2021 CoD Technologies Corp.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Decimal implementation.
16
17use crate::convert::MAX_I128_REPR;
18use crate::error::{DecimalConvertError, DecimalFormatError};
19use crate::u256::{POWERS_10, ROUNDINGS, U256};
20use stack_buf::StackVec;
21use std::cmp::Ordering;
22use std::fmt;
23use std::hash::{Hash, Hasher};
24use std::io;
25
26/// Maximum precision of `Decimal`.
27pub const MAX_PRECISION: u32 = 38;
28/// Maximum binary data size of `Decimal`.
29pub const MAX_BINARY_SIZE: usize = 18;
30pub const MAX_SCALE: i16 = 130;
31pub const MIN_SCALE: i16 = -126;
32
33const SIGN_MASK: u8 = 0x01;
34const SCALE_MASK: u8 = 0x02;
35const SCALE_SHIFT: u8 = 1;
36
37/// When the precision of add/subtract/multiply result is not greater than `MAX_PRECISION`, use `DECIMAL128`.
38pub const DECIMAL128: u8 = 1;
39/// When the precision of add/subtract/multiply result is not greater than `DECIMAL64_MAX_PRECISION`, use `DECIMAL64`.
40pub const DECIMAL64: u8 = 2;
41/// Maximum precision of `Decimal64`.
42pub const DECIMAL64_MAX_PRECISION: u8 = 19;
43
44/// Computes by Taylor series, not accurate values.
45static NATURAL_EXP: [Decimal; 291] = [
46    // e^0
47    unsafe { Decimal::from_raw_parts(1, 0, false) },
48    unsafe { Decimal::from_raw_parts(27182818284590452353602874713526624975, 37, false) },
49    unsafe { Decimal::from_raw_parts(73890560989306502272304274605750078133, 37, false) },
50    unsafe { Decimal::from_raw_parts(20085536923187667740928529654581717900, 36, false) },
51    unsafe { Decimal::from_raw_parts(54598150033144239078110261202860878404, 36, false) },
52    // e^5
53    unsafe { Decimal::from_raw_parts(14841315910257660342111558004055227960, 35, false) },
54    unsafe { Decimal::from_raw_parts(40342879349273512260838718054338827962, 35, false) },
55    unsafe { Decimal::from_raw_parts(10966331584284585992637202382881214326, 34, false) },
56    unsafe { Decimal::from_raw_parts(29809579870417282747435920994528886736, 34, false) },
57    unsafe { Decimal::from_raw_parts(81030839275753840077099966894327599646, 34, false) },
58    // e^10
59    unsafe { Decimal::from_raw_parts(22026465794806716516957900645284244366, 33, false) },
60    unsafe { Decimal::from_raw_parts(59874141715197818455326485792257781616, 33, false) },
61    unsafe { Decimal::from_raw_parts(16275479141900392080800520489848678316, 32, false) },
62    unsafe { Decimal::from_raw_parts(44241339200892050332610277594908828183, 32, false) },
63    unsafe { Decimal::from_raw_parts(12026042841647767777492367707678594496, 31, false) },
64    // e^15
65    unsafe { Decimal::from_raw_parts(32690173724721106393018550460917213156, 31, false) },
66    unsafe { Decimal::from_raw_parts(88861105205078726367630237407814503509, 31, false) },
67    unsafe { Decimal::from_raw_parts(24154952753575298214775435180385823883, 30, false) },
68    unsafe { Decimal::from_raw_parts(65659969137330511138786503259060033570, 30, false) },
69    unsafe { Decimal::from_raw_parts(17848230096318726084491003378872270387, 29, false) },
70    // e^20
71    unsafe { Decimal::from_raw_parts(48516519540979027796910683054154055870, 29, false) },
72    unsafe { Decimal::from_raw_parts(13188157344832146972099988837453027850, 28, false) },
73    unsafe { Decimal::from_raw_parts(35849128461315915616811599459784206894, 28, false) },
74    unsafe { Decimal::from_raw_parts(97448034462489026000346326848229752775, 28, false) },
75    unsafe { Decimal::from_raw_parts(26489122129843472294139162152811882340, 27, false) },
76    // e^25
77    unsafe { Decimal::from_raw_parts(72004899337385872524161351466126157931, 27, false) },
78    unsafe { Decimal::from_raw_parts(19572960942883876426977639787609534281, 26, false) },
79    unsafe { Decimal::from_raw_parts(53204824060179861668374730434117744164, 26, false) },
80    unsafe { Decimal::from_raw_parts(14462570642914751736770474229969288564, 25, false) },
81    unsafe { Decimal::from_raw_parts(39313342971440420743886205808435276867, 25, false) },
82    // e^30
83    unsafe { Decimal::from_raw_parts(10686474581524462146990468650741401654, 24, false) },
84    unsafe { Decimal::from_raw_parts(29048849665247425231085682111679825660, 24, false) },
85    unsafe { Decimal::from_raw_parts(78962960182680695160978022635108224222, 24, false) },
86    unsafe { Decimal::from_raw_parts(21464357978591606462429776153126088037, 23, false) },
87    unsafe { Decimal::from_raw_parts(58346174252745488140290273461039101919, 23, false) },
88    // e^35
89    unsafe { Decimal::from_raw_parts(15860134523134307281296446257746601247, 22, false) },
90    unsafe { Decimal::from_raw_parts(43112315471151952271134222928569253911, 22, false) },
91    unsafe { Decimal::from_raw_parts(11719142372802611308772939791190194524, 21, false) },
92    unsafe { Decimal::from_raw_parts(31855931757113756220328671701298645997, 21, false) },
93    unsafe { Decimal::from_raw_parts(86593400423993746953606932719264934249, 21, false) },
94    // e^40
95    unsafe { Decimal::from_raw_parts(23538526683701998540789991074903480449, 20, false) },
96    unsafe { Decimal::from_raw_parts(63984349353005494922266340351557081880, 20, false) },
97    unsafe { Decimal::from_raw_parts(17392749415205010473946813036112352260, 19, false) },
98    unsafe { Decimal::from_raw_parts(47278394682293465614744575627442803712, 19, false) },
99    unsafe { Decimal::from_raw_parts(12851600114359308275809299632143099259, 18, false) },
100    // e^45
101    unsafe { Decimal::from_raw_parts(34934271057485095348034797233406099546, 18, false) },
102    unsafe { Decimal::from_raw_parts(94961194206024488745133649117118323116, 18, false) },
103    unsafe { Decimal::from_raw_parts(25813128861900673962328580021527338043, 17, false) },
104    unsafe { Decimal::from_raw_parts(70167359120976317386547159988611740555, 17, false) },
105    unsafe { Decimal::from_raw_parts(19073465724950996905250998409538484479, 16, false) },
106    // e^50
107    unsafe { Decimal::from_raw_parts(51847055285870724640874533229334853872, 16, false) },
108    unsafe { Decimal::from_raw_parts(14093490824269387964492143312370168789, 15, false) },
109    unsafe { Decimal::from_raw_parts(38310080007165768493035695487861993900, 15, false) },
110    unsafe { Decimal::from_raw_parts(10413759433029087797183472933493796442, 14, false) },
111    unsafe { Decimal::from_raw_parts(28307533032746939004420635480140745403, 14, false) },
112    // e^55
113    unsafe { Decimal::from_raw_parts(76947852651420171381827455901293939935, 14, false) },
114    unsafe { Decimal::from_raw_parts(20916594960129961539070711572146737783, 13, false) },
115    unsafe { Decimal::from_raw_parts(56857199993359322226403488206332533049, 13, false) },
116    unsafe { Decimal::from_raw_parts(15455389355901039303530766911174620071, 12, false) },
117    unsafe { Decimal::from_raw_parts(42012104037905142549565934307191617692, 12, false) },
118    // e^60
119    unsafe { Decimal::from_raw_parts(11420073898156842836629571831447656295, 11, false) },
120    unsafe { Decimal::from_raw_parts(31042979357019199087073421411071003730, 11, false) },
121    unsafe { Decimal::from_raw_parts(84383566687414544890733294803731179603, 11, false) },
122    unsafe { Decimal::from_raw_parts(22937831594696098790993528402686136005, 10, false) },
123    unsafe { Decimal::from_raw_parts(62351490808116168829092387089284697469, 10, false) },
124    // e^65
125    unsafe { Decimal::from_raw_parts(16948892444103337141417836114371974954, 9, false) },
126    unsafe { Decimal::from_raw_parts(46071866343312915426773184428060086892, 9, false) },
127    unsafe { Decimal::from_raw_parts(12523631708422137805135219607443657677, 8, false) },
128    unsafe { Decimal::from_raw_parts(34042760499317405213769071870043505954, 8, false) },
129    unsafe { Decimal::from_raw_parts(92537817255877876002423979166873458740, 8, false) },
130    // e^70
131    unsafe { Decimal::from_raw_parts(25154386709191670062657811742521129623, 7, false) },
132    unsafe { Decimal::from_raw_parts(68376712297627438667558928266777109561, 7, false) },
133    unsafe { Decimal::from_raw_parts(18586717452841279803403701812545411949, 6, false) },
134    unsafe { Decimal::from_raw_parts(50523936302761041945570383321857646506, 6, false) },
135    unsafe { Decimal::from_raw_parts(13733829795401761877841885298085389320, 5, false) },
136    // e^75
137    unsafe { Decimal::from_raw_parts(37332419967990016402549083172647001445, 5, false) },
138    unsafe { Decimal::from_raw_parts(10148003881138887278324617841317169760, 4, false) },
139    unsafe { Decimal::from_raw_parts(27585134545231702062864698199026619434, 4, false) },
140    unsafe { Decimal::from_raw_parts(74984169969901204346756305912240604567, 4, false) },
141    unsafe { Decimal::from_raw_parts(20382810665126687668323137537172632374, 3, false) },
142    // e^80
143    unsafe { Decimal::from_raw_parts(55406223843935100525711733958316612937, 3, false) },
144    unsafe { Decimal::from_raw_parts(15060973145850305483525941301676749817, 2, false) },
145    unsafe { Decimal::from_raw_parts(40939969621274546966609142293278290448, 2, false) },
146    unsafe { Decimal::from_raw_parts(11128637547917594120870714781839408062, 1, false) },
147    unsafe { Decimal::from_raw_parts(30250773222011423382665663964434287432, 1, false) },
148    // e^85
149    unsafe { Decimal::from_raw_parts(82230127146229135103043280164077746957, 1, false) },
150    unsafe { Decimal::from_raw_parts(22352466037347150474430657323327147399, 0, false) },
151    unsafe { Decimal::from_raw_parts(60760302250568721495223289381302760758, 0, false) },
152    unsafe { Decimal::from_raw_parts(16516362549940018555283297962648587672, -1, false) },
153    unsafe { Decimal::from_raw_parts(44896128191743452462842455796453162784, -1, false) },
154    // e^90
155    unsafe { Decimal::from_raw_parts(12204032943178408020027100351363697548, -2, false) },
156    unsafe { Decimal::from_raw_parts(33174000983357426257555161078525919101, -2, false) },
157    unsafe { Decimal::from_raw_parts(90176284050342989314009959821709052567, -2, false) },
158    unsafe { Decimal::from_raw_parts(24512455429200857855527729431109153420, -3, false) },
159    unsafe { Decimal::from_raw_parts(66631762164108958342448140502408732643, -3, false) },
160    // e^95
161    unsafe { Decimal::from_raw_parts(18112390828890232821937987580988159254, -4, false) },
162    unsafe { Decimal::from_raw_parts(49234582860120583997548620591133044956, -4, false) },
163    unsafe { Decimal::from_raw_parts(13383347192042695004617364087061150290, -5, false) },
164    unsafe { Decimal::from_raw_parts(36379709476088045792877438267601857313, -5, false) },
165    unsafe { Decimal::from_raw_parts(98890303193469467705600309671380371021, -5, false) },
166    // e^100
167    unsafe { Decimal::from_raw_parts(26881171418161354484126255515800135886, -6, false) },
168    unsafe { Decimal::from_raw_parts(73070599793680672726476826340615135883, -6, false) },
169    unsafe { Decimal::from_raw_parts(19862648361376543258740468906137709930, -7, false) },
170    unsafe { Decimal::from_raw_parts(53992276105801688697616842371936818967, -7, false) },
171    unsafe { Decimal::from_raw_parts(14676622301554423285107021120870470922, -8, false) },
172    // e^105
173    unsafe { Decimal::from_raw_parts(39895195705472158507637572787300953989, -8, false) },
174    unsafe { Decimal::from_raw_parts(10844638552900230813361001028568739551, -9, false) },
175    unsafe { Decimal::from_raw_parts(29478783914555093773878202487079276618, -9, false) },
176    unsafe { Decimal::from_raw_parts(80131642640005911410561058362935555141, -9, false) },
177    unsafe { Decimal::from_raw_parts(21782038807290206355539393313936824934, -10, false) },
178    // e^110
179    unsafe { Decimal::from_raw_parts(59209720276646702989552288155880397734, -10, false) },
180    unsafe { Decimal::from_raw_parts(16094870669615180549262332993373505801, -11, false) },
181    unsafe { Decimal::from_raw_parts(43750394472613410734625746750879389186, -11, false) },
182    unsafe { Decimal::from_raw_parts(11892590228282008819681954096389267312, -12, false) },
183    unsafe { Decimal::from_raw_parts(32327411910848593114262354205829189194, -12, false) },
184    // e^115
185    unsafe { Decimal::from_raw_parts(87875016358370231131069738030496383831, -12, false) },
186    unsafe { Decimal::from_raw_parts(23886906014249914254626392949441611667, -13, false) },
187    unsafe { Decimal::from_raw_parts(64931342556644621362249507087712085619, -13, false) },
188    unsafe { Decimal::from_raw_parts(17650168856917655832911782056447182390, -14, false) },
189    unsafe { Decimal::from_raw_parts(47978133272993021860034882895011331584, -14, false) },
190    // e^120
191    unsafe { Decimal::from_raw_parts(13041808783936322797338790280986488115, -15, false) },
192    unsafe { Decimal::from_raw_parts(35451311827611664751894074212478186941, -15, false) },
193    unsafe { Decimal::from_raw_parts(96366656736032012717638730141942241231, -15, false) },
194    unsafe { Decimal::from_raw_parts(26195173187490626761889810253746390880, -16, false) },
195    unsafe { Decimal::from_raw_parts(71205863268893377088330680682701942197, -16, false) },
196    // e^125
197    unsafe { Decimal::from_raw_parts(19355760420357225687206244905274872200, -17, false) },
198    unsafe { Decimal::from_raw_parts(52614411826663857451767767041616346183, -17, false) },
199    unsafe { Decimal::from_raw_parts(14302079958348104463583671072905261088, -18, false) },
200    unsafe { Decimal::from_raw_parts(38877084059945950922226736883574780745, -18, false) },
201    unsafe { Decimal::from_raw_parts(10567887114362588125648834960427354587, -19, false) },
202    // e^130
203    unsafe { Decimal::from_raw_parts(28726495508178319332673332249621538192, -19, false) },
204    unsafe { Decimal::from_raw_parts(78086710735191511717214963161789844250, -19, false) },
205    unsafe { Decimal::from_raw_parts(21226168683560893890870118295564590878, -20, false) },
206    unsafe { Decimal::from_raw_parts(57698708620330031794130831485493325609, -20, false) },
207    unsafe { Decimal::from_raw_parts(15684135116819639406725212333317378882, -21, false) },
208    // e^135
209    unsafe { Decimal::from_raw_parts(42633899483147210448936866880765989362, -21, false) },
210    unsafe { Decimal::from_raw_parts(11589095424138854283480495676005460415, -22, false) },
211    unsafe { Decimal::from_raw_parts(31502427499714519184111642911336978953, -22, false) },
212    unsafe { Decimal::from_raw_parts(85632476224822491931954909086237584537, -22, false) },
213    unsafe { Decimal::from_raw_parts(23277320404788620254741750385140984218, -23, false) },
214    // e^140
215    unsafe { Decimal::from_raw_parts(63274317071555853643430245123511451556, -23, false) },
216    unsafe { Decimal::from_raw_parts(17199742630376622641833783925547830056, -24, false) },
217    unsafe { Decimal::from_raw_parts(46753747846325154027207734100637066905, -24, false) },
218    unsafe { Decimal::from_raw_parts(12708986318302188795555166499146091281, -25, false) },
219    unsafe { Decimal::from_raw_parts(34546606567175463231258517866889865270, -25, false) },
220    // e^145
221    unsafe { Decimal::from_raw_parts(93907412866476978131540504016909901172, -25, false) },
222    unsafe { Decimal::from_raw_parts(25526681395254551047668755808654353440, -26, false) },
223    unsafe { Decimal::from_raw_parts(69388714177584033016228037440452491187, -26, false) },
224    unsafe { Decimal::from_raw_parts(18861808084906520052196148181812219044, -27, false) },
225    unsafe { Decimal::from_raw_parts(51271710169083297668258887684658163998, -27, false) },
226    // e^150
227    unsafe { Decimal::from_raw_parts(13937095806663796973183419371414574787, -28, false) },
228    unsafe { Decimal::from_raw_parts(37884954272746958042494750441949388081, -28, false) },
229    unsafe { Decimal::from_raw_parts(10298198277160991943993878773913738166, -29, false) },
230    unsafe { Decimal::from_raw_parts(27993405242674970683739228910895090969, -29, false) },
231    unsafe { Decimal::from_raw_parts(76093964787853542218200718174787272690, -29, false) },
232    // e^155
233    unsafe { Decimal::from_raw_parts(20684484173822473091270347966282423297, -30, false) },
234    unsafe { Decimal::from_raw_parts(56226257460750335807897650819666306371, -30, false) },
235    unsafe { Decimal::from_raw_parts(15283881393781745666100414040841103028, -31, false) },
236    unsafe { Decimal::from_raw_parts(41545897061040224373905771068319348361, -31, false) },
237    unsafe { Decimal::from_raw_parts(11293345702805569478727022021871312858, -32, false) },
238    // e^160
239    unsafe { Decimal::from_raw_parts(30698496406442424667364570301654957343, -32, false) },
240    unsafe { Decimal::from_raw_parts(83447164942647743609658358092023252638, -32, false) },
241    unsafe { Decimal::from_raw_parts(22683291210002404713058390312611402982, -33, false) },
242    unsafe { Decimal::from_raw_parts(61659578305794325320049670543781654770, -33, false) },
243    unsafe { Decimal::from_raw_parts(16760811125908827725861073497722332472, -34, false) },
244    // e^165
245    unsafe { Decimal::from_raw_parts(45560608313792156880112864411796691453, -34, false) },
246    unsafe { Decimal::from_raw_parts(12384657367292132198269856467846840036, -35, false) },
247    unsafe { Decimal::from_raw_parts(33664989073201642477955778901752989037, -35, false) },
248    unsafe { Decimal::from_raw_parts(91510928052956339360089438336198973142, -35, false) },
249    unsafe { Decimal::from_raw_parts(24875249283177429446603994479964329509, -36, false) },
250    // e^170
251    unsafe { Decimal::from_raw_parts(67617938104850097226297739817614724043, -36, false) },
252    unsafe { Decimal::from_raw_parts(18380461242828247026619661332259011810, -37, false) },
253    unsafe { Decimal::from_raw_parts(49963273795075782374799992291440821058, -37, false) },
254    unsafe { Decimal::from_raw_parts(13581425924747849789093255011954118328, -38, false) },
255    unsafe { Decimal::from_raw_parts(36918143295804664423920014322334714971, -38, false) },
256    // e^175
257    unsafe { Decimal::from_raw_parts(10035391806143294571946733464755740501, -39, false) },
258    unsafe { Decimal::from_raw_parts(27279023188106115192557593199527116730, -39, false) },
259    unsafe { Decimal::from_raw_parts(74152073030341784283386937576609008214, -39, false) },
260    unsafe { Decimal::from_raw_parts(20156623266094612066329318409141309108, -40, false) },
261    unsafe { Decimal::from_raw_parts(54791382747319794379865564450966140139, -40, false) },
262    // e^180
263    unsafe { Decimal::from_raw_parts(14893842007818383595644410230322886973, -41, false) },
264    unsafe { Decimal::from_raw_parts(40485660085792693262271426689569678698, -41, false) },
265    unsafe { Decimal::from_raw_parts(11005143412437994843280976031210742493, -42, false) },
266    unsafe { Decimal::from_raw_parts(29915081357615969207184701601447122427, -42, false) },
267    unsafe { Decimal::from_raw_parts(81317622051281434061126712044925707902, -42, false) },
268    // e^185
269    unsafe { Decimal::from_raw_parts(22104421435549887327561037093210488312, -43, false) },
270    unsafe { Decimal::from_raw_parts(60086047116855861250341632178539649714, -43, false) },
271    unsafe { Decimal::from_raw_parts(16333081002168329377271943881088378495, -44, false) },
272    unsafe { Decimal::from_raw_parts(44397917290943821356155881988414973276, -44, false) },
273    unsafe { Decimal::from_raw_parts(12068605179340023095364473314473432497, -45, false) },
274    // e^190
275    unsafe { Decimal::from_raw_parts(32805870153846701518250084137059135841, -45, false) },
276    unsafe { Decimal::from_raw_parts(89175600705988431420770803324912086042, -45, false) },
277    unsafe { Decimal::from_raw_parts(24240441494100795852378097352461489720, -46, false) },
278    unsafe { Decimal::from_raw_parts(65892351627238821736753930934534639373, -46, false) },
279    unsafe { Decimal::from_raw_parts(17911398206275708900431827624144225532, -47, false) },
280    // e^195
281    unsafe { Decimal::from_raw_parts(48688228266413197067093362018659672146, -47, false) },
282    unsafe { Decimal::from_raw_parts(13234832615645703553069383005626040404, -48, false) },
283    unsafe { Decimal::from_raw_parts(35976005001806811307586628488491091980, -48, false) },
284    unsafe { Decimal::from_raw_parts(97792920656963176027414937748815917871, -48, false) },
285    unsafe { Decimal::from_raw_parts(26582871917376019734003283472389741150, -49, false) },
286    // e^200
287    unsafe { Decimal::from_raw_parts(72259737681257492581774770421893056951, -49, false) },
288    unsafe { Decimal::from_raw_parts(19642233186817958656484864137420231201, -50, false) },
289    unsafe { Decimal::from_raw_parts(53393125542082459716222599802082679919, -50, false) },
290    unsafe { Decimal::from_raw_parts(14513756292567525940523654914390132839, -51, false) },
291    unsafe { Decimal::from_raw_parts(39452479992769427900327573211143818566, -51, false) },
292    // e^205
293    unsafe { Decimal::from_raw_parts(10724295945198918021924451209369968217, -52, false) },
294    unsafe { Decimal::from_raw_parts(29151658790851239660496155224556382547, -52, false) },
295    unsafe { Decimal::from_raw_parts(79242424360609307491188688802264059684, -52, false) },
296    unsafe { Decimal::from_raw_parts(21540324218248465690209815988756000148, -53, false) },
297    unsafe { Decimal::from_raw_parts(58552671901581093475081587475320346051, -53, false) },
298    // e^210
299    unsafe { Decimal::from_raw_parts(15916266403779241591571863407774423364, -54, false) },
300    unsafe { Decimal::from_raw_parts(43264897742306309199371472477969207063, -54, false) },
301    unsafe { Decimal::from_raw_parts(11760618534305001227335647241278102208, -55, false) },
302    unsafe { Decimal::from_raw_parts(31968675653239935348846785115930182070, -55, false) },
303    unsafe { Decimal::from_raw_parts(86899870108103213822063274684049309002, -55, false) },
304    // e^215
305    unsafe { Decimal::from_raw_parts(23621833781030833300746567469515129092, -56, false) },
306    unsafe { Decimal::from_raw_parts(64210801521856135516771541362226454717, -56, false) },
307    unsafe { Decimal::from_raw_parts(17454305496765194050281862479081601620, -57, false) },
308    unsafe { Decimal::from_raw_parts(47445721460229655544587842889161196570, -57, false) },
309    unsafe { Decimal::from_raw_parts(12897084248347162974810234147016917437, -58, false) },
310    // e^220
311    unsafe { Decimal::from_raw_parts(35057909752387477224025060891275483360, -58, false) },
312    unsafe { Decimal::from_raw_parts(95297279023672025386355634986304892255, -58, false) },
313    unsafe { Decimal::from_raw_parts(25904486187163901031830171287130712546, -59, false) },
314    unsafe { Decimal::from_raw_parts(70415694078135969991088372949671264959, -59, false) },
315    unsafe { Decimal::from_raw_parts(19140970165092820820108477320064452781, -60, false) },
316    // e^225
317    unsafe { Decimal::from_raw_parts(52030551378848545923020205358078977737, -60, false) },
318    unsafe { Decimal::from_raw_parts(14143370233782872265039837168370554989, -61, false) },
319    unsafe { Decimal::from_raw_parts(38445666299660540093457531706674996418, -61, false) },
320    unsafe { Decimal::from_raw_parts(10450615608536754863982177507098957249, -62, false) },
321    unsafe { Decimal::from_raw_parts(28407718504895927718534013347769901830, -62, false) },
322    // e^230
323    unsafe { Decimal::from_raw_parts(77220184999838357175621252140277020406, -62, false) },
324    unsafe { Decimal::from_raw_parts(20990622567530634724568039312619468559, -63, false) },
325    unsafe { Decimal::from_raw_parts(57058427893360872481970148326895352874, -63, false) },
326    unsafe { Decimal::from_raw_parts(15510088770296358097556054518881247548, -64, false) },
327    unsafe { Decimal::from_raw_parts(42160792462083288741186917596094351517, -64, false) },
328    // e^235
329    unsafe { Decimal::from_raw_parts(11460491602311409370637865042895610414, -65, false) },
330    unsafe { Decimal::from_raw_parts(31152846067770590954201464312400440172, -65, false) },
331    unsafe { Decimal::from_raw_parts(84682215370802619418949577677244718361, -65, false) },
332    unsafe { Decimal::from_raw_parts(23019012723610800962705119766260408375, -66, false) },
333    unsafe { Decimal::from_raw_parts(62572163995658794914917604846876973579, -66, false) },
334    // e^240
335    unsafe { Decimal::from_raw_parts(17008877635675862685398902860714557440, -67, false) },
336    unsafe { Decimal::from_raw_parts(46234922999541146273426274861568776275, -67, false) },
337    unsafe { Decimal::from_raw_parts(12567955102985587136353369613287969585, -68, false) },
338    unsafe { Decimal::from_raw_parts(34163243977334849966907467619116852824, -68, false) },
339    unsafe { Decimal::from_raw_parts(92865325304802240908397570249090596499, -68, false) },
340    // e^245
341    unsafe { Decimal::from_raw_parts(25243412626998187770632793234418799940, -69, false) },
342    unsafe { Decimal::from_raw_parts(68618709832262784296500189663439273040, -69, false) },
343    unsafe { Decimal::from_raw_parts(18652499202934394647893057141276968924, -70, false) },
344    unsafe { Decimal::from_raw_parts(50702749638683390134216749367456409844, -70, false) },
345    unsafe { Decimal::from_raw_parts(13782436299574148088857901819149382333, -71, false) },
346    // e^250
347    unsafe { Decimal::from_raw_parts(37464546145026732603499548122029201501, -71, false) },
348    unsafe { Decimal::from_raw_parts(10183919499749154121311809801154593781, -72, false) },
349    unsafe { Decimal::from_raw_parts(27682763318657855929985771603963318292, -72, false) },
350    unsafe { Decimal::from_raw_parts(75249552490640263726958791405721841505, -72, false) },
351    unsafe { Decimal::from_raw_parts(20454949113498251750794190253329225813, -73, false) },
352    // e^255
353    unsafe { Decimal::from_raw_parts(55602316477276754174041540473381702051, -73, false) },
354    unsafe { Decimal::from_raw_parts(15114276650041035425200896657072865078, -74, false) },
355    unsafe { Decimal::from_raw_parts(41084863568109398732746435014199662608, -74, false) },
356    unsafe { Decimal::from_raw_parts(11168023806191082975759894188368741636, -75, false) },
357    unsafe { Decimal::from_raw_parts(30357836172167242865270564060096681892, -75, false) },
358    // e^260
359    unsafe { Decimal::from_raw_parts(82521154418138915708209187078469436590, -75, false) },
360    unsafe { Decimal::from_raw_parts(22431575451828987090132598854038981998, -76, false) },
361    unsafe { Decimal::from_raw_parts(60975343934414732803540925731945597709, -76, false) },
362    unsafe { Decimal::from_raw_parts(16574816940096003310288868055969816163, -77, false) },
363    unsafe { Decimal::from_raw_parts(45055023698298121117106125112845233389, -77, false) },
364    // e^265
365    unsafe { Decimal::from_raw_parts(12247225219987543111692123050999620531, -78, false) },
366    unsafe { Decimal::from_raw_parts(33291409764537471210498902650647395181, -78, false) },
367    unsafe { Decimal::from_raw_parts(90495434206726229847410205869155592671, -78, false) },
368    unsafe { Decimal::from_raw_parts(24599209436265500385962442739613565585, -79, false) },
369    unsafe { Decimal::from_raw_parts(66867584005058783767836195501715462777, -79, false) },
370    // e^270
371    unsafe { Decimal::from_raw_parts(18176493851390999782546650445313340672, -80, false) },
372    unsafe { Decimal::from_raw_parts(49408832941333720129685111047602318635, -80, false) },
373    unsafe { Decimal::from_raw_parts(13430713274979613085859250297613421779, -81, false) },
374    unsafe { Decimal::from_raw_parts(36508463838620754258131757683218532187, -81, false) },
375    unsafe { Decimal::from_raw_parts(99240293837476957258975386473680449662, -81, false) },
376    // e^275
377    unsafe { Decimal::from_raw_parts(26976308738934978232765417912571366677, -82, false) },
378    unsafe { Decimal::from_raw_parts(73329209843947893397917976493127739665, -82, false) },
379    unsafe { Decimal::from_raw_parts(19932945861406369879404057817936726125, -83, false) },
380    unsafe { Decimal::from_raw_parts(54183364522718865591003756988762312406, -83, false) },
381    unsafe { Decimal::from_raw_parts(14728565518687920080874372478970627032, -84, false) },
382    // e^280
383    unsafe { Decimal::from_raw_parts(40036392008717845384002607853055449617, -84, false) },
384    unsafe { Decimal::from_raw_parts(10883019687436065167926658665346876179, -85, false) },
385    unsafe { Decimal::from_raw_parts(29583114655119494191648535413124937628, -85, false) },
386    unsafe { Decimal::from_raw_parts(80415242996231796059259460914427322527, -85, false) },
387    unsafe { Decimal::from_raw_parts(21859129376777539785144693723458114365, -86, false) },
388    // e^285
389    unsafe { Decimal::from_raw_parts(59419274170829680786039665041625326132, -86, false) },
390    unsafe { Decimal::from_raw_parts(16151833323879222366041833857187834774, -87, false) },
391    unsafe { Decimal::from_raw_parts(43905235020600150754042953190395882915, -87, false) },
392    unsafe { Decimal::from_raw_parts(11934680253072108439235558933754921818, -88, false) },
393    unsafe { Decimal::from_raw_parts(32441824460394911649740723321265334285, -88, false) },
394    // e^290
395    unsafe { Decimal::from_raw_parts(88186021912749658986094822427733469383, -88, false) },
396];
397
398/// Computes by Taylor series, not accurate values.
399static NATURAL_EXP_NEG: [Decimal; 9] = [
400    // e^-291
401    unsafe { Decimal::from_raw_parts(41716298478166806118243377939293045745, 164, false) },
402    unsafe { Decimal::from_raw_parts(15346568571889094399003486191226211569, 164, false) },
403    unsafe { Decimal::from_raw_parts(56456870701257797059912015304055553681, 165, false) },
404    unsafe { Decimal::from_raw_parts(20769322043867093362333818538068856442, 165, false) },
405    // e^-295
406    unsafe { Decimal::from_raw_parts(76406065870075445735958388880036815267, 166, false) },
407    unsafe { Decimal::from_raw_parts(28108220814391766921916452972683068317, 166, false) },
408    unsafe { Decimal::from_raw_parts(10340436565521946602575863724595250916, 166, false) },
409    unsafe { Decimal::from_raw_parts(38040340251929620404917847776950070293, 167, false) },
410    unsafe { Decimal::from_raw_parts(13994259113851392172977837187029463838, 167, false) },
411];
412
413pub(crate) type Buf = stack_buf::StackVec<u8, 256>;
414
415/// High precision decimal.
416#[derive(Copy, Clone, Debug, Eq)]
417#[repr(C, packed(4))]
418pub struct Decimal {
419    int_val: u128,
420    // A positive scale means a negative power of 10
421    scale: i16,
422    negative: bool,
423    _aligned: u8,
424}
425
426impl Decimal {
427    /// Zero value, i.e. `0`.
428    pub const ZERO: Decimal = unsafe { Decimal::from_raw_parts(0, 0, false) };
429
430    /// i.e. `1`.
431    pub const ONE: Decimal = unsafe { Decimal::from_raw_parts(1, 0, false) };
432
433    /// i.e. `-1`.
434    const MINUS_ONE: Decimal = unsafe { Decimal::from_raw_parts(1, 0, true) };
435
436    /// i.e. `2`.
437    const TWO: Decimal = unsafe { Decimal::from_raw_parts(2, 0, false) };
438
439    /// i.e. `0.5`.
440    const ZERO_POINT_FIVE: Decimal = unsafe { Decimal::from_raw_parts(5, 1, false) };
441
442    #[inline]
443    pub(crate) const unsafe fn from_raw_parts(int_val: u128, scale: i16, negative: bool) -> Decimal {
444        Decimal {
445            int_val,
446            scale,
447            negative,
448            _aligned: 0,
449        }
450    }
451
452    /// Creates a `Decimal` from parts without boundary checking.
453    ///
454    /// # Safety
455    /// User have to guarantee that `int_val` has at most 38 tens digits and `scale` ranges from `[-126, 130]`.
456    #[inline]
457    pub const unsafe fn from_parts_unchecked(int_val: u128, scale: i16, negative: bool) -> Decimal {
458        if int_val != 0 {
459            Decimal::from_raw_parts(int_val, scale, negative)
460        } else {
461            Decimal::ZERO
462        }
463    }
464
465    /// Creates a `Decimal` from parts.
466    ///
467    /// `int_val` has at most 38 tens digits, `scale` ranges from `[-126, 130]`.
468    #[inline]
469    pub const fn from_parts(int_val: u128, scale: i16, negative: bool) -> Result<Decimal, DecimalConvertError> {
470        if int_val > MAX_I128_REPR as u128 {
471            return Err(DecimalConvertError::Overflow);
472        }
473
474        if scale >= MAX_SCALE + MAX_PRECISION as i16 || scale < MIN_SCALE {
475            return Err(DecimalConvertError::Overflow);
476        }
477
478        Ok(unsafe { Decimal::from_parts_unchecked(int_val, scale, negative) })
479    }
480
481    /// Consumes the `Decimal`, returning `(int_val, scale, negative)`.
482    #[inline]
483    pub const fn into_parts(self) -> (u128, i16, bool) {
484        (self.int_val, self.scale, self.negative)
485    }
486
487    /// Returns the precision, i.e. the count of significant digits in this decimal.
488    #[inline]
489    pub fn precision(&self) -> u8 {
490        U256::from(self.int_val).count_digits() as u8
491    }
492
493    #[inline(always)]
494    pub(crate) const fn int_val(&self) -> u128 {
495        self.int_val
496    }
497
498    /// Returns the scale, i.e. the count of decimal digits in the fractional part.
499    /// A positive scale means a negative power of 10.
500    #[inline(always)]
501    pub const fn scale(&self) -> i16 {
502        self.scale
503    }
504
505    /// Returns `true` if the sign bit of the decimal is negative.
506    #[inline(always)]
507    pub const fn is_sign_negative(&self) -> bool {
508        self.negative
509    }
510
511    /// Returns `true` if the sign bit of the decimal is positive.
512    #[inline(always)]
513    pub const fn is_sign_positive(&self) -> bool {
514        !self.negative
515    }
516
517    /// Checks if `self` is zero.
518    #[inline]
519    pub const fn is_zero(&self) -> bool {
520        self.int_val == 0
521    }
522
523    /// Computes the absolute value of `self`.
524    #[inline]
525    pub const fn abs(&self) -> Decimal {
526        let mut abs_val = *self;
527        abs_val.negative = false;
528        abs_val
529    }
530
531    #[inline]
532    pub(crate) fn neg_mut(&mut self) {
533        if !self.is_zero() {
534            self.negative = !self.negative;
535        }
536    }
537
538    #[inline]
539    fn encode_header(&self) -> [u8; 2] {
540        let sign = if self.is_sign_negative() { 1 } else { 0 };
541
542        let (scale_sign, abs_scale) = if self.scale <= 0 {
543            (0, (-self.scale) as u8)
544        } else {
545            (1, self.scale as u8)
546        };
547
548        let flags = (scale_sign << SCALE_SHIFT) | sign;
549
550        [flags, abs_scale]
551    }
552
553    /// Encodes `self` to `writer` as binary bytes.
554    /// Returns total size on success, which is not larger than [`MAX_BINARY_SIZE`].
555    fn internal_encode<W: io::Write, const COMPACT: bool>(&self, mut writer: W) -> std::io::Result<usize> {
556        if self.is_zero() {
557            return if COMPACT {
558                writer.write_all(&[0])?;
559                Ok(1)
560            } else {
561                writer.write_all(&[0; 3])?;
562                Ok(3)
563            };
564        }
565
566        let int_bytes: [u8; 16] = self.int_val.to_le_bytes();
567
568        let leading_zeros = self.int_val.leading_zeros() >> 3;
569        let trailing_non_zeros = 16 - leading_zeros as usize;
570
571        if COMPACT && trailing_non_zeros <= 2 && self.scale == 0 && self.is_sign_positive() {
572            debug_assert_ne!(trailing_non_zeros, 0);
573            return if trailing_non_zeros == 1 {
574                writer.write_all(&int_bytes[0..1])?;
575                Ok(1)
576            } else {
577                writer.write_all(&int_bytes[0..2])?;
578                Ok(2)
579            };
580        }
581
582        let header = self.encode_header();
583        writer.write_all(&header)?;
584        writer.write_all(&int_bytes[0..trailing_non_zeros])?;
585        let size = trailing_non_zeros + 2;
586
587        Ok(size)
588    }
589
590    /// Encodes `self` to `writer` as binary bytes.
591    /// Returns total size on success, which is not larger than [`MAX_BINARY_SIZE`].
592    #[inline]
593    pub fn encode<W: io::Write>(&self, writer: W) -> std::io::Result<usize> {
594        self.internal_encode::<_, false>(writer)
595    }
596
597    /// Encodes `self` to `writer` as binary bytes.
598    /// Returns total size on success, which is not larger than [`MAX_BINARY_SIZE`].
599    ///
600    /// The only different from [`Decimal::encode`] is it will compact encoded bytes
601    /// when `self` is zero or small positive integer.
602    #[inline]
603    pub fn compact_encode<W: io::Write>(&self, writer: W) -> std::io::Result<usize> {
604        self.internal_encode::<_, true>(writer)
605    }
606
607    /// Decodes a `Decimal` from binary bytes.
608    #[inline]
609    pub fn decode(bytes: &[u8]) -> Decimal {
610        let len = bytes.len();
611        assert!(len > 0);
612
613        if len <= 2 {
614            let int_val = if len == 1 {
615                bytes[0] as u128
616            } else {
617                ((bytes[1] as u128) << 8) | (bytes[0] as u128)
618            };
619
620            return unsafe { Decimal::from_parts_unchecked(int_val, 0, false) };
621        }
622
623        let flags = bytes[0];
624        let abs_scale = bytes[1];
625
626        let negative = (flags & SIGN_MASK) == 1;
627        let scale = if (flags & SCALE_MASK) != 0 {
628            abs_scale as i16
629        } else {
630            -(abs_scale as i16)
631        };
632
633        let mut int_bytes = [0; 16];
634        if len < MAX_BINARY_SIZE {
635            int_bytes[0..len - 2].copy_from_slice(&bytes[2..]);
636        } else {
637            int_bytes.copy_from_slice(&bytes[2..MAX_BINARY_SIZE]);
638        }
639        let int = u128::from_le_bytes(int_bytes);
640
641        unsafe { Decimal::from_parts_unchecked(int, scale, negative) }
642    }
643
644    /// Computes the smallest integer that is greater than or equal to `self`.
645    #[inline]
646    pub fn ceil(&self) -> Decimal {
647        if self.scale <= 0 {
648            return *self;
649        }
650
651        if self.scale > MAX_PRECISION as i16 {
652            return if self.negative { Decimal::ZERO } else { Decimal::ONE };
653        }
654
655        let divisor = POWERS_10[self.scale as usize].low();
656        let int_val = self.int_val / divisor;
657
658        let int_val = if !self.negative && self.int_val % divisor != 0 {
659            int_val + 1
660        } else {
661            int_val
662        };
663
664        unsafe { Decimal::from_parts_unchecked(int_val, 0, self.negative) }
665    }
666
667    /// Computes the largest integer that is equal to or less than `self`.
668    #[inline]
669    pub fn floor(&self) -> Decimal {
670        if self.scale <= 0 {
671            return *self;
672        }
673
674        if self.scale > MAX_PRECISION as i16 {
675            return if self.negative {
676                Decimal::MINUS_ONE
677            } else {
678                Decimal::ZERO
679            };
680        }
681
682        let divisor = POWERS_10[self.scale as usize].low();
683        let int_val = self.int_val / divisor;
684
685        let int_val = if !self.negative || self.int_val % divisor == 0 {
686            int_val
687        } else {
688            int_val + 1
689        };
690
691        unsafe { Decimal::from_parts_unchecked(int_val, 0, self.negative) }
692    }
693
694    /// Truncate a value to have `scale` digits after the decimal point.
695    /// We allow negative `scale`, implying a truncation before the decimal
696    /// point.
697    #[inline]
698    pub fn trunc(&self, scale: i16) -> Decimal {
699        // Limit the scale value to avoid possible overflow in calculations
700        let real_scale = if !self.is_zero() {
701            scale.max(MIN_SCALE).min(MAX_SCALE + MAX_PRECISION as i16 - 1)
702        } else {
703            return Decimal::ZERO;
704        };
705
706        if self.scale <= real_scale {
707            return *self;
708        }
709
710        let e = self.scale - real_scale;
711        debug_assert!(e > 0);
712        if e > MAX_PRECISION as i16 {
713            return Decimal::ZERO;
714        }
715
716        let int_val = self.int_val / POWERS_10[e as usize].low();
717
718        unsafe { Decimal::from_parts_unchecked(int_val, real_scale, self.negative) }
719    }
720
721    /// Round a value to have `scale` digits after the decimal point.
722    /// We allow negative `scale`, implying rounding before the decimal
723    /// point.
724    #[inline]
725    pub fn round(&self, scale: i16) -> Decimal {
726        // Limit the scale value to avoid possible overflow in calculations
727        let real_scale = if !self.is_zero() {
728            scale.max(MIN_SCALE).min(MAX_SCALE + MAX_PRECISION as i16 - 1)
729        } else {
730            return Decimal::ZERO;
731        };
732
733        if self.scale <= real_scale {
734            return *self;
735        }
736
737        let e = self.scale - real_scale;
738        debug_assert!(e > 0);
739        if e > MAX_PRECISION as i16 {
740            return Decimal::ZERO;
741        }
742
743        let int_val = (self.int_val + ROUNDINGS[e as usize].low()) / POWERS_10[e as usize].low();
744
745        unsafe { Decimal::from_parts_unchecked(int_val, real_scale, self.negative) }
746    }
747
748    /// Do bounds checking and rounding according to `precision` and `scale`.
749    ///
750    /// Returns `true` if overflows.
751    #[inline]
752    pub fn round_with_precision(&mut self, precision: u8, scale: i16) -> bool {
753        if self.is_zero() {
754            return false;
755        }
756
757        // N * 10^E < 10^(P - S)
758        // => log(N) + E < P - S
759        // => N < 10^(P - E - S)   N > 1
760        // => P > E + S
761
762        // E < P - S, E < 0
763        let e = scale - self.scale;
764        if e >= precision as i16 {
765            return true;
766        }
767
768        if e < -(self.precision() as i16) {
769            *self = Decimal::ZERO;
770            return false;
771        }
772
773        // N * 10^E = N * 10^(E + S) * 10^ (-S)
774        if e >= 0 {
775            let ceil = POWERS_10[(precision as i16 - e) as usize].low();
776            if self.int_val >= ceil {
777                return true;
778            }
779
780            if e == 0 {
781                return false;
782            }
783
784            let val = U256::mul128(self.int_val, POWERS_10[e as usize].low());
785            self.int_val = val.low();
786        } else {
787            let div_result = U256::from(self.int_val).div128_round(POWERS_10[-e as usize].low());
788            let ceil = POWERS_10[precision as usize].low();
789            self.int_val = div_result.low();
790            if self.int_val >= ceil {
791                return true;
792            }
793        }
794
795        self.scale = scale;
796        false
797    }
798
799    /// Normalize a `Decimal`'s scale toward specified `scale`.
800    #[inline]
801    pub fn normalize_to_scale(&self, scale: i16) -> Decimal {
802        if self.is_zero() {
803            return Decimal::ZERO;
804        }
805
806        if self.scale == scale {
807            return *self;
808        }
809
810        let mut current_scale = self.scale;
811        let mut int_val = self.int_val;
812
813        while current_scale > scale {
814            if int_val % 10 > 0 {
815                break;
816            }
817
818            int_val /= 10;
819            current_scale -= 1;
820        }
821
822        while current_scale < scale {
823            if int_val >= 10_0000_0000_0000_0000_0000_0000_0000_0000_0000_u128 {
824                break;
825            }
826
827            int_val *= 10;
828            current_scale += 1;
829        }
830
831        unsafe { Decimal::from_parts_unchecked(int_val, current_scale, self.negative) }
832    }
833
834    /// Normalize a `Decimal`'s scale toward zero.
835    #[inline]
836    pub fn normalize(&self) -> Decimal {
837        self.normalize_to_scale(0)
838    }
839
840    #[inline]
841    fn rescale_cmp(&self, other: &Decimal) -> Ordering {
842        debug_assert!(self.scale < other.scale);
843
844        let e = other.scale - self.scale;
845        debug_assert!(e > 0);
846        if e as u32 > MAX_PRECISION {
847            Ordering::Greater
848        } else {
849            let self_int_val = U256::mul128(self.int_val, POWERS_10[e as usize].low());
850            self_int_val.cmp128(other.int_val)
851        }
852    }
853
854    #[inline]
855    fn adjust_scale(int_val: U256, scale: i16, negative: bool) -> Option<Decimal> {
856        let digits = int_val.count_digits();
857        let s = scale as i32 - digits as i32;
858
859        if s >= MAX_SCALE as i32 {
860            return Some(Decimal::ZERO);
861        }
862
863        if s < MIN_SCALE as i32 {
864            // overflow
865            return None;
866        }
867
868        if digits > MAX_PRECISION {
869            let shift_scale = (digits - MAX_PRECISION) as i16;
870            return if shift_scale as u32 <= MAX_PRECISION {
871                let dividend = int_val + ROUNDINGS[shift_scale as usize].low();
872                let result = dividend / POWERS_10[shift_scale as usize].low();
873                Some(unsafe { Decimal::from_parts_unchecked(result.low(), scale - shift_scale, negative) })
874            } else {
875                let dividend = int_val + ROUNDINGS[shift_scale as usize];
876                let result = dividend / POWERS_10[shift_scale as usize];
877                Some(unsafe { Decimal::from_parts_unchecked(result.low(), scale - shift_scale, negative) })
878            };
879        }
880
881        Some(unsafe { Decimal::from_parts_unchecked(int_val.low(), scale, negative) })
882    }
883
884    #[inline]
885    fn rescale_add(&self, other: &Decimal, negative: bool) -> Option<Decimal> {
886        debug_assert!(self.scale < other.scale);
887
888        let e = other.scale - self.scale;
889        debug_assert!(e > 0);
890        if e as u32 > MAX_PRECISION {
891            if self.is_zero() {
892                return Some(unsafe { Decimal::from_parts_unchecked(other.int_val, other.scale, negative) });
893            }
894            if other.is_zero() {
895                return Some(unsafe { Decimal::from_parts_unchecked(self.int_val, self.scale, negative) });
896            }
897            if (e as usize) < POWERS_10.len() {
898                if let Some(self_int_val) = POWERS_10[e as usize].checked_mul(self.int_val) {
899                    if let Some(int_val) = self_int_val.checked_add(other.int_val) {
900                        return Decimal::adjust_scale(int_val, other.scale, negative);
901                    }
902                }
903            }
904
905            return Some(unsafe { Decimal::from_parts_unchecked(self.int_val, self.scale, negative) });
906        }
907
908        let self_int_val = U256::mul128(self.int_val, POWERS_10[e as usize].low());
909        let int_val = self_int_val + other.int_val;
910        Decimal::adjust_scale(int_val, other.scale, negative)
911    }
912
913    #[inline]
914    fn add_internal(&self, other: &Decimal, negative: bool) -> Option<Decimal> {
915        if self.scale != other.scale {
916            return if self.scale < other.scale {
917                self.rescale_add(other, negative)
918            } else {
919                other.rescale_add(self, negative)
920            };
921        }
922
923        let int_val = U256::add128(self.int_val, other.int_val);
924        if !int_val.is_decimal_overflowed() && self.scale >= 0 {
925            return Some(unsafe { Decimal::from_parts_unchecked(int_val.low(), self.scale, negative) });
926        }
927
928        Decimal::adjust_scale(int_val, self.scale, negative)
929    }
930
931    /// Make sure the two decimals have the same scale and result is not overflow.
932    #[inline]
933    unsafe fn add_internal_with_same_scale<const DECIMAL_MODEL: u8>(
934        &self,
935        other: &Decimal,
936        negative: bool,
937        scale: i16,
938    ) -> Decimal {
939        debug_assert!(self.scale == scale || self.is_zero());
940        debug_assert!(other.scale == scale || other.is_zero());
941        let val = match DECIMAL_MODEL {
942            DECIMAL64 => (self.int_val as u64 + other.int_val as u64) as u128,
943            _ => self.int_val + other.int_val,
944        };
945
946        Decimal::from_parts_unchecked(val, scale, negative)
947    }
948
949    #[inline]
950    fn rescale_sub(&self, other: &Decimal, negative: bool) -> Option<Decimal> {
951        debug_assert!(self.scale < other.scale);
952
953        let e = other.scale - self.scale;
954        debug_assert!(e > 0);
955        if e as u32 > MAX_PRECISION {
956            if (e as usize) < POWERS_10.len() {
957                if let Some(self_int_val) = POWERS_10[e as usize].checked_mul(self.int_val) {
958                    if let Some(int_val) = self_int_val.checked_sub(other.int_val) {
959                        return Decimal::adjust_scale(int_val, other.scale, negative);
960                    }
961                }
962            }
963
964            return Some(unsafe { Decimal::from_parts_unchecked(self.int_val(), self.scale, negative) });
965        }
966
967        let self_int_val = U256::mul128(self.int_val(), POWERS_10[e as usize].low());
968        let (int_val, neg) = if self_int_val >= other.int_val() {
969            let result = self_int_val - other.int_val();
970            (result, negative)
971        } else {
972            let result = other.int_val() - self_int_val;
973            (U256::from(result), !negative)
974        };
975
976        Decimal::adjust_scale(int_val, other.scale, neg)
977    }
978
979    #[inline]
980    fn sub_internal(&self, other: &Decimal, negative: bool) -> Option<Decimal> {
981        if other.int_val == 0 {
982            return Some(*self);
983        }
984
985        if self.int_val == 0 {
986            return Some(unsafe { Decimal::from_parts_unchecked(other.int_val, other.scale, !negative) });
987        }
988
989        if self.scale != other.scale {
990            return if self.scale < other.scale {
991                self.rescale_sub(other, negative)
992            } else {
993                other.rescale_sub(self, !negative)
994            };
995        }
996
997        debug_assert_eq!(self.scale, other.scale);
998        let (val, neg) = if self.int_val >= other.int_val {
999            (self.int_val - other.int_val, negative)
1000        } else {
1001            (other.int_val - self.int_val, !negative)
1002        };
1003
1004        Some(unsafe { Decimal::from_parts_unchecked(val, self.scale, neg) })
1005    }
1006
1007    #[inline]
1008    unsafe fn sub_internal_with_same_scale<const DECIMAL_MODEL: u8>(
1009        &self,
1010        other: &Decimal,
1011        negative: bool,
1012        scale: i16,
1013    ) -> Decimal {
1014        debug_assert!(self.scale == scale || self.is_zero());
1015        debug_assert!(other.scale == scale || other.is_zero());
1016        let (val, neg) = match DECIMAL_MODEL {
1017            DECIMAL64 => {
1018                let l = self.int_val as u64;
1019                let r = other.int_val as u64;
1020                if l >= r {
1021                    ((l - r) as u128, negative)
1022                } else {
1023                    ((r - l) as u128, !negative)
1024                }
1025            }
1026            _ => {
1027                if self.int_val >= other.int_val {
1028                    (self.int_val - other.int_val, negative)
1029                } else {
1030                    (other.int_val - self.int_val, !negative)
1031                }
1032            }
1033        };
1034        Decimal::from_parts_unchecked(val, scale, neg)
1035    }
1036
1037    /// Add two decimals.
1038    /// returning `None` if overflow occurred.
1039    #[inline]
1040    pub fn checked_add(&self, other: impl AsRef<Decimal>) -> Option<Decimal> {
1041        let other = other.as_ref();
1042        if self.negative != other.negative {
1043            if other.negative {
1044                self.sub_internal(other, self.negative)
1045            } else {
1046                other.sub_internal(self, other.negative)
1047            }
1048        } else {
1049            self.add_internal(other, self.negative)
1050        }
1051    }
1052
1053    /// Add two decimals.
1054    /// # Safety
1055    /// Make sure the decimal is zero or the scale is the same and the result is not overflow.
1056    #[inline]
1057    pub unsafe fn add_with_same_scale_unchecked<const DECIMAL_MODEL: u8>(
1058        &self,
1059        other: &Decimal,
1060        scale: i16,
1061    ) -> Decimal {
1062        if self.negative != other.negative {
1063            if other.negative {
1064                self.sub_internal_with_same_scale::<DECIMAL_MODEL>(other, self.negative, scale)
1065            } else {
1066                other.sub_internal_with_same_scale::<DECIMAL_MODEL>(self, other.negative, scale)
1067            }
1068        } else {
1069            self.add_internal_with_same_scale::<DECIMAL_MODEL>(other, self.negative, scale)
1070        }
1071    }
1072
1073    /// Add two decimals.
1074    /// # Safety
1075    /// Make sure the follow conditions
1076    /// 1. decimal is zero or the scale is the same.
1077    /// 2. the result is not overflow.
1078    /// 3. decimal is zero or the negative is the same.
1079    #[inline]
1080    pub unsafe fn add_with_same_scale_and_negative_unchecked<const DECIMAL_MODEL: u8>(
1081        &self,
1082        other: &Decimal,
1083        scale: i16,
1084        negative: bool,
1085    ) -> Decimal {
1086        debug_assert!(self.negative == negative || self.is_zero());
1087        debug_assert!(other.negative == negative || other.is_zero());
1088        self.add_internal_with_same_scale::<DECIMAL_MODEL>(other, negative, scale)
1089    }
1090
1091    /// Subtract one decimal from another,
1092    /// returning `None` if overflow occurred.
1093    #[inline]
1094    pub fn checked_sub(&self, other: impl AsRef<Decimal>) -> Option<Decimal> {
1095        let other = other.as_ref();
1096        if self.negative != other.negative {
1097            self.add_internal(other, self.negative)
1098        } else if self.negative {
1099            other.sub_internal(self, !self.negative)
1100        } else {
1101            self.sub_internal(other, self.negative)
1102        }
1103    }
1104
1105    /// Subtract one decimal from another,
1106    /// # Safety
1107    /// Make sure two decimal have the same scale or is zero and the result is not overflow.
1108    #[inline]
1109    pub unsafe fn sub_with_same_scale_unchecked<const DECIMAL_MODEL: u8>(
1110        &self,
1111        other: &Decimal,
1112        scale: i16,
1113    ) -> Decimal {
1114        if self.negative != other.negative {
1115            self.add_internal_with_same_scale::<DECIMAL_MODEL>(other, self.negative, scale)
1116        } else if self.negative {
1117            other.sub_internal_with_same_scale::<DECIMAL_MODEL>(self, !self.negative, scale)
1118        } else {
1119            self.sub_internal_with_same_scale::<DECIMAL_MODEL>(other, self.negative, scale)
1120        }
1121    }
1122
1123    /// Calculate the product of two decimals,
1124    /// returning `None` if overflow occurred.
1125    #[inline]
1126    pub fn checked_mul(&self, other: impl AsRef<Decimal>) -> Option<Decimal> {
1127        let other = other.as_ref();
1128
1129        if self.is_zero() || other.is_zero() {
1130            return Some(Decimal::ZERO);
1131        }
1132
1133        let scale = self.scale + other.scale;
1134        let negative = self.negative ^ other.negative;
1135        let int_val = U256::mul128(self.int_val, other.int_val);
1136
1137        if !int_val.is_decimal_overflowed() && scale == 0 {
1138            Some(unsafe { Decimal::from_parts_unchecked(int_val.low(), 0, negative) })
1139        } else {
1140            Decimal::adjust_scale(int_val, scale, negative)
1141        }
1142    }
1143
1144    /// Calculate the product of two decimals,
1145    /// # Safety
1146    /// Make sure the result scale is scale and the result is not overflow.
1147    #[inline]
1148    pub unsafe fn mul_unchecked<const DECIMAL_MODEL: u8>(&self, other: &Decimal, scale: i16) -> Decimal {
1149        let negative = self.negative ^ other.negative;
1150        let val = match DECIMAL_MODEL {
1151            DECIMAL64 => ((self.int_val) as u64 * (other.int_val as u64)) as u128,
1152            _ => self.int_val * other.int_val,
1153        };
1154        Decimal::from_parts_unchecked(val, scale, negative)
1155    }
1156
1157    /// Checked decimal division.
1158    /// Computes `self / other`, returning `None` if `other == 0` or the division results in overflow.
1159    #[inline]
1160    pub fn checked_div(&self, other: impl AsRef<Decimal>) -> Option<Decimal> {
1161        let other = other.as_ref();
1162
1163        if other.is_zero() {
1164            return None;
1165        }
1166
1167        if self.is_zero() {
1168            return Some(Decimal::ZERO);
1169        }
1170
1171        let other_precision = other.precision();
1172        let self_precision = self.precision();
1173
1174        let (self_int_val, shift_precision) = if other_precision > self_precision {
1175            let p = MAX_PRECISION + (other_precision - self_precision) as u32;
1176            (POWERS_10[p as usize] * self.int_val, other_precision - self_precision)
1177        } else {
1178            (U256::mul128(self.int_val, POWERS_10[MAX_PRECISION as usize].low()), 0)
1179        };
1180
1181        let negative = self.negative ^ other.negative;
1182        let int_val = self_int_val.div128_round(other.int_val);
1183        let scale = self.scale - other.scale + MAX_PRECISION as i16 + shift_precision as i16;
1184
1185        Decimal::adjust_scale(int_val, scale, negative)
1186    }
1187
1188    /// Checked decimal remainder.
1189    /// Computes `self % other`, returning None if rhs == 0 or the division results in overflow.
1190    #[inline]
1191    pub fn checked_rem(&self, other: impl AsRef<Decimal>) -> Option<Decimal> {
1192        let other = other.as_ref();
1193
1194        if other.is_zero() {
1195            return None;
1196        }
1197
1198        if self.is_zero() {
1199            return Some(Decimal::ZERO);
1200        }
1201
1202        if self.scale == other.scale {
1203            let rem = self.int_val % other.int_val;
1204            return Some(unsafe { Decimal::from_parts_unchecked(rem, self.scale, self.negative) });
1205        }
1206
1207        if self.scale < other.scale {
1208            let e = other.scale - self.scale;
1209            debug_assert!(e > 0);
1210
1211            let mut res = *self;
1212            loop {
1213                let scale = (MAX_PRECISION as i16).min(other.scale - res.scale);
1214                let res_val = U256::mul128(res.int_val, POWERS_10[scale as usize].low());
1215                let rem = res_val % other.int_val;
1216                res = unsafe { Decimal::from_parts_unchecked(rem.low(), res.scale + scale, res.negative) };
1217                if res.scale == other.scale || res.is_zero() {
1218                    break;
1219                }
1220            }
1221            Some(res)
1222        } else {
1223            let e = self.scale - other.scale;
1224            debug_assert!(e > 0);
1225            if e as u32 > MAX_PRECISION {
1226                return Some(*self);
1227            }
1228
1229            let other_int_val = U256::mul128(other.int_val, POWERS_10[e as usize].low());
1230            let rem = self.int_val % other_int_val;
1231            debug_assert_eq!(rem.high(), 0);
1232
1233            Some(unsafe { Decimal::from_parts_unchecked(rem.low(), self.scale, self.negative) })
1234        }
1235    }
1236
1237    /// Computes the square root of a decimal,
1238    /// returning None if `self` is negative or the results in overflow.
1239    #[inline]
1240    pub fn sqrt(&self) -> Option<Decimal> {
1241        if self.negative {
1242            return None;
1243        }
1244
1245        if self.is_zero() {
1246            return Some(Decimal::ZERO);
1247        }
1248
1249        let mut result = Decimal::ONE;
1250        let mut last = result;
1251
1252        loop {
1253            let val = self.checked_div(&result)?.normalize();
1254            result = result.checked_add(&val)?;
1255            result = result.checked_mul(&Decimal::ZERO_POINT_FIVE)?;
1256
1257            if result == last {
1258                break;
1259            }
1260
1261            last = result;
1262        }
1263
1264        Some(result)
1265    }
1266
1267    /// Formats the decimal, including sign and omitting integer zero in fractional.
1268    #[inline]
1269    pub fn simply_format<W: fmt::Write>(&self, w: W) -> Result<(), DecimalFormatError> {
1270        self.fmt_internal(true, true, true, None, w)
1271    }
1272
1273    #[inline]
1274    pub(crate) fn fmt_internal<W: fmt::Write>(
1275        &self,
1276        append_sign: bool,
1277        omit_integer_zero: bool,
1278        omit_frac_ending_zero: bool,
1279        precision: Option<usize>,
1280        mut w: W,
1281    ) -> Result<(), DecimalFormatError> {
1282        use std::fmt::Write;
1283
1284        const ZERO_BUF: [u8; 256] = [b'0'; 256];
1285
1286        if self.is_zero() {
1287            w.write_byte(b'0')?;
1288            return Ok(());
1289        }
1290
1291        let dec = if let Some(prec) = precision {
1292            self.round(prec as i16)
1293        } else {
1294            *self
1295        };
1296
1297        let scale = dec.scale();
1298
1299        if append_sign && self.is_sign_negative() {
1300            w.write_byte(b'-')?;
1301        }
1302
1303        if scale <= 0 {
1304            write!(w, "{}", dec.int_val())?;
1305            w.write_bytes(&ZERO_BUF[..-scale as usize])?;
1306            if let Some(prec) = precision {
1307                if prec != 0 {
1308                    w.write_byte(b'.')?;
1309                    w.write_bytes(&ZERO_BUF[..prec])?;
1310                }
1311            }
1312        } else {
1313            let mut buf = StackVec::<u8, 40>::new();
1314            write!(&mut buf, "{}", dec.int_val())?;
1315            let digits = buf.as_slice();
1316
1317            let len = digits.len();
1318            if len <= scale as usize {
1319                if !omit_integer_zero {
1320                    w.write_byte(b'0')?;
1321                }
1322                w.write_byte(b'.')?;
1323                w.write_bytes(&ZERO_BUF[..scale as usize - len])?;
1324                if omit_frac_ending_zero {
1325                    let zero_num = digits.iter().rev().take_while(|ch| **ch == b'0').count();
1326                    w.write_bytes(&digits[0..len - zero_num])?;
1327                } else {
1328                    w.write_bytes(digits)?;
1329                }
1330            } else {
1331                let (int_digits, frac_digits) = digits.split_at(len - scale as usize);
1332                w.write_bytes(int_digits)?;
1333                if let Some(prec) = precision {
1334                    w.write_byte(b'.')?;
1335                    let after_len = frac_digits.len();
1336                    if prec > after_len {
1337                        w.write_bytes(frac_digits)?;
1338                        w.write_bytes(&ZERO_BUF[..prec - after_len])?;
1339                    } else {
1340                        w.write_bytes(&frac_digits[0..prec])?;
1341                    }
1342                } else {
1343                    let zero_num = frac_digits.iter().rev().take_while(|ch| **ch == b'0').count();
1344                    if zero_num < frac_digits.len() {
1345                        w.write_byte(b'.')?;
1346                        w.write_bytes(&frac_digits[0..frac_digits.len() - zero_num])?;
1347                    }
1348                }
1349            }
1350        }
1351
1352        Ok(())
1353    }
1354
1355    #[inline]
1356    fn fmt_sci_internal<W: fmt::Write, const POSITIVE_EXP: bool, const MIN_SCALE: i16>(
1357        &self,
1358        expect_scale: i16,
1359        mut exp: u16,
1360        mut w: W,
1361    ) -> Result<(), DecimalFormatError> {
1362        if expect_scale >= MIN_SCALE {
1363            // Creates number part
1364            let temp_scale = if POSITIVE_EXP {
1365                expect_scale - exp as i16
1366            } else {
1367                expect_scale + exp as i16
1368            };
1369
1370            let mut dec = self.round(temp_scale);
1371
1372            // Whether number carries or not
1373            if dec.precision() > self.trunc(temp_scale).precision() {
1374                if POSITIVE_EXP {
1375                    exp += 1
1376                } else {
1377                    exp -= 1
1378                }
1379            }
1380
1381            // This decimal only includes scientific notation number part
1382            if POSITIVE_EXP {
1383                dec.scale += exp as i16
1384            } else {
1385                dec.scale -= exp as i16
1386            };
1387
1388            // Supplies zero to fill expect scale
1389            dec.fmt_internal(true, true, true, Some(expect_scale as usize), &mut w)?;
1390
1391            if POSITIVE_EXP {
1392                write_exp(b"E+", exp, true, w)?;
1393            } else {
1394                write_exp(b"E-", exp, true, w)?;
1395            }
1396        } else {
1397            return Err(DecimalFormatError::OutOfRange);
1398        }
1399
1400        Ok(())
1401    }
1402
1403    /// Formats the decimal, using scientific notation depending on the width.
1404    #[inline]
1405    pub fn format_with_sci<W: fmt::Write>(&self, max_width: u16, mut w: W) -> Result<(), DecimalFormatError> {
1406        const DOT_LEN: u16 = 1; // the length of "."
1407
1408        if self.is_zero() {
1409            w.write_byte(b'0')?;
1410            return Ok(());
1411        }
1412
1413        let precision = self.precision() as i16;
1414        let sign_len = if self.negative { 1 } else { 0 };
1415        // include ".", but without sign
1416        let max_digits = max_width - sign_len;
1417
1418        let (use_sci, positive_exp, prec): (bool, bool, Option<usize>) = if self.scale < precision {
1419            // integer part
1420            let int_len = (precision - self.scale) as u16;
1421            if max_digits >= int_len {
1422                if max_digits == int_len {
1423                    (false, true, Some(0))
1424                } else {
1425                    // length of the fractional part
1426                    let scale = (max_digits as u16 - int_len - DOT_LEN) as usize;
1427                    if scale as i16 >= self.scale() {
1428                        (false, true, None)
1429                    } else {
1430                        (false, true, Some(scale))
1431                    }
1432                }
1433            } else {
1434                // use sci notation, with "E+"
1435                (true, true, None)
1436            }
1437        } else if self.scale - precision >= 5 {
1438            if max_digits < self.scale as u16 + DOT_LEN {
1439                // use sci notation, with "E-"
1440                (true, false, None)
1441            } else {
1442                (false, true, None)
1443            }
1444        } else {
1445            // round the decimal
1446            let scale = max_width as usize - 1;
1447            (false, true, Some(scale))
1448        };
1449
1450        if use_sci {
1451            const E_NOTATION_LEN: usize = 2; // "E+" or "E-"
1452            const SCI_INT_LEN: i16 = 2; // e.g. "1."
1453
1454            // Ignore the sign in exponent part
1455            let exp = (precision - self.scale - 1).unsigned_abs();
1456            // 'E' + sign + exponent number
1457            let exp_len = E_NOTATION_LEN + if exp < 100 { 2 } else { 3 };
1458            // Remove integer and '.' in scientific notation
1459            let expect_scale = max_digits as i16 - exp_len as i16 - SCI_INT_LEN;
1460
1461            const MIN_SCALE: i16 = 1;
1462            if positive_exp {
1463                self.fmt_sci_internal::<W, true, MIN_SCALE>(expect_scale, exp, w)?;
1464            } else {
1465                self.fmt_sci_internal::<W, false, MIN_SCALE>(expect_scale, exp, w)?;
1466            }
1467        } else {
1468            self.fmt_internal(true, true, true, prec, w)?;
1469        }
1470
1471        Ok(())
1472    }
1473
1474    /// Formats the decimal, forced using scientific notation depending on the scale.
1475    ///
1476    /// In particular, the scientific notation is also enforced for 0.  
1477    /// When the decimal is 0 and expect_scale greater than 0, with_zero_before_dot determines whether there is a 0 before the decimal point.
1478    #[inline]
1479    pub fn format_with_sci_forced<W: fmt::Write>(
1480        &self,
1481        expect_scale: i16,
1482        with_zero_before_dot: bool,
1483        mut w: W,
1484    ) -> Result<(), DecimalFormatError> {
1485        // max_scale: 64(to_char max length) - 1(sign) - 1(.) -1(integer_count) - 5 = 56
1486        const MAX_SCALE: usize = 56;
1487        if expect_scale > MAX_SCALE as i16 {
1488            return Err(DecimalFormatError::OutOfRange);
1489        }
1490        let precision = self.precision() as i16;
1491        let exp = (precision - self.scale - 1).unsigned_abs();
1492        let positive_exp = precision > self.scale;
1493
1494        if self.is_zero() && expect_scale > 0 {
1495            const ZERO_BUF: [u8; MAX_SCALE] = [b'0'; MAX_SCALE];
1496            if with_zero_before_dot {
1497                w.write_bytes(b"0.")?;
1498            } else {
1499                w.write_bytes(b" .")?;
1500            }
1501            w.write_bytes(&ZERO_BUF[..expect_scale as usize - 1])?;
1502        }
1503
1504        const MIN_SCALE: i16 = 0;
1505        if positive_exp {
1506            self.fmt_sci_internal::<W, true, MIN_SCALE>(expect_scale, exp, w)?;
1507        } else {
1508            self.fmt_sci_internal::<W, false, MIN_SCALE>(expect_scale, exp, w)?;
1509        }
1510        Ok(())
1511    }
1512
1513    /// Format decimal as a hexadecimal number.
1514    ///
1515    /// A maximum of 63 digits hexadecimal positive number are supported.
1516    #[inline]
1517    pub fn format_to_hex<W: fmt::Write>(&self, is_uppercase: bool, mut w: W) -> Result<(), DecimalFormatError> {
1518        // Max number: u256::MAX/16 = 7237005577332262213973186563042994240829374041602535252466099000494570602495
1519        const MAX_DECIMAL: Decimal =
1520            unsafe { Decimal::from_parts_unchecked(72370055773322622139731865630429942408, -38, false) };
1521
1522        if self.is_sign_negative() || self > MAX_DECIMAL {
1523            return Err(DecimalFormatError::OutOfRange);
1524        }
1525
1526        let integer = self.round(0);
1527        let real_num = POWERS_10[(-integer.scale) as usize] * integer.int_val;
1528        if is_uppercase {
1529            if real_num.high() != 0 {
1530                write!(&mut w, "{:X}", real_num.high())?;
1531            }
1532            write!(&mut w, "{:X}", real_num.low())?;
1533        } else {
1534            if real_num.high() != 0 {
1535                write!(&mut w, "{:x}", real_num.high())?;
1536            }
1537            write!(&mut w, "{:x}", real_num.low())?;
1538        }
1539
1540        Ok(())
1541    }
1542
1543    /// Formats the decimal in the json number format, using scientific notation depending on the width.
1544    #[inline]
1545    pub fn format_to_json<W: fmt::Write>(&self, mut w: W) -> Result<(), DecimalFormatError> {
1546        if self.is_zero() {
1547            w.write_byte(b'0')?;
1548            return Ok(());
1549        }
1550
1551        const MAX_WIDTH: i16 = 40;
1552
1553        let precision = self.precision() as i16;
1554        let use_sci = if self.scale <= 0 {
1555            precision - self.scale > MAX_WIDTH
1556        } else {
1557            let mut int_val = self.int_val;
1558            let mut zero_count = 0;
1559            while int_val != 0 {
1560                if int_val % 10 != 0 {
1561                    break;
1562                }
1563                zero_count += 1;
1564                int_val /= 10;
1565            }
1566            self.scale - zero_count > MAX_WIDTH
1567        };
1568
1569        if !use_sci {
1570            return self.fmt_internal(true, false, true, None, w);
1571        }
1572
1573        let mut dec = *self;
1574        let positive_exp = precision > dec.scale;
1575        let exp = (precision - dec.scale - 1).unsigned_abs();
1576        if positive_exp {
1577            dec.scale += exp as i16;
1578            dec.fmt_internal(true, false, true, None, &mut w)?;
1579            write_exp(b"E+", exp, false, w)?;
1580        } else {
1581            dec.scale -= exp as i16;
1582            dec.fmt_internal(true, false, true, None, &mut w)?;
1583            write_exp(b"E-", exp, false, w)?;
1584        };
1585
1586        Ok(())
1587    }
1588
1589    /// Raise `self` to the power of `exponent`, where `self`
1590    /// is a decimal and `exponent` is an u64 integer,
1591    /// returning None if the result overflowed.
1592    #[inline]
1593    fn pow_u64(&self, exponent: u64) -> Option<Decimal> {
1594        match exponent {
1595            0 => Some(Decimal::ONE),
1596            1 => Some(*self),
1597            2 => self.checked_mul(self),
1598            _ => {
1599                // Here use Exponentiation by squaring to calculate x^n:
1600                // Let a + b + c + ... = n,
1601                //   x^n = x^(a + b + c + ...) = x^a * x^b * x^c * ...
1602                // Here a, b, c ... are powers of 2,
1603                // so x^a, x^b, x^c ... can be calculated by squaring x.
1604
1605                let x = *self;
1606                let mut n = exponent;
1607                let mut sum = Decimal::ONE;
1608                let mut power_x = x;
1609
1610                // Multiply once to avoid power_x greater than x^n,
1611                // so power_x will not cross the boundary first.
1612                if n & 1 == 1 {
1613                    sum = sum.checked_mul(&power_x)?;
1614                }
1615                n >>= 1;
1616
1617                while n != 0 {
1618                    power_x = power_x.checked_mul(&power_x)?;
1619                    if n & 1 == 1 {
1620                        sum = sum.checked_mul(&power_x)?;
1621                    }
1622                    n >>= 1;
1623                }
1624
1625                Some(sum)
1626            }
1627        }
1628    }
1629
1630    /// The range that Decimal can represent `self` to the power of |`exponent`|,
1631    /// where `exponent` is negative, only used in `pow_i64()` to calculate quickly.
1632    #[inline]
1633    fn pow_quick_range(&self, exponent: u64) -> bool {
1634        // 1163^42 won't overflow, 1164^42 and 1163^43 will overflow, so 1163^42 is an upper
1635        // bound, `self` to the power of -`exponent` in this range can be calculated quickly.
1636        // 125^61 won't overflow, 126^61 and 125^62 will overflow, so 125^61 is an upper
1637        // bound, `self` to the power of -`exponent` in this range can be calculated quickly.
1638        // 10^126 won't overflow, 11^126 and 10^127 will overflow, so 10^126 is an upper
1639        // bound, `self` to the power of -`exponent` in this range can be calculated quickly.
1640
1641        const BASE_UPPER_BOUND1: Decimal = unsafe { Decimal::from_parts_unchecked(1163, 0, false) };
1642        const EXP_UPPER_BOUND1: u64 = 42;
1643        const BASE_UPPER_BOUND2: Decimal = unsafe { Decimal::from_parts_unchecked(125, 0, false) };
1644        const EXP_UPPER_BOUND2: u64 = 61;
1645        const BASE_UPPER_BOUND3: Decimal = unsafe { Decimal::from_parts_unchecked(1, -1, false) };
1646        const EXP_UPPER_BOUND3: u64 = 126;
1647
1648        (exponent < EXP_UPPER_BOUND1 && *self < BASE_UPPER_BOUND1)
1649            || (exponent < EXP_UPPER_BOUND2 && *self < BASE_UPPER_BOUND2)
1650            || (exponent < EXP_UPPER_BOUND3 && *self < BASE_UPPER_BOUND3)
1651    }
1652
1653    /// Raise `self` to the power of `exponent`, where `self` is
1654    /// a decimal and `exponent` is an i64 integer, returning None
1655    /// if `self == 0` at the same time `exponent` is negative or
1656    /// the result overflowed.
1657    #[inline]
1658    fn pow_i64(&self, exponent: i64) -> Option<Decimal> {
1659        if exponent >= 0 {
1660            return self.pow_u64(exponent as u64);
1661        }
1662        // exponent is negative, example: 0^-3 is error
1663        if self.is_zero() {
1664            return None;
1665        }
1666
1667        // Here use reciprocal value to calculate x^-y:
1668        //   x^-y = 1 / x^y
1669        // Here y is positive, so can calculate x^y from `pow_u64()`.
1670
1671        let x = *self;
1672        let y = exponent.unsigned_abs();
1673
1674        // x and y in some ranges can be calculated quickly.
1675        let result = if x.pow_quick_range(y) {
1676            // x^y won't overflow, so can be calculated quickly
1677            Decimal::ONE.checked_div(&x.pow_u64(y)?)?
1678        } else {
1679            // x^y maybe overflow, so calculate x^-y with x^(y/2)
1680
1681            // if y is even,
1682            //   x^-y = 1 / x^y = 1 / x^(y/2) / x^(y/2)
1683            // if y is odd,
1684            //   x^-y = 1 / x^y = 1 / x^(y/2) / x^(y/2) / x
1685
1686            match x.pow_u64(y / 2) {
1687                Some(p) => {
1688                    let power = Decimal::ONE.checked_div(&p)?.checked_div(p)?;
1689                    if y % 2 == 1 {
1690                        power.checked_div(&x)?
1691                    } else {
1692                        power
1693                    }
1694                }
1695                // x^(y/2) is overflow, x^-y = 1 / x^(y/2) / x^(y/2) must be 0
1696                None => Decimal::ZERO,
1697            }
1698        };
1699
1700        Some(result)
1701    }
1702
1703    /// Raise `self` to the power of `exponent`, where `self`
1704    /// and `exponent` are both decimal, requires `exponent`
1705    /// is an integer, only used in `checked_pow()`.
1706    #[inline]
1707    fn pow_decimal_integral(&self, exponent: &Decimal) -> Option<Decimal> {
1708        debug_assert!((exponent.int_val == exponent.normalize().int_val) && (exponent.scale() <= 0));
1709
1710        if exponent.is_sign_negative() {
1711            // too small to calculate from pow_i64 accurately
1712            if *exponent < Decimal::from(i16::MIN) {
1713                return self.pow_decimal(exponent);
1714            }
1715
1716            self.pow_i64(-(exponent.int_val as i64))
1717        } else {
1718            // too big to calculate from pow_u64 accurately
1719            if *exponent > Decimal::from(u16::MAX) {
1720                return self.pow_decimal(exponent);
1721            }
1722
1723            self.pow_u64(exponent.int_val as u64)
1724        }
1725    }
1726
1727    /// Raise `self` to the power of `exponent`, where `self` and
1728    /// `exponent` are both decimal, only used in `checked_pow()`,
1729    /// requires `self` is positive or `exponent` is an integer,
1730    /// returning None if the result overflowed.
1731    #[inline]
1732    fn pow_decimal(&self, exponent: &Decimal) -> Option<Decimal> {
1733        debug_assert!((*self > Decimal::ZERO) || (exponent.normalize().scale() <= 0));
1734
1735        // For positive x:
1736        //   x^b = e^(b * ln(x))
1737        // If x is negative, calculate |x|^b then add a sign.
1738        // When x is negative and b is odd, x^b will be negative.
1739        // When x is negative and b is even, x^b will be positive.
1740
1741        let x = self.abs();
1742        let b = *exponent;
1743
1744        let ln = x.ln()?;
1745        let exp = ln.checked_mul(&b)?;
1746        let mut result = exp.exp()?;
1747
1748        if self.negative && b.checked_rem(&Decimal::TWO)? == Decimal::ONE {
1749            result = -result;
1750        }
1751
1752        Some(result)
1753    }
1754
1755    /// Raise `self` to the power of `exponent`, where `self` and `exponent`
1756    /// are both decimal, returning None if `self == 0` at the same time
1757    /// `exponent` is negative or `self` is negative at the same time
1758    /// `exponent` is a fraction or the result overflowed.
1759    #[inline]
1760    pub fn checked_pow(&self, exponent: &Decimal) -> Option<Decimal> {
1761        if exponent.is_zero() {
1762            return Some(Decimal::ONE);
1763        }
1764        if self.is_zero() {
1765            // exponent is negative, example: 0^-3 is error
1766            if exponent.is_sign_negative() {
1767                return None;
1768            }
1769            return Some(Decimal::ZERO);
1770        }
1771        if *self == Decimal::ONE {
1772            return Some(Decimal::ONE);
1773        }
1774        if exponent == Decimal::ONE {
1775            return Some(*self);
1776        }
1777
1778        let exponent = exponent.normalize();
1779        // exponent is an integer
1780        if exponent.scale() <= 0 {
1781            return self.pow_decimal_integral(&exponent);
1782        }
1783
1784        // base is negative and exponent is a fraction, example: (-3)^2.2 is error
1785        if self.is_sign_negative() {
1786            return None;
1787        }
1788
1789        // Let n = a + b:
1790        //   x^n = x^(a + b) = x^a * x^b,
1791        // where a is the integer part of n and b is the fraction part of n.
1792        // a is an integer and b is a fraction in range (-1, 1),
1793        // so calculate x^a and x^b is faster and more accurate.
1794
1795        let x = *self;
1796        let n = exponent;
1797
1798        let a = n.trunc(0);
1799        let b = n.checked_sub(&a)?;
1800
1801        let power_a = x.pow_decimal_integral(&a)?;
1802        let power_b = x.pow_decimal(&b)?;
1803
1804        // x^n = x^(a + b) = x^a * x^b
1805        let result = power_a.checked_mul(&power_b)?;
1806
1807        Some(result)
1808    }
1809
1810    /// Computes the natural logarithm of `self`,
1811    /// returning None if `self` is negative or `self == 0`.
1812    #[inline]
1813    pub fn ln(&self) -> Option<Decimal> {
1814        const ZERO_POINT_ONE: Decimal = unsafe { Decimal::from_parts_unchecked(1, 1, false) };
1815        const ONE_POINT_ONE: Decimal = unsafe { Decimal::from_parts_unchecked(11, 1, false) };
1816        const TEN: Decimal = unsafe { Decimal::from_parts_unchecked(10, 0, false) };
1817        const LOWER_BOUND: Decimal = unsafe { Decimal::from_parts_unchecked(9047, 4, false) };
1818        // 1.2217
1819        const R: Decimal = unsafe { Decimal::from_parts_unchecked(12217, 4, false) };
1820        const LN_10: Decimal =
1821            unsafe { Decimal::from_parts_unchecked(23025850929940456840179914546843642076, 37, false) };
1822        // ln(1.2217)
1823        const LN_R: Decimal =
1824            unsafe { Decimal::from_parts_unchecked(2002433314278771112016301166984297937, 37, false) };
1825
1826        // ln(x) requires x > 0
1827        if self.is_sign_negative() || self.is_zero() {
1828            return None;
1829        }
1830
1831        if *self == Decimal::ONE {
1832            return Some(Decimal::ZERO);
1833        }
1834
1835        // Taylor series:
1836        //   ln(x) = ln((1 + y) / (1 - y)) = 2(y + y^3/3 + y^5/5 + y^7 / 7 + ...)
1837        // The Taylor series converges fast as y approaches 0.
1838        //
1839        // ln(x) = ln(x / 10^n1 * 10^n1) = ln(x / 10^n1) + n1 * ln(10),
1840        // ln(x / 10^n1) = ln(x / 10^n1 / R^n2 * R^n2) = ln(x / 10^n1 / R^n2) + n2 * ln(R),
1841        // let z = x / 10^n1 / R^n2, then ln(x) = ln(z) + n1 * ln(10) + n2 * ln(R)
1842        //
1843        // Here use Taylor series to calculate ln(z).
1844        // let z = (1 + y)/(1 - y), for requires y in (-0.05, 0.05)(this range approaches 0),
1845        // lower bound of z is (1 + -0.05) / (1 - -0.05) = 0.9047,
1846        // upper bound of z is (1 + 0.05) / (1 - 0.05) = 1.10526,
1847        // so need reduce x into z in range [0.9047, 1.10526),
1848        // R = 1.10526 / 0.9047 = 1.2217.
1849
1850        let mut x = *self;
1851        let mut n1 = 0;
1852        let mut n2 = 0;
1853
1854        // reduce x into (0.1, 1.1]
1855        while x > ONE_POINT_ONE {
1856            x = x.checked_mul(&ZERO_POINT_ONE)?;
1857            n1 += 1;
1858        }
1859        while x <= ZERO_POINT_ONE {
1860            x = x.checked_mul(&TEN)?;
1861            n1 -= 1;
1862        }
1863
1864        // reduce x into [0.9047, 1.10526)
1865        while x < LOWER_BOUND {
1866            x = x.checked_mul(&R)?;
1867            n2 -= 1;
1868        }
1869
1870        // z = (1 + y)/(1 - y), then y = (z - 1)/(z + 1)
1871        let z = x;
1872        let y = z
1873            .checked_sub(&Decimal::ONE)?
1874            .checked_div(&z.checked_add(&Decimal::ONE)?)?;
1875        let y_square = y.checked_mul(&y)?;
1876
1877        // ln(z) = ln((1 + y)/(1 - y)) = 2 * (y + y^3 / 3 + y^5 / 5 + y^7 / 7 + ...)
1878        let mut sum = y;
1879        let mut power_y = y;
1880        let mut last;
1881        let mut iter = 1;
1882
1883        loop {
1884            iter += 2;
1885            power_y = power_y.checked_mul(&y_square)?;
1886            let term = power_y.checked_div(&Decimal::from(iter))?;
1887
1888            if term.is_zero() {
1889                break;
1890            }
1891
1892            last = sum;
1893            sum = sum.checked_add(&term)?;
1894
1895            if last == sum {
1896                break;
1897            }
1898        }
1899
1900        let ln_z = sum.checked_mul(&Decimal::TWO)?;
1901
1902        // ln(x) = ln(z) + n1 * ln(10) + n2 * ln(R).
1903        let mut result = ln_z.checked_add(&LN_10.checked_mul(&Decimal::from(n1))?)?;
1904        result = result.checked_add(&LN_R.checked_mul(&Decimal::from(n2))?)?;
1905        Some(result)
1906    }
1907
1908    /// Computes the nature exponential of `self`,
1909    /// calculate with Taylor series, returning
1910    /// None if the result overflowed.
1911    #[inline]
1912    fn exp_decimal(&self) -> Option<Decimal> {
1913        // Taylor series:
1914        //   e^x = 1 + x + x^2 / 2! + x^3 / 3! + x^4 / 4! + ...
1915        // Here use Taylor series to calculate e^x,
1916        // start with the third term.
1917
1918        let x = *self;
1919        let mut term = x;
1920        let mut sum = Decimal::ONE.checked_add(&x)?;
1921        let mut last;
1922        let mut iter = 1;
1923        loop {
1924            iter += 1;
1925
1926            // Calculate latter term from former term by multiplying x over iter,
1927            // Divide first then multiply to avoid the intermediate process to cross the boundary.
1928            term = term.checked_div(&Decimal::from(iter))?.checked_mul(&x)?;
1929
1930            if term.is_zero() {
1931                break;
1932            }
1933
1934            last = sum;
1935            sum = sum.checked_add(&term)?;
1936
1937            if last == sum {
1938                break;
1939            }
1940        }
1941
1942        Some(sum)
1943    }
1944
1945    /// Computes the nature exponential of `self`,
1946    /// returning None if the result overflowed.
1947    #[inline]
1948    pub fn exp(&self) -> Option<Decimal> {
1949        // same as Oracle: e^291 will overflow, e^-300 is 0
1950        const UPPER_BOUND: Decimal = unsafe { Decimal::from_parts_unchecked(291, 0, false) };
1951        const LOWER_BOUND: Decimal = unsafe { Decimal::from_parts_unchecked(300, 0, true) };
1952
1953        if self.is_zero() {
1954            return Some(Decimal::ONE);
1955        }
1956        if *self >= UPPER_BOUND {
1957            // overflow
1958            return None;
1959        }
1960        if *self <= LOWER_BOUND {
1961            return Some(Decimal::ZERO);
1962        }
1963
1964        // Taylor series:
1965        //   e^x = 1 + x + x^2 / 2! + x^3 / 3! + x^4 / 4! + ...
1966        // The Taylor series converges faster as input approaches 0,
1967        //
1968        // Let x = a + b:
1969        //   e^x = e^(a + b) = e^a * e^b,
1970        // where a is the integer part of x and b is the fraction part of x,
1971        // to reduce input into range -1 < b < 1 by getting rid of the integer part of x.
1972        //
1973        // Here use look-up table to get e^a,
1974        // calculate e^a in advance when testing by using Taylor series,
1975        // put it into array `NATURAL_EXP` and `NATURAL_EXP_NEG`.
1976        //
1977        // Here use Taylor series to calculate e^b,
1978        // b is the fraction part of x, so b is in (-1, 1)(this range approaches 0).
1979
1980        let x = *self;
1981        let a = x.trunc(0);
1982        let b = x.checked_sub(&a)?;
1983
1984        let exp_a = if a.is_sign_positive() {
1985            NATURAL_EXP[a.int_val as usize]
1986        } else if a.int_val < UPPER_BOUND.int_val {
1987            // e^|a| won't overflow
1988            Decimal::ONE.checked_div(&NATURAL_EXP[a.int_val as usize])?
1989        } else {
1990            // e^|a| will overflow
1991            NATURAL_EXP_NEG[(a.int_val - UPPER_BOUND.int_val) as usize]
1992        };
1993
1994        let exp_b = if b.is_zero() {
1995            // e^0 = 1, so e^x = e^a.
1996            return Some(exp_a);
1997        } else {
1998            b.exp_decimal()?
1999        };
2000
2001        // e^x = e^(a + b) = e^a * e^b
2002        let result = exp_a.checked_mul(&exp_b)?;
2003
2004        Some(result)
2005    }
2006}
2007
2008trait WriteExt: fmt::Write {
2009    #[inline(always)]
2010    fn write_byte(&mut self, byte: u8) -> fmt::Result {
2011        self.write_bytes(&[byte])
2012    }
2013
2014    #[inline(always)]
2015    fn write_bytes(&mut self, bytes: &[u8]) -> fmt::Result {
2016        let s = unsafe { std::str::from_utf8_unchecked(bytes) };
2017        self.write_str(s)
2018    }
2019}
2020
2021impl<W: fmt::Write> WriteExt for W {}
2022
2023#[inline]
2024fn write_exp<W: fmt::Write>(
2025    e_notation: &[u8],
2026    exp: u16,
2027    add_left_padding_zero: bool,
2028    mut w: W,
2029) -> Result<(), DecimalFormatError> {
2030    w.write_bytes(e_notation)?;
2031
2032    // Creates a temp array to save exp str
2033    let mut buf = [b'0'; 3];
2034    let mut index = 2;
2035
2036    let mut val = exp;
2037    while val >= 10 {
2038        let v = val % 10;
2039        val /= 10;
2040        buf[index] += v as u8;
2041        index -= 1;
2042    }
2043    buf[index] += val as u8;
2044
2045    // Adds zero if exponent number doesn't have two digits
2046    if index == 2 && add_left_padding_zero {
2047        index -= 1;
2048    }
2049
2050    w.write_bytes(&buf[index..])?;
2051    Ok(())
2052}
2053
2054impl AsRef<Decimal> for Decimal {
2055    #[inline]
2056    fn as_ref(&self) -> &Decimal {
2057        self
2058    }
2059}
2060
2061impl fmt::Display for Decimal {
2062    #[inline]
2063    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2064        let mut buf = Buf::new();
2065        self.fmt_internal(false, false, false, f.precision(), &mut buf)
2066            .expect("failed to format decimal");
2067        let str = unsafe { std::str::from_utf8_unchecked(buf.as_slice()) };
2068        f.pad_integral(self.is_sign_positive(), "", str)
2069    }
2070}
2071
2072impl Default for Decimal {
2073    #[inline]
2074    fn default() -> Self {
2075        Decimal::ZERO
2076    }
2077}
2078
2079impl PartialEq for Decimal {
2080    #[inline]
2081    fn eq(&self, other: &Self) -> bool {
2082        self.cmp(other) == Ordering::Equal
2083    }
2084}
2085
2086impl PartialEq<&Decimal> for Decimal {
2087    #[inline]
2088    fn eq(&self, other: &&Decimal) -> bool {
2089        self.eq(*other)
2090    }
2091}
2092
2093impl PartialEq<Decimal> for &Decimal {
2094    #[inline]
2095    fn eq(&self, other: &Decimal) -> bool {
2096        (*self).eq(other)
2097    }
2098}
2099
2100impl PartialOrd for Decimal {
2101    #[inline]
2102    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2103        Some(self.cmp(other))
2104    }
2105}
2106
2107impl PartialOrd<&Decimal> for Decimal {
2108    #[inline]
2109    fn partial_cmp(&self, other: &&Decimal) -> Option<Ordering> {
2110        self.partial_cmp(*other)
2111    }
2112}
2113
2114impl PartialOrd<Decimal> for &Decimal {
2115    #[inline]
2116    fn partial_cmp(&self, other: &Decimal) -> Option<Ordering> {
2117        (*self).partial_cmp(other)
2118    }
2119}
2120
2121impl Ord for Decimal {
2122    #[inline]
2123    fn cmp(&self, other: &Self) -> Ordering {
2124        // sign is different
2125        if self.negative != other.negative {
2126            return if self.negative {
2127                Ordering::Less
2128            } else {
2129                Ordering::Greater
2130            };
2131        }
2132
2133        let (left, right) = if self.negative {
2134            // both are negative, so reverse cmp
2135            debug_assert!(other.negative);
2136            (other, self)
2137        } else {
2138            (self, other)
2139        };
2140
2141        if left.is_zero() {
2142            return if right.is_zero() {
2143                Ordering::Equal
2144            } else {
2145                Ordering::Less
2146            };
2147        } else if right.is_zero() {
2148            return Ordering::Greater;
2149        }
2150
2151        if left.scale == right.scale {
2152            // fast path for same scale
2153            return left.int_val().cmp(&right.int_val());
2154        }
2155
2156        if left.scale < right.scale {
2157            left.rescale_cmp(right)
2158        } else {
2159            right.rescale_cmp(left).reverse()
2160        }
2161    }
2162}
2163
2164impl Hash for Decimal {
2165    #[inline]
2166    fn hash<H: Hasher>(&self, state: &mut H) {
2167        let n = self.normalize();
2168        n.int_val().hash(state);
2169        n.scale.hash(state);
2170        n.negative.hash(state);
2171    }
2172}
2173
2174#[cfg(test)]
2175mod tests {
2176    use super::*;
2177
2178    #[test]
2179    fn test_decimal_repr() {
2180        assert_eq!(std::mem::size_of::<Decimal>(), 20);
2181        assert_eq!(std::mem::align_of::<Decimal>(), 4);
2182    }
2183
2184    #[test]
2185    fn test_fmt_internal() {
2186        fn assert(
2187            int_val: u128,
2188            scale: i16,
2189            negative: bool,
2190            append_sign: bool,
2191            precision: Option<usize>,
2192            expected: &str,
2193        ) {
2194            let dec = Decimal::from_parts(int_val, scale, negative).unwrap();
2195            let mut buf = Buf::new();
2196            dec.fmt_internal(append_sign, false, false, precision, &mut buf)
2197                .unwrap();
2198            let str = unsafe { std::str::from_utf8_unchecked(buf.as_slice()) };
2199            assert_eq!(str, expected);
2200        }
2201
2202        assert(128, 0, false, false, None, "128");
2203        assert(128, -2, true, true, None, "-12800");
2204        assert(128, 4, true, true, None, "-0.0128");
2205        assert(128, 2, true, false, None, "1.28");
2206        assert(1280, 4, true, true, None, "-0.1280");
2207        assert(12856, 4, true, false, None, "1.2856");
2208        assert(12856, 4, true, false, Some(2), "1.29");
2209        assert(12856, 4, true, false, Some(6), "1.285600");
2210        assert(1285600, 6, false, false, None, "1.2856");
2211    }
2212
2213    #[test]
2214    fn test_display() {
2215        macro_rules! assert_display {
2216            ($num: expr, $scale: expr, $negative: expr, $fmt: expr,$expected: expr) => {{
2217                let dec = Decimal::from_parts($num, $scale, $negative).unwrap();
2218                let str = format!($fmt, dec);
2219                assert_eq!(str, $expected);
2220            }};
2221        }
2222
2223        assert_display!(0, -1, false, "{}", "0");
2224        assert_display!(1, 0, false, "{}", "1");
2225        assert_display!(1, 1, false, "{}", "0.1");
2226        assert_display!(1, -1, false, "{}", "10");
2227        assert_display!(10, 0, false, "{}", "10");
2228        assert_display!(10, 1, false, "{}", "1");
2229        assert_display!(10, -1, false, "{}", "100");
2230        assert_display!(128, 0, false, "{}", "128");
2231        assert_display!(128, -2, true, "{}", "-12800");
2232        assert_display!(128, 4, true, "{}", "-0.0128");
2233        assert_display!(128, 2, true, "{}", "-1.28");
2234        assert_display!(12800, 1, false, "{}", "1280");
2235        assert_display!(12800, 2, false, "{}", "128");
2236        assert_display!(12800, 3, false, "{}", "12.8");
2237        assert_display!(12856, 4, true, "{}", "-1.2856");
2238        assert_display!(12856, 4, true, "{:.2}", "-1.29");
2239        assert_display!(12856, 4, true, "{:.6}", "-1.285600");
2240        assert_display!(12856, 0, true, "{:.6}", "-12856.000000");
2241        assert_display!(1285600, 6, false, "{}", "1.2856");
2242        assert_display!(u64::MAX as u128, 0, false, "{}", u64::MAX.to_string());
2243        assert_display!(101, -98, false, "{:.10}", "10100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0000000000");
2244        assert_display!(101, 98, false, "{:.10}", "0.0000000000");
2245    }
2246
2247    #[test]
2248    fn test_precision() {
2249        fn assert_precision(val: &str, expected: u8) {
2250            let dec = val.parse::<Decimal>().unwrap();
2251            assert_eq!(dec.precision(), expected);
2252        }
2253
2254        assert_precision("0.0", 1);
2255        assert_precision("1", 1);
2256        assert_precision("10", 2);
2257        assert_precision("1.230", 3);
2258        assert_precision("123456123456", 12);
2259        assert_precision("123456.123456", 12);
2260        assert_precision("-123456.123456", 12);
2261        assert_precision("99999999999999999999999999999999999999", 38);
2262    }
2263
2264    #[test]
2265    fn test_encoding() {
2266        fn assert_encoding(num: &str) {
2267            let num = num.parse::<Decimal>().unwrap();
2268            let mut buf = Vec::new();
2269
2270            // Compact encode
2271            {
2272                let size = num.compact_encode(&mut buf).unwrap();
2273                assert_eq!(buf.len(), size);
2274                let decoded_num = Decimal::decode(&buf);
2275                assert_eq!(decoded_num, num);
2276            }
2277
2278            buf.clear();
2279
2280            // Encode
2281            {
2282                let size = num.encode(&mut buf).unwrap();
2283                assert_eq!(buf.len(), size);
2284                let decoded_num = Decimal::decode(&buf);
2285                assert_eq!(decoded_num, num);
2286            }
2287        }
2288
2289        assert_encoding("0");
2290        assert_encoding("255");
2291        assert_encoding("-255");
2292        assert_encoding("65535");
2293        assert_encoding("-65535");
2294        assert_encoding("65536");
2295        assert_encoding("4294967295");
2296        assert_encoding("-4294967295");
2297        assert_encoding("4294967296");
2298        assert_encoding("18446744073709551615");
2299        assert_encoding("-18446744073709551615");
2300        assert_encoding("18446744073709551616");
2301        assert_encoding("99999999999999999999999999999999999999");
2302        assert_encoding("-99999999999999999999999999999999999999");
2303        assert_encoding("184467440.73709551615");
2304        assert_encoding("-184467440.73709551615");
2305    }
2306
2307    #[test]
2308    fn test_cmp() {
2309        macro_rules! assert_cmp {
2310            ($left: expr, $cmp: tt, $right: expr) => {{
2311                let l = $left.parse::<Decimal>().unwrap();
2312                let r = $right.parse::<Decimal>().unwrap();
2313                assert!(l $cmp r, "{} {} {}", l, stringify!($cmp),r);
2314            }};
2315        }
2316
2317        assert_cmp!("0", ==, "0");
2318
2319        assert_cmp!("-1", <, "1");
2320        assert_cmp!("1", >, "-1");
2321
2322        assert_cmp!("1.1", ==, "1.1");
2323        assert_cmp!("1.2", >, "1.1");
2324        assert_cmp!("-1.2", <, "1.1");
2325        assert_cmp!("1.1", >, "-1.2");
2326
2327        assert_cmp!("1", <, "1e39");
2328        assert_cmp!("1", >, "1e-39");
2329        assert_cmp!("1.0e-100", >=, "1.0e-101");
2330        assert_cmp!("1.0e-101", <=, "1.0e-100");
2331        assert_cmp!("1.0e-100", !=, "1.0e-101");
2332
2333        assert_cmp!("1.12", <, "1.2");
2334        assert_cmp!("1.2", >, "1.12");
2335        assert_cmp!("-1.2", <, "-1.12");
2336        assert_cmp!("-1.12", >, "-1.2");
2337        assert_cmp!("-1.12", <, "1.2");
2338        assert_cmp!("1.12", >, "-1.2");
2339
2340        assert_cmp!("0.000000001", <,"100000000");
2341        assert_cmp!("100000000", >, "0.000000001");
2342
2343        assert_cmp!(
2344            "9999999999999999999999999999999999999.9", >, "9.9999999999999999999999999999999999999"
2345        );
2346        assert_cmp!(
2347            "9.9999999999999999999999999999999999999", >, "0"
2348        );
2349        assert_cmp!(
2350            "9.9999999999999999999999999999999999999", >, "1"
2351        );
2352        assert_cmp!(
2353            "-9999999999999999999999999999999999999.9", <, "-9.9999999999999999999999999999999999999"
2354        );
2355        assert_cmp!(
2356            "-9.9999999999999999999999999999999999999", <, "0"
2357        );
2358        assert_cmp!(
2359            "-9.9999999999999999999999999999999999999", <, "1"
2360        );
2361        assert_cmp!("4703178999618078116505370421100e39", >, "0");
2362        assert_cmp!("4703178999618078116505370421100e-39", >, "0");
2363        assert_cmp!("-4703178999618078116505370421100e39", <, "0");
2364        assert_cmp!("-4703178999618078116505370421100e-39", <, "0");
2365        assert_cmp!("0", <, "4703178999618078116505370421100e39");
2366        assert_cmp!("0", <, "4703178999618078116505370421100e-39");
2367        assert_cmp!("0", >, "-4703178999618078116505370421100e39");
2368        assert_cmp!("0", >, "-4703178999618078116505370421100e-39");
2369    }
2370
2371    #[test]
2372    fn test_abs() {
2373        fn assert_abs(val: &str, expected: &str) {
2374            let abs_val = val.parse::<Decimal>().unwrap().abs();
2375            let expected = expected.parse::<Decimal>().unwrap();
2376            assert_eq!(abs_val, expected);
2377        }
2378
2379        assert_abs("0.0", "0");
2380        assert_abs("123456.123456", "123456.123456");
2381        assert_abs("-123456.123456", "123456.123456");
2382    }
2383
2384    #[test]
2385    fn test_trunc() {
2386        fn assert_trunc(val: &str, scale: i16, expected: &str) {
2387            let decimal = val.parse::<Decimal>().unwrap().trunc(scale);
2388            let expected = expected.parse::<Decimal>().unwrap();
2389            assert_eq!(decimal, expected);
2390        }
2391
2392        assert_trunc("0", -1, "0");
2393        assert_trunc("123456", 0, "123456");
2394        assert_trunc("123456.123456", 6, "123456.123456");
2395        assert_trunc("123456.123456", 5, "123456.12345");
2396        assert_trunc("123456.123456", 4, "123456.1234");
2397        assert_trunc("123456.123456", 3, "123456.123");
2398        assert_trunc("123456.123456", 2, "123456.12");
2399        assert_trunc("123456.123456", 1, "123456.1");
2400        assert_trunc("123456.123456", 0, "123456");
2401        assert_trunc("123456.123456", -1, "123450");
2402        assert_trunc("123456.123456", -2, "123400");
2403        assert_trunc("123456.123456", -3, "123000");
2404        assert_trunc("123456.123456", -4, "120000");
2405        assert_trunc("123456.123456", -5, "100000");
2406        assert_trunc("9999.9", 1, "9999.9");
2407        assert_trunc("9999.9", -2, "9900");
2408        assert_trunc("9999.9", -4, "0");
2409        assert_trunc("1e125", 0, "1e125");
2410        assert_trunc("1e125", -125, "1e125");
2411        assert_trunc("1e-130", 0, "0");
2412        assert_trunc("1.7976931348623279769313486232797693134E-130", 131, "1.7E-130");
2413        assert_trunc(
2414            "1.7976931348623279769313486232797693134E-130",
2415            166,
2416            "1.797693134862327976931348623279769313E-130",
2417        );
2418        assert_trunc(
2419            "1.7976931348623279769313486232797693134E-130",
2420            167,
2421            "1.7976931348623279769313486232797693134E-130",
2422        );
2423        assert_trunc(
2424            "1.7976931348623279769313486232797693134E-130",
2425            168,
2426            "1.7976931348623279769313486232797693134E-130",
2427        );
2428    }
2429
2430    #[test]
2431    fn test_round() {
2432        fn assert_round(val: &str, scale: i16, expected: &str) {
2433            let decimal = val.parse::<Decimal>().unwrap().round(scale);
2434            let expected = expected.parse::<Decimal>().unwrap();
2435            assert_eq!(decimal, expected);
2436        }
2437
2438        assert_round("0", -1, "0");
2439        assert_round("123456", 0, "123456");
2440        assert_round("123456.123456", 6, "123456.123456");
2441        assert_round("123456.123456", 5, "123456.12346");
2442        assert_round("123456.123456", 4, "123456.1235");
2443        assert_round("123456.123456", 3, "123456.123");
2444        assert_round("123456.123456", 2, "123456.12");
2445        assert_round("123456.123456", 1, "123456.1");
2446        assert_round("123456.123456", 0, "123456");
2447        assert_round("123456.123456", -1, "123460");
2448        assert_round("123456.123456", -2, "123500");
2449        assert_round("123456.123456", -3, "123000");
2450        assert_round("123456.123456", -4, "120000");
2451        assert_round("123456.123456", -5, "100000");
2452        assert_round("9999.9", 1, "9999.9");
2453        assert_round("9999.9", -2, "10000");
2454        assert_round("9999.9", -4, "10000");
2455        assert_round("1.7976931348623279769313486232797693134E-130", 131, "1.8E-130");
2456        assert_round(
2457            "1.7976931348623279769313486232797693134E-130",
2458            166,
2459            "1.797693134862327976931348623279769313E-130",
2460        );
2461        assert_round(
2462            "1.7976931348623279769313486232797693134E-130",
2463            167,
2464            "1.7976931348623279769313486232797693134E-130",
2465        );
2466        assert_round(
2467            "1.7976931348623279769313486232797693134E-130",
2468            168,
2469            "1.7976931348623279769313486232797693134E-130",
2470        );
2471    }
2472
2473    #[test]
2474    fn test_round_with_precision() {
2475        fn assert(val: &str, precision: u8, scale: i16, expected: &str) {
2476            let mut decimal = val.parse::<Decimal>().unwrap();
2477            let overflowed = decimal.round_with_precision(precision, scale);
2478            assert!(!overflowed);
2479            let expected = expected.parse::<Decimal>().unwrap();
2480            assert_eq!(decimal, expected);
2481        }
2482
2483        fn assert_overflow(val: &str, precision: u8, scale: i16) {
2484            let mut decimal = val.parse::<Decimal>().unwrap();
2485            let overflowed = decimal.round_with_precision(precision, scale);
2486            assert!(overflowed);
2487        }
2488
2489        assert_overflow("123456", 5, 0);
2490        assert_overflow("123456", 5, 1);
2491        assert_overflow("123456", 6, 1);
2492        assert_overflow("123.456", 6, 4);
2493        assert_overflow("5e100", 5, -2);
2494        assert_overflow("5e100", 20, -80);
2495
2496        assert("123456", 5, -1, "123460");
2497        assert("123456", 5, -5, "100000");
2498        assert("123456", 5, -6, "0");
2499        assert("123456", 6, 0, "123456");
2500        assert("123456", 6, -1, "123460");
2501        assert("123.456", 6, 0, "123");
2502        assert("123.456", 6, 1, "123.5");
2503        assert("123.456", 6, 3, "123.456");
2504        assert("123.456", 6, -1, "120");
2505        assert("123.456", 6, -2, "100");
2506        assert("123.456", 6, -3, "0");
2507        assert("623.456", 6, -3, "1000");
2508        assert("123.456", 6, -4, "0");
2509        assert("123.456", 5, -4, "0");
2510        assert("123.456", 5, -3, "0");
2511        assert("123.456", 5, -2, "100");
2512        assert("123456", 5, -5, "100000");
2513        assert("123456", 5, -6, "0");
2514        assert("123456", 5, -7, "0");
2515        assert("5e100", 21, -80, "5e100");
2516        assert("5E-130", 10, 5, "0");
2517        assert("5E-47", 1, 10, "0");
2518        assert("-1E-130", 38, 10, "0");
2519        assert("0.000811111", 5, 3, "0.001");
2520    }
2521
2522    #[test]
2523    fn test_normalize_to() {
2524        fn assert_normalize(val: (u128, i16), scale: i16, expected: (u128, i16)) {
2525            let left = Decimal::from_parts(val.0, val.1, false).unwrap();
2526            let right = Decimal::from_parts(expected.0, expected.1, false).unwrap();
2527            assert_eq!(left, right);
2528            let normal = left.normalize_to_scale(scale);
2529            assert_eq!((normal.int_val, normal.scale), expected);
2530        }
2531
2532        assert_normalize((12300, MAX_SCALE), 2, (123, MAX_SCALE - 2));
2533        assert_normalize((12300, 2), 2, (12300, 2));
2534        assert_normalize((12300, 2), 3, (123000, 3));
2535        assert_normalize((12300, 2), 0, (123, 0));
2536        assert_normalize((12300, 2), -1, (123, 0));
2537        assert_normalize((123000, 2), -1, (123, -1));
2538        assert_normalize(
2539            (9_9999_9999_9999_9999_9999_9999_9999_9999_9999_u128, -2),
2540            2,
2541            (99_9999_9999_9999_9999_9999_9999_9999_9999_9990_u128, -1),
2542        );
2543        assert_normalize((12300, MIN_SCALE + 1), -100, (123000000000000000000000000000, -100));
2544    }
2545
2546    #[test]
2547    fn test_normalize() {
2548        fn assert_normalize(val: (u128, i16), expected: (u128, i16)) {
2549            let left = Decimal::from_parts(val.0, val.1, false).unwrap();
2550            let right = Decimal::from_parts(expected.0, expected.1, false).unwrap();
2551            assert_eq!(left, right);
2552            let normal = left.normalize();
2553            assert_eq!((normal.int_val, normal.scale), expected);
2554        }
2555
2556        assert_normalize((12300, MAX_SCALE), (123, MAX_SCALE - 2));
2557        assert_normalize((12300, 2), (123, 0));
2558        assert_normalize((1230, 0), (1230, 0));
2559        assert_normalize((12300, -2), (1230000, 0));
2560        assert_normalize(
2561            (9_9999_9999_9999_9999_9999_9999_9999_9999_9999_u128, -2),
2562            (99_9999_9999_9999_9999_9999_9999_9999_9999_9990_u128, -1),
2563        );
2564        assert_normalize((12300, MIN_SCALE + 1), (12300000000000000000000000000000000000, -92));
2565    }
2566
2567    #[test]
2568    fn test_hash() {
2569        use std::collections::hash_map::DefaultHasher;
2570
2571        let d1 = Decimal::from_parts(12345, 3, false).unwrap();
2572        let d2 = Decimal::from_parts(123450, 4, false).unwrap();
2573
2574        let mut hash1 = DefaultHasher::new();
2575        let mut hash2 = DefaultHasher::new();
2576
2577        d1.hash(&mut hash1);
2578        d2.hash(&mut hash2);
2579
2580        assert_eq!(hash1.finish(), hash2.finish());
2581    }
2582
2583    #[test]
2584    fn test_sqrt() {
2585        fn assert_sqrt(val: &str, expected: &str) {
2586            let num = val.parse::<Decimal>().unwrap();
2587            let expected = expected.parse::<Decimal>().unwrap();
2588            let result = num.sqrt().unwrap();
2589            assert_eq!(result, expected);
2590        }
2591
2592        assert_sqrt("0", "0");
2593        assert_sqrt("0.00000", "0");
2594        assert_sqrt("1", "1");
2595        assert_sqrt("1.001", "1.0004998750624609648232582877001097531");
2596        assert_sqrt("1.44", "1.2");
2597        assert_sqrt("2", "1.4142135623730950488016887242096980786");
2598        assert_sqrt("100", "10");
2599        assert_sqrt("49", "7");
2600        assert_sqrt("0.25", "0.5");
2601        assert_sqrt("0.0152399025", "0.12345");
2602        assert_sqrt("152399025", "12345");
2603        assert_sqrt("0.00400", "0.063245553203367586639977870888654370675");
2604        assert_sqrt("0.1", "0.31622776601683793319988935444327185337");
2605        assert_sqrt("2", "1.4142135623730950488016887242096980786");
2606        assert_sqrt("125348", "354.04519485512015631084871931761013143");
2607        assert_sqrt(
2608            "18446744073709551616.1099511",
2609            "4294967296.0000000000127999926917254925",
2610        );
2611        assert_sqrt(
2612            "3.1415926535897931159979634685441851615",
2613            "1.7724538509055159927515191031392484393",
2614        );
2615        assert_sqrt(
2616            "0.000000000089793115997963468544185161590576171875",
2617            "0.0000094759229628550415175617837401442254225",
2618        );
2619        assert_sqrt(
2620            "0.71777001097629639227453423431674136248",
2621            "0.84721308475276536670429805177990207040",
2622        );
2623        assert_sqrt(
2624            "0.012345679012345679012345679012345679012",
2625            "0.11111111111111111111111111111111111111",
2626        );
2627        assert_sqrt(
2628            "0.11088900000000000000000000000000000444",
2629            "0.33300000000000000000000000000000000667",
2630        );
2631        assert_sqrt(
2632            "17014118346046923173168730371588410572",
2633            "4124817371235594858.7903221175243613899",
2634        );
2635        assert_sqrt(
2636            "0.17014118346046923173168730371588410572",
2637            "0.41248173712355948587903221175243613899",
2638        );
2639        assert_sqrt("1e100", "1e50");
2640        assert_sqrt("1.01e100", "1.0049875621120890270219264912759576187e50");
2641        assert_sqrt("1e-100", "1e-50");
2642        assert_sqrt("1.01e-100", "1.0049875621120890270219264912759576187e-50");
2643        assert_sqrt("1.0e-130", "1.0e-65");
2644    }
2645
2646    #[test]
2647    fn test_ceil_floor() {
2648        fn assert_ceil_floor(val: &str, expected_ceil: &str, expected_floor: &str) {
2649            let decimal_ceil = val.parse::<Decimal>().unwrap().ceil();
2650            let decimal_floor = val.parse::<Decimal>().unwrap().floor();
2651            let expected_ceil = expected_ceil.parse::<Decimal>().unwrap();
2652            let expected_floor = expected_floor.parse::<Decimal>().unwrap();
2653            assert_eq!(decimal_ceil, expected_ceil);
2654            assert_eq!(decimal_floor, expected_floor);
2655        }
2656
2657        assert_ceil_floor("0", "0", "0");
2658        assert_ceil_floor("123456", "123456", "123456");
2659        assert_ceil_floor("12345600", "12345600", "12345600");
2660        assert_ceil_floor("-12345600", "-12345600", "-12345600");
2661        assert_ceil_floor("123456.123456", "123457", "123456");
2662        assert_ceil_floor("-123456.123456", "-123456", "-123457");
2663        assert_ceil_floor("0.00123456", "1", "0");
2664        assert_ceil_floor("-0.00123456", "0", "-1");
2665        assert_ceil_floor("1e100", "1e100", "1e100");
2666        assert_ceil_floor("1e-100", "1", "0");
2667        assert_ceil_floor("-1e100", "-1e100", "-1e100");
2668        assert_ceil_floor("-1e-100", "0", "-1");
2669        assert_ceil_floor("100e-2", "1", "1");
2670        assert_ceil_floor("-100e-2", "-1", "-1");
2671    }
2672
2673    #[test]
2674    fn test_simply_format() {
2675        fn assert_fmt(input: &str, expected: &str) {
2676            let mut s = String::with_capacity(256);
2677            let num = input.parse::<Decimal>().unwrap();
2678            num.simply_format(&mut s).unwrap();
2679            assert_eq!(s.as_str(), expected);
2680        }
2681
2682        assert_fmt("0", "0");
2683        assert_fmt("0.6796000", ".6796");
2684        assert_fmt("0.6796", ".6796");
2685        assert_fmt("-0.6796", "-.6796");
2686        assert_fmt("123456789.123456789", "123456789.123456789");
2687        assert_fmt("+123456789.123456789", "123456789.123456789");
2688        assert_fmt("-123456789.123456789", "-123456789.123456789");
2689    }
2690
2691    #[test]
2692    fn test_format_with_sci() {
2693        fn assert_fmt(input: &str, target_len: u16, expected: &str) {
2694            let mut s = String::with_capacity(256);
2695            let num = input.parse::<Decimal>().unwrap();
2696            num.format_with_sci(target_len, &mut s).unwrap();
2697            assert_eq!(s.as_str(), expected);
2698        }
2699
2700        fn assert_error(input: &str, target_len: u16) {
2701            let mut s = String::with_capacity(256);
2702            let num = input.parse::<Decimal>().unwrap();
2703            assert!(num.format_with_sci(target_len, &mut s).is_err());
2704        }
2705
2706        // Cannot truncates when target_len is smaller than scientific notation length
2707        assert_fmt("0", 1, "0");
2708        assert_fmt("0", 5, "0");
2709        assert_fmt("6", 1, "6");
2710        assert_fmt("6", 5, "6");
2711        assert_error("10", 1);
2712        assert_fmt("10", 2, "10");
2713        assert_fmt("10", 5, "10");
2714        assert_error("100", 2);
2715        assert_fmt("100", 3, "100");
2716        assert_fmt("100", 5, "100");
2717        assert_fmt("-236.23", 20, "-236.23");
2718        assert_fmt("-236.23", 7, "-236.23");
2719
2720        // Keeps zero ending
2721        assert_fmt("1000000000", 10, "1000000000");
2722        assert_fmt("-1000000000", 11, "-1000000000");
2723        assert_fmt("1000000000", 9, "1.000E+09");
2724        assert_fmt("-1000000000", 10, "-1.000E+09");
2725        assert_fmt("1000000000", 7, "1.0E+09");
2726        assert_fmt("-1000000000", 8, "-1.0E+09");
2727        assert_error("1000000000", 6);
2728        assert_error("-1000000000", 7);
2729
2730        // Rounds when truncate
2731        assert_fmt("9999999999", 9, "1.000E+10");
2732        assert_fmt("9999999999", 7, "1.0E+10");
2733        assert_fmt("1899999999", 9, "1.900E+09");
2734        assert_fmt("1899999999", 7, "1.9E+09");
2735        assert_fmt("1989999999", 9, "1.990E+09");
2736        assert_fmt("1989999999", 7, "2.0E+09");
2737        assert_fmt("1999999999", 9, "2.000E+09");
2738        assert_fmt("1999999999", 7, "2.0E+09");
2739        assert_fmt("1666666666", 9, "1.667E+09");
2740        assert_fmt("1666666666", 7, "1.7E+09");
2741        assert_error("1666666666", 6);
2742        assert_fmt("9999999999.999999999", 25, "9999999999.999999999");
2743        assert_fmt("9999999999.999999999", 9, "1.000E+10");
2744        assert_fmt("-9999999999.999999999", 9, "-1.00E+10");
2745        assert_fmt("666666.666666", 10, "666666.667");
2746        assert_fmt(".0000123456789", 10, ".000012346");
2747        assert_fmt(".00000123456789", 10, "1.2346E-06");
2748        assert_fmt(".00000999999999", 10, "1.0000E-05");
2749        assert_fmt("-0.00000999999999", 10, "-1.000E-05");
2750        assert_fmt("-0.00000999999999", 20, "-.00000999999999");
2751        assert_fmt("-0.0000000000123456789", 14, "-1.2345679E-11");
2752        assert_fmt(".0000000000123456789", 14, "1.23456789E-11");
2753        assert_fmt("-0.0000000000123456789", 20, "-1.2345678900000E-11");
2754
2755        // Ignores zero integer
2756        assert_fmt("-0.0000000000123456789", 21, "-.0000000000123456789");
2757        assert_fmt("0.135E-100", 8, "1.4E-101");
2758        assert_fmt("0.135E-100", 15, "1.35000000E-101");
2759        assert_fmt("0.135E-100", 25, "1.350000000000000000E-101");
2760        assert_fmt("0.135E-100", 30, "1.35000000000000000000000E-101");
2761        assert_fmt("-0.135E+100", 25, "-1.350000000000000000E+99");
2762        assert_fmt("-0.135E+100", 30, "-1.35000000000000000000000E+99");
2763        assert_fmt(
2764            "-0.135E-100",
2765            106,
2766            "-.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000135",
2767        );
2768        assert_fmt(
2769            "0.1E-126",
2770            127,
2771            "1.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000E-127",
2772        );
2773
2774        // Ignores ending '.' after integer
2775        assert_fmt("666666.666666", 7, "666667");
2776        assert_fmt("666666.666666", 6, "666667");
2777        assert_error("666666.666666", 5);
2778
2779        // Ignores zeros after decimal's int_val in fraction
2780        fn assert_fmt2(num: Decimal, target_len: u16, expected: &str) {
2781            let mut s = String::with_capacity(256);
2782            num.format_with_sci(target_len, &mut s).unwrap();
2783            assert_eq!(s.as_str(), expected);
2784        }
2785
2786        let num = Decimal::from_parts(330, 3, false).unwrap();
2787        assert_fmt2(num, 10, ".33");
2788        assert_fmt2(num, 2, ".3");
2789    }
2790
2791    #[test]
2792    fn test_format_with_sci_forced() {
2793        fn assert_sci(input: &str, expect_scale: i16, with_zero_before_dot: bool, expect: &str) {
2794            let num = input.parse::<Decimal>().unwrap();
2795            let mut s = String::new();
2796            num.format_with_sci_forced(expect_scale, with_zero_before_dot, &mut s)
2797                .unwrap();
2798            assert_eq!(s.as_str(), expect);
2799        }
2800
2801        assert_sci("0", 0, false, "0E+00");
2802        assert_sci("0", 1, false, " .0E+00");
2803        assert_sci("0", 3, false, " .000E+00");
2804        assert_sci(
2805            "0",
2806            56,
2807            false,
2808            " .00000000000000000000000000000000000000000000000000000000E+00",
2809        );
2810        assert_sci("0", 0, true, "0E+00");
2811        assert_sci("0", 1, true, "0.0E+00");
2812        assert_sci("0", 3, true, "0.000E+00");
2813        assert_sci(
2814            "0",
2815            56,
2816            true,
2817            "0.00000000000000000000000000000000000000000000000000000000E+00",
2818        );
2819        assert_sci("0.6", 0, false, "6E-01");
2820        assert_sci("1.6", 0, false, "2E+00");
2821        assert_sci("1.2", 0, false, "1E+00");
2822        assert_sci(
2823            "3.234234E120",
2824            56,
2825            false,
2826            "3.23423400000000000000000000000000000000000000000000000000E+120",
2827        );
2828        assert_sci(
2829            "3.234234E-120",
2830            56,
2831            false,
2832            "3.23423400000000000000000000000000000000000000000000000000E-120",
2833        );
2834        assert_sci("3.234234E120", 3, false, "3.234E+120");
2835        assert_sci("3.234234E-120", 3, false, "3.234E-120");
2836        assert_sci(
2837            "0.345e100",
2838            56,
2839            false,
2840            "3.45000000000000000000000000000000000000000000000000000000E+99",
2841        );
2842        assert_sci(
2843            "0.345e-100",
2844            56,
2845            false,
2846            "3.45000000000000000000000000000000000000000000000000000000E-101",
2847        );
2848        assert_sci("3e2", 4, false, "3.0000E+02");
2849        assert_sci("300", 4, false, "3.0000E+02");
2850        assert_sci("0.03", 4, false, "3.0000E-02");
2851        assert_sci("3.36e60", 0, false, "3E+60");
2852        assert_sci("3.36e-60", 0, false, "3E-60");
2853        assert_sci("-3.36e60", 0, false, "-3E+60");
2854        assert_sci("-3.36e-60", 0, false, "-3E-60");
2855        assert_sci("3.36e60", 1, false, "3.4E+60");
2856        assert_sci("3.36e-60", 1, false, "3.4E-60");
2857        assert_sci("-3.36e60", 1, false, "-3.4E+60");
2858        assert_sci("-3.36e-60", 1, false, "-3.4E-60");
2859    }
2860
2861    #[test]
2862    fn test_pow() {
2863        fn assert_pow_uint(base: &str, exponent: u64, expected: &str) {
2864            let decimal = base.parse::<Decimal>().unwrap().pow_u64(exponent).unwrap();
2865            let expected = expected.parse::<Decimal>().unwrap();
2866            assert_eq!(decimal, expected);
2867        }
2868        fn assert_pow_int(base: &str, exponent: i64, expected: &str) {
2869            let decimal = base.parse::<Decimal>().unwrap().pow_i64(exponent).unwrap();
2870            let expected = expected.parse::<Decimal>().unwrap();
2871            assert_eq!(decimal, expected);
2872        }
2873        fn assert_pow_decimal(base: &str, exponent: &str, expected: &str) {
2874            let exponent = exponent.parse::<Decimal>().unwrap();
2875            let decimal = base.parse::<Decimal>().unwrap().checked_pow(&exponent).unwrap();
2876            let expected = expected.parse::<Decimal>().unwrap();
2877            assert_eq!(decimal, expected);
2878        }
2879
2880        assert_pow_uint("0", 0, "1");
2881        assert_pow_uint("0", 2, "0");
2882        assert_pow_uint("30.03", 11, "17910538937279543.381440174900003379415");
2883        assert_pow_uint("0.9999999", 123456, "0.98773029366878871282374552006725694652");
2884        assert_pow_uint("2", 418, "676921312041214565326761275425557544830000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
2885        assert_pow_int("3.333", 3, "37.025927037");
2886        assert_pow_int("123456", -2, "0.000000000065610839816062225597621740797803625383");
2887        assert_pow_int("16.66666", -6, "0.000000046656111974556764327215254493713994963");
2888        assert_pow_int("15", -15, "0.0000000000000000022836582605211672220051325163651837732");
2889        assert_pow_int(
2890            "2",
2891            200,
2892            "1606938044258990275541962092341162602500000000000000000000000",
2893        );
2894        assert_pow_int("100", -9223372036854775808, "0");
2895        assert_pow_decimal("-3", "0", "1");
2896        assert_pow_decimal("3.333", "3", "37.025927037");
2897        assert_pow_decimal("3.3", "2.2", "13.827086118044145328600539201031810464");
2898        assert_pow_decimal("2", "50.1", "1206709641626009.0372720478765230064730");
2899        assert_pow_decimal("2", "-50.1", "0.00000000000000082869976795124193101335598234941507825");
2900        assert_pow_decimal("123456", "2.2", "158974271527.98285353227767713306007512");
2901        assert_pow_decimal(
2902            "123456",
2903            "-12.2",
2904            "0.0000000000000000000000000000000000000000000000000000000000000076480574247485409303800372083765338615",
2905        );
2906        assert_pow_decimal("123456.789", "0.9999999", "123456.64426370977396175023229704225849");
2907        assert_pow_decimal(
2908            "234567890123456.789",
2909            "5.8822",
2910            "3379043109285747020459941490972051546800000000000000000000000000000000000000000000000",
2911        );
2912        assert_pow_decimal("0.9999999", "0.789", "0.99999992109999916760496639898664270396");
2913        assert_pow_decimal("0.9999999", "123456.789", "0.98773021573686772017452509110356382471");
2914        assert_pow_decimal(
2915            "0.9",
2916            "22222220000000000000000000000000000000000000000000000000000000",
2917            "0",
2918        );
2919        assert_pow_decimal(
2920            "1",
2921            "22222220000000000000000000000000000000000000000000000000000000",
2922            "1",
2923        );
2924        assert_pow_decimal("2", "418.1", "725506298471023093722890872060236907240000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
2925        assert_pow_decimal(
2926            "1.0000000000000000000000000000000000001",
2927            "340282366920938463463374607431768211450",
2928            "600171577097065.40413095725314413792835",
2929        );
2930        assert_pow_decimal("100", "-170141183460469231731687303715884105720", "0");
2931        assert_pow_decimal("5", "-4188888888888888888444444444444444000000000000000000000000", "0");
2932        assert_pow_decimal(
2933            "1.000000000001",
2934            "1234567889",
2935            "1.0012353302816452027366495735797849363",
2936        );
2937    }
2938
2939    #[test]
2940    fn test_ln() {
2941        fn assert_ln(val: &str, expected: &str) {
2942            let decimal = val.parse::<Decimal>().unwrap().ln().unwrap();
2943            let expected = expected.parse::<Decimal>().unwrap();
2944            assert_eq!(decimal, expected);
2945        }
2946
2947        assert_ln(
2948            "1.0000000000000000000000000000000000001",
2949            "0.000000000000000000000000000000000000099999999999999999999999999999999999996",
2950        );
2951        assert_ln("0.000123456789", "-8.9996193497605301750219641082491662814");
2952        assert_ln("13.3", "2.5877640352277080810963887206466690594");
2953        assert_ln("1000", "6.9077552789821370520539743640530926228");
2954        assert_ln("12345.67891", "9.4210613950018353041649175905084849130");
2955        assert_ln("1500000000000000", "34.944241503018849642247884935729812251");
2956        assert_ln(
2957            "1500000000000000000000000000000.123456",
2958            "69.483017897929534902517756755995357669",
2959        );
2960        assert_ln(
2961            "15000000000000000000000000000000000000000000000000000000000000000000000000000",
2962            "175.40193217565563636734536367147602892",
2963        );
2964    }
2965
2966    #[test]
2967    fn test_exp() {
2968        fn assert_exp(exponent: &str, expected: &str) {
2969            let decimal = exponent.parse::<Decimal>().unwrap().exp().unwrap();
2970            let expected = expected.parse::<Decimal>().unwrap();
2971            assert_eq!(decimal, expected);
2972        }
2973
2974        assert_exp("1", "2.7182818284590452353602874713526624975");
2975        assert_exp("0.00000012", "1.0000001200000072000002880000086400002");
2976        assert_exp(
2977            "0.9999999999999999999999999999999999999",
2978            "2.7182818284590452353602874713526624971",
2979        );
2980        assert_exp("-0.00000012", "0.99999988000000719999971200000863999979");
2981        assert_exp(
2982            "-0.9999999999999999999999999999999999999",
2983            "0.36787944117144232159552377016146086748",
2984        );
2985        assert_exp("12.3456789", "229964.19456908213454430507162889547155");
2986        assert_exp("-50.1", "0.00000000000000000000017452050324689209452230894746470912110");
2987        assert_exp("259.11111", "33925423113202888041488548716222730394000000000000000000000000000000000000000000000000000000000000000000000000000");
2988        assert_exp("290.123456", "997736847550168914657296864583252087210000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
2989    }
2990
2991    #[test]
2992    fn generate_exp_array() {
2993        // [e^0, e^290]
2994        for i in 0..291 {
2995            let exponent = Decimal::from(i);
2996            let result = exponent.exp_decimal().unwrap();
2997
2998            if i % 5 == 0 {
2999                println!("// e^{}", i);
3000            }
3001            println!(
3002                "unsafe {{ Decimal::from_raw_parts({}, {}, {}) }},",
3003                result.int_val(),
3004                result.scale,
3005                result.negative,
3006            );
3007        }
3008    }
3009
3010    #[test]
3011    fn generate_exp_negative_array() {
3012        // e^-291
3013        const EXP_NEGATIVE_291: Decimal =
3014            unsafe { Decimal::from_raw_parts(41716298478166806118243377939293045745, 164, false) };
3015        // [e^-299, e^-291]
3016        for i in 291..300 {
3017            let result = EXP_NEGATIVE_291.checked_div(&NATURAL_EXP[(i - 291) as usize]).unwrap();
3018
3019            if i % 5 == 0 {
3020                println!("// e^-{}", i);
3021            }
3022            println!(
3023                "unsafe {{ Decimal::from_raw_parts({}, {}, {}) }},",
3024                result.int_val(),
3025                result.scale,
3026                result.negative,
3027            );
3028        }
3029    }
3030
3031    #[test]
3032    fn test_format_to_hex() {
3033        fn assert_fmt_hex(input: &str, is_capital: bool, expect: &str) {
3034            let mut s = String::new();
3035            let num = input.parse::<Decimal>().unwrap();
3036            num.format_to_hex(is_capital, &mut s).unwrap();
3037            assert_eq!(s.as_str(), expect);
3038        }
3039
3040        assert_fmt_hex("3", true, "3");
3041        assert_fmt_hex("15", true, "F");
3042        assert_fmt_hex("15", false, "f");
3043        assert_fmt_hex(
3044            "7e75",
3045            true,
3046            "f79dc0e8c518f31eb934b4522ad36a1d39f275c35e858000000000000000000"
3047                .to_uppercase()
3048                .as_str(),
3049        );
3050        assert_fmt_hex(
3051            "7e75",
3052            false,
3053            "f79dc0e8c518f31eb934b4522ad36a1d39f275c35e858000000000000000000",
3054        );
3055        assert_fmt_hex(
3056            "6e70",
3057            true,
3058            "8b18610932ab6b2906ea3dfeaa8da073a862d7e0d800000000000000000"
3059                .to_uppercase()
3060                .as_str(),
3061        );
3062        assert_fmt_hex(
3063            "6e70",
3064            false,
3065            "8b18610932ab6b2906ea3dfeaa8da073a862d7e0d800000000000000000",
3066        );
3067        assert_fmt_hex("999", true, "3E7");
3068        assert_fmt_hex("999", false, "3e7");
3069        assert_fmt_hex(
3070            "9.93879279687e53",
3071            true,
3072            "a6067cc8b3051f61f39c31e697c47c18e3c0000000000".to_uppercase().as_str(),
3073        );
3074        assert_fmt_hex(
3075            "9.93879279687e53",
3076            false,
3077            "a6067cc8b3051f61f39c31e697c47c18e3c0000000000",
3078        );
3079        assert_fmt_hex(
3080            "12345678901234567890123456789012345678e30",
3081            true,
3082            "753aaed77fe1aa5508b3e1db763b1a087e44a76fa433d81f80000000"
3083                .to_uppercase()
3084                .as_str(),
3085        );
3086        assert_fmt_hex(
3087            "12345678901234567890123456789012345678e30",
3088            false,
3089            "753aaed77fe1aa5508b3e1db763b1a087e44a76fa433d81f80000000",
3090        );
3091        assert_fmt_hex("253.658", true, "FE");
3092        assert_fmt_hex("253.658", false, "fe");
3093        assert_fmt_hex("0", true, "0");
3094        assert_fmt_hex("0", false, "0");
3095        assert_fmt_hex("0.2", true, "0");
3096        assert_fmt_hex("0.2", false, "0");
3097        assert_fmt_hex("0.7", true, "1");
3098        assert_fmt_hex("0.7", false, "1");
3099        // Max value
3100        assert_fmt_hex(
3101            "72370055773322622139731865630429942408e38",
3102            true,
3103            "fffffffffffffffffffffffffffffffe9e6c3ef3908c56c58cab20000000000"
3104                .to_uppercase()
3105                .as_str(),
3106        );
3107        assert_fmt_hex(
3108            "72370055773322622139731865630429942408e38",
3109            false,
3110            "fffffffffffffffffffffffffffffffe9e6c3ef3908c56c58cab20000000000",
3111        );
3112    }
3113
3114    #[test]
3115    fn test_format_to_json() {
3116        fn assert_fmt_json(input: &str, expect: &str) {
3117            let mut s = String::new();
3118            let num = input.parse::<Decimal>().unwrap();
3119            num.format_to_json(&mut s).unwrap();
3120            assert_eq!(s.as_str(), expect);
3121        }
3122
3123        assert_fmt_json("0", "0");
3124        assert_fmt_json("123", "123");
3125        assert_fmt_json("123.123", "123.123");
3126        assert_fmt_json("-123", "-123");
3127        assert_fmt_json("-123.123", "-123.123");
3128        assert_fmt_json("123e37", "1230000000000000000000000000000000000000");
3129        assert_fmt_json("123e38", "1.23E+40");
3130        assert_fmt_json("123e39", "1.23E+41");
3131        assert_fmt_json("12300e35", "1230000000000000000000000000000000000000");
3132        assert_fmt_json("12300e36", "1.23E+40");
3133        assert_fmt_json("12300e37", "1.23E+41");
3134        assert_fmt_json("-123e37", "-1230000000000000000000000000000000000000");
3135        assert_fmt_json("-123e38", "-1.23E+40");
3136        assert_fmt_json("-123e39", "-1.23E+41");
3137        assert_fmt_json("-12300e35", "-1230000000000000000000000000000000000000");
3138        assert_fmt_json("-12300e36", "-1.23E+40");
3139        assert_fmt_json("-12300e37", "-1.23E+41");
3140
3141        assert_fmt_json("123e-42", "1.23E-40");
3142        assert_fmt_json("123e-41", "1.23E-39");
3143        assert_fmt_json("123e-40", "0.0000000000000000000000000000000000000123");
3144        assert_fmt_json("12300e-44", "1.23E-40");
3145        assert_fmt_json("12300e-43", "1.23E-39");
3146        assert_fmt_json("12300e-42", "0.0000000000000000000000000000000000000123");
3147        assert_fmt_json("-123e-42", "-1.23E-40");
3148        assert_fmt_json("-123e-41", "-1.23E-39");
3149        assert_fmt_json("-123e-40", "-0.0000000000000000000000000000000000000123");
3150        assert_fmt_json("-12300e-44", "-1.23E-40");
3151        assert_fmt_json("-12300e-43", "-1.23E-39");
3152        assert_fmt_json("-12300e-42", "-0.0000000000000000000000000000000000000123");
3153
3154        assert_fmt_json("1234.1234e36", "1234123400000000000000000000000000000000");
3155        assert_fmt_json("1234.1234e37", "1.2341234E+40");
3156        assert_fmt_json("1234.1234e-36", "0.0000000000000000000000000000000012341234");
3157        assert_fmt_json("1234.1234e-37", "1.2341234E-34");
3158
3159        assert_fmt_json(
3160            "12345678901234567890123456789012345678e2",
3161            "1234567890123456789012345678901234567800",
3162        );
3163        assert_fmt_json(
3164            "12345678901234567890123456789012345678e3",
3165            "1.2345678901234567890123456789012345678E+40",
3166        );
3167        assert_fmt_json(
3168            "12345678901234567890123456789012345678e-40",
3169            "0.0012345678901234567890123456789012345678",
3170        );
3171        assert_fmt_json(
3172            "12345678901234567890123456789012345678e-41",
3173            "1.2345678901234567890123456789012345678E-4",
3174        );
3175
3176        assert_fmt_json(
3177            "1234567890123456789012345678901234567800e0",
3178            "1234567890123456789012345678901234567800",
3179        );
3180        assert_fmt_json(
3181            "1234567890123456789012345678901234567800e1",
3182            "1.2345678901234567890123456789012345678E+40",
3183        );
3184        assert_fmt_json(
3185            "1234567890123456789012345678901234567800e-42",
3186            "0.0012345678901234567890123456789012345678",
3187        );
3188        assert_fmt_json(
3189            "1234567890123456789012345678901234567800e-43",
3190            "1.2345678901234567890123456789012345678E-4",
3191        );
3192
3193        assert_fmt_json(
3194            "12345678901234567.890123456789012345678e19",
3195            "123456789012345678901234567890123456.78",
3196        );
3197        assert_fmt_json(
3198            "12345678901234567.890123456789012345678e21",
3199            "12345678901234567890123456789012345678",
3200        );
3201        assert_fmt_json(
3202            "12345678901234567.890123456789012345678e23",
3203            "1234567890123456789012345678901234567800",
3204        );
3205        assert_fmt_json(
3206            "12345678901234567.890123456789012345678e24",
3207            "1.2345678901234567890123456789012345678E+40",
3208        );
3209        assert_fmt_json(
3210            "12345678901234567.890123456789012345678e-15",
3211            "12.345678901234567890123456789012345678",
3212        );
3213        assert_fmt_json(
3214            "12345678901234567.890123456789012345678e-17",
3215            "0.12345678901234567890123456789012345678",
3216        );
3217        assert_fmt_json(
3218            "12345678901234567.890123456789012345678e-19",
3219            "0.0012345678901234567890123456789012345678",
3220        );
3221        assert_fmt_json(
3222            "12345678901234567.890123456789012345678e-21",
3223            "1.2345678901234567890123456789012345678E-5",
3224        );
3225
3226        assert_fmt_json(
3227            "0.00000000012345678901234567890123456789012345678e-1",
3228            "1.2345678901234567890123456789012345678E-11",
3229        );
3230        assert_fmt_json(
3231            "0.00000000012345678901234567890123456789012345678e0",
3232            "1.2345678901234567890123456789012345678E-10",
3233        );
3234        assert_fmt_json(
3235            "0.00000000012345678901234567890123456789012345678e6",
3236            "1.2345678901234567890123456789012345678E-4",
3237        );
3238        assert_fmt_json(
3239            "0.00000000012345678901234567890123456789012345678e7",
3240            "0.0012345678901234567890123456789012345678",
3241        );
3242        assert_fmt_json(
3243            "0.00000000012345678901234567890123456789012345678e47",
3244            "12345678901234567890123456789012345678",
3245        );
3246        assert_fmt_json(
3247            "0.00000000012345678901234567890123456789012345678e49",
3248            "1234567890123456789012345678901234567800",
3249        );
3250        assert_fmt_json(
3251            "0.00000000012345678901234567890123456789012345678e50",
3252            "1.2345678901234567890123456789012345678E+40",
3253        );
3254    }
3255
3256    #[test]
3257    fn test_unchecked_add() {
3258        fn assert_unchecked_add<const DECIMAL_MODEL: u8>(val1: &str, val2: &str, expected: &str, scale: i16) {
3259            let mut var1 = val1.parse::<Decimal>().unwrap();
3260            let ret = var1.round_with_precision(38, scale);
3261            assert!(!ret);
3262            let mut var2 = val2.parse::<Decimal>().unwrap();
3263            let ret = var2.round_with_precision(38, scale);
3264            assert!(!ret);
3265            let expected = expected.parse::<Decimal>().unwrap();
3266
3267            let result = unsafe { var1.add_with_same_scale_unchecked::<DECIMAL_MODEL>(&var2, scale) };
3268            assert_eq!(result, expected);
3269        }
3270
3271        assert_unchecked_add::<DECIMAL64>("2.34", "3.45", "5.79", 2);
3272        assert_unchecked_add::<DECIMAL64>("2.34", "-3.45", "-1.11", 2);
3273        assert_unchecked_add::<DECIMAL64>("0", "-3.45", "-3.45", 2);
3274        assert_unchecked_add::<DECIMAL64>("-2.34", "3.45", "1.11", 2);
3275        assert_unchecked_add::<DECIMAL64>("-2.34", "-3.45", "-5.79", 2);
3276        assert_unchecked_add::<DECIMAL64>("0", "0", "0", 2);
3277        assert_unchecked_add::<DECIMAL64>("9999999999999999.99", "9999999999999999.99", "19999999999999999.98", 2);
3278        assert_unchecked_add::<DECIMAL64>("0", "9999999999999999.99", "9999999999999999.99", 2);
3279        assert_unchecked_add::<DECIMAL64>(
3280            "-9999999999999999.99",
3281            "-9999999999999999.99",
3282            "-19999999999999999.98",
3283            2,
3284        );
3285        assert_unchecked_add::<DECIMAL64>("-9999999999999999.99", "9999999999999999.99", "0", 2);
3286        assert_unchecked_add::<DECIMAL64>("0", "9999999999999999.99", "9999999999999999.99", 2);
3287
3288        assert_unchecked_add::<DECIMAL128>("2.34", "3.45", "5.79", 2);
3289        assert_unchecked_add::<DECIMAL128>("2.34", "-3.45", "-1.11", 2);
3290        assert_unchecked_add::<DECIMAL128>("0", "-3.45", "-3.45", 2);
3291        assert_unchecked_add::<DECIMAL128>("-2.34", "3.45", "1.11", 2);
3292        assert_unchecked_add::<DECIMAL128>("-2.34", "-3.45", "-5.79", 2);
3293        assert_unchecked_add::<DECIMAL128>("0", "0", "0", 2);
3294        assert_unchecked_add::<DECIMAL128>("9999999999999999.99", "9999999999999999.99", "19999999999999999.98", 2);
3295        assert_unchecked_add::<DECIMAL128>("0", "9999999999999999.99", "9999999999999999.99", 2);
3296        assert_unchecked_add::<DECIMAL128>(
3297            "-9999999999999999.99",
3298            "-9999999999999999.99",
3299            "-19999999999999999.98",
3300            2,
3301        );
3302        assert_unchecked_add::<DECIMAL128>("-9999999999999999.99", "9999999999999999.99", "0", 2);
3303        assert_unchecked_add::<DECIMAL128>("0", "9999999999999999.99", "9999999999999999.99", 2);
3304
3305        assert_unchecked_add::<DECIMAL128>(
3306            "99999999999999999999999999999999999.99",
3307            "99999999999999999999999999999999999.99",
3308            "199999999999999999999999999999999999.98",
3309            2,
3310        );
3311
3312        assert_unchecked_add::<DECIMAL128>(
3313            "-99999999999999999999999999999999999.99",
3314            "-99999999999999999999999999999999999.99",
3315            "-199999999999999999999999999999999999.98",
3316            2,
3317        );
3318
3319        assert_unchecked_add::<DECIMAL128>(
3320            "-99999999999999999999999999999999999.99",
3321            "99999999999999999999999999999999999.99",
3322            "0",
3323            2,
3324        );
3325
3326        assert_unchecked_add::<DECIMAL128>(
3327            "9999999999999999999999999999999999999",
3328            "9999999999999999999999999999999999999",
3329            "19999999999999999999999999999999999998",
3330            0,
3331        );
3332
3333        assert_unchecked_add::<DECIMAL128>(
3334            "0.9999999999999999999999999999999999999",
3335            "0.9999999999999999999999999999999999999",
3336            "1.9999999999999999999999999999999999998",
3337            37,
3338        );
3339
3340        fn assert_unchecked_add_with_negative<const DECIMAL_MODEL: u8>(
3341            val1: &str,
3342            val2: &str,
3343            expected: &str,
3344            scale: i16,
3345            negative: bool,
3346        ) {
3347            let mut var1 = val1.parse::<Decimal>().unwrap();
3348            let ret = var1.round_with_precision(38, scale);
3349            assert!(!ret);
3350            let mut var2 = val2.parse::<Decimal>().unwrap();
3351            let ret = var2.round_with_precision(38, scale);
3352            assert!(!ret);
3353            let expected = expected.parse::<Decimal>().unwrap();
3354
3355            let result =
3356                unsafe { var1.add_with_same_scale_and_negative_unchecked::<DECIMAL_MODEL>(&var2, scale, negative) };
3357            assert_eq!(result, expected);
3358        }
3359
3360        assert_unchecked_add_with_negative::<DECIMAL64>("2.34", "3.45", "5.79", 2, false);
3361        assert_unchecked_add_with_negative::<DECIMAL64>("0", "-3.45", "-3.45", 2, true);
3362        assert_unchecked_add_with_negative::<DECIMAL64>("-2.34", "-3.45", "-5.79", 2, true);
3363        assert_unchecked_add_with_negative::<DECIMAL64>("0", "0", "0", 0, false);
3364        assert_unchecked_add_with_negative::<DECIMAL64>(
3365            "9999999999999999.99",
3366            "9999999999999999.99",
3367            "19999999999999999.98",
3368            2,
3369            false,
3370        );
3371        assert_unchecked_add_with_negative::<DECIMAL64>("0", "9999999999999999.99", "9999999999999999.99", 2, false);
3372        assert_unchecked_add_with_negative::<DECIMAL64>(
3373            "-9999999999999999.99",
3374            "-9999999999999999.99",
3375            "-19999999999999999.98",
3376            2,
3377            true,
3378        );
3379
3380        assert_unchecked_add_with_negative::<DECIMAL128>("2.34", "3.45", "5.79", 2, false);
3381        assert_unchecked_add_with_negative::<DECIMAL128>("0", "-3.45", "-3.45", 2, true);
3382        assert_unchecked_add_with_negative::<DECIMAL128>("-2.34", "-3.45", "-5.79", 2, true);
3383        assert_unchecked_add_with_negative::<DECIMAL128>("0", "0", "0", 0, false);
3384        assert_unchecked_add_with_negative::<DECIMAL128>(
3385            "9999999999999999.99",
3386            "9999999999999999.99",
3387            "19999999999999999.98",
3388            2,
3389            false,
3390        );
3391        assert_unchecked_add_with_negative::<DECIMAL128>("0", "9999999999999999.99", "9999999999999999.99", 2, false);
3392        assert_unchecked_add_with_negative::<DECIMAL128>(
3393            "-9999999999999999.99",
3394            "-9999999999999999.99",
3395            "-19999999999999999.98",
3396            2,
3397            true,
3398        );
3399        assert_unchecked_add_with_negative::<DECIMAL128>(
3400            "99999999999999999999999999999999999.99",
3401            "99999999999999999999999999999999999.99",
3402            "199999999999999999999999999999999999.98",
3403            2,
3404            false,
3405        );
3406
3407        assert_unchecked_add_with_negative::<DECIMAL128>(
3408            "-99999999999999999999999999999999999.99",
3409            "-99999999999999999999999999999999999.99",
3410            "-199999999999999999999999999999999999.98",
3411            2,
3412            true,
3413        );
3414
3415        let zero_decimal = unsafe { Decimal::from_raw_parts(0, 2, true) };
3416        let val = unsafe { Decimal::from_raw_parts(38, 2, true) };
3417        let ret = unsafe { zero_decimal.add_with_same_scale_unchecked::<DECIMAL64>(&val, 2) };
3418        assert_eq!(ret, val);
3419        let ret = unsafe { val.add_with_same_scale_unchecked::<DECIMAL64>(&zero_decimal, 2) };
3420        assert_eq!(ret, val);
3421    }
3422
3423    #[test]
3424    fn test_unchecked_sub() {
3425        fn assert_unchecked_sub<const DECIMAL_MODEL: u8>(val1: &str, val2: &str, expected: &str, scale: i16) {
3426            let mut var1 = val1.parse::<Decimal>().unwrap();
3427            let ret = var1.round_with_precision(38, scale);
3428            assert!(!ret);
3429            let mut var2 = val2.parse::<Decimal>().unwrap();
3430            let ret = var2.round_with_precision(38, scale);
3431            assert!(!ret);
3432            let expected = expected.parse::<Decimal>().unwrap();
3433
3434            let result = unsafe { var1.sub_with_same_scale_unchecked::<DECIMAL_MODEL>(&var2, scale) };
3435            assert_eq!(result, expected);
3436        }
3437        assert_unchecked_sub::<DECIMAL64>("2.34", "3.45", "-1.11", 2);
3438        assert_unchecked_sub::<DECIMAL64>("3.45", "2.34", "1.11", 2);
3439        assert_unchecked_sub::<DECIMAL64>("-2.34", "-3.45", "1.11", 2);
3440        assert_unchecked_sub::<DECIMAL64>("-3.45", "-2.34", "-1.11", 2);
3441        assert_unchecked_sub::<DECIMAL64>("0", "-3.45", "3.45", 2);
3442        assert_unchecked_sub::<DECIMAL64>("-3.45", "0", "-3.45", 2);
3443        assert_unchecked_sub::<DECIMAL64>("-2.34", "3.45", "-5.79", 2);
3444        assert_unchecked_sub::<DECIMAL64>("3.45", "-2.34", "5.79", 2);
3445        assert_unchecked_sub::<DECIMAL64>("2.34", "-3.45", "5.79", 2);
3446        assert_unchecked_sub::<DECIMAL64>("-3.45", "2.34", "-5.79", 2);
3447        assert_unchecked_sub::<DECIMAL64>("0", "0", "0", 2);
3448        assert_unchecked_sub::<DECIMAL64>("9999999999999999.99", "9999999999999999.99", "0", 2);
3449        assert_unchecked_sub::<DECIMAL64>("-9999999999999999.99", "-9999999999999999.99", "0", 2);
3450        assert_unchecked_sub::<DECIMAL64>("9999999999999999.99", "-9999999999999999.99", "19999999999999999.98", 2);
3451        assert_unchecked_sub::<DECIMAL64>(
3452            "-9999999999999999.99",
3453            "9999999999999999.99",
3454            "-19999999999999999.98",
3455            2,
3456        );
3457        assert_unchecked_sub::<DECIMAL64>("0", "9999999999999999.99", "-9999999999999999.99", 2);
3458        assert_unchecked_sub::<DECIMAL64>("-9999999999999999.99", "0", "-9999999999999999.99", 2);
3459        assert_unchecked_sub::<DECIMAL64>("0", "-9999999999999999.99", "9999999999999999.99", 2);
3460
3461        assert_unchecked_sub::<DECIMAL128>("2.34", "3.45", "-1.11", 2);
3462        assert_unchecked_sub::<DECIMAL128>("3.45", "2.34", "1.11", 2);
3463        assert_unchecked_sub::<DECIMAL128>("-2.34", "-3.45", "1.11", 2);
3464        assert_unchecked_sub::<DECIMAL128>("-3.45", "-2.34", "-1.11", 2);
3465        assert_unchecked_sub::<DECIMAL128>("0", "-3.45", "3.45", 2);
3466        assert_unchecked_sub::<DECIMAL128>("-3.45", "0", "-3.45", 2);
3467        assert_unchecked_sub::<DECIMAL128>("-2.34", "3.45", "-5.79", 2);
3468        assert_unchecked_sub::<DECIMAL128>("3.45", "-2.34", "5.79", 2);
3469        assert_unchecked_sub::<DECIMAL128>("2.34", "-3.45", "5.79", 2);
3470        assert_unchecked_sub::<DECIMAL128>("-3.45", "2.34", "-5.79", 2);
3471        assert_unchecked_sub::<DECIMAL128>("0", "0", "0", 2);
3472        assert_unchecked_sub::<DECIMAL128>("9999999999999999.99", "9999999999999999.99", "0", 2);
3473        assert_unchecked_sub::<DECIMAL128>("-9999999999999999.99", "-9999999999999999.99", "0", 2);
3474        assert_unchecked_sub::<DECIMAL128>("9999999999999999.99", "-9999999999999999.99", "19999999999999999.98", 2);
3475        assert_unchecked_sub::<DECIMAL128>(
3476            "-9999999999999999.99",
3477            "9999999999999999.99",
3478            "-19999999999999999.98",
3479            2,
3480        );
3481        assert_unchecked_sub::<DECIMAL128>("0", "9999999999999999.99", "-9999999999999999.99", 2);
3482        assert_unchecked_sub::<DECIMAL128>("-9999999999999999.99", "0", "-9999999999999999.99", 2);
3483        assert_unchecked_sub::<DECIMAL128>("0", "-9999999999999999.99", "9999999999999999.99", 2);
3484
3485        assert_unchecked_sub::<DECIMAL128>(
3486            "-99999999999999999999999999999999999.99",
3487            "99999999999999999999999999999999999.99",
3488            "-199999999999999999999999999999999999.98",
3489            2,
3490        );
3491
3492        assert_unchecked_sub::<DECIMAL128>(
3493            "99999999999999999999999999999999999.99",
3494            "-99999999999999999999999999999999999.99",
3495            "199999999999999999999999999999999999.98",
3496            2,
3497        );
3498
3499        assert_unchecked_sub::<DECIMAL128>(
3500            "99999999999999999999999999999999999.99",
3501            "0",
3502            "99999999999999999999999999999999999.99",
3503            2,
3504        );
3505    }
3506
3507    #[test]
3508    fn test_unchecked_mul() {
3509        fn assert_unchecked_mul<const DECIMAL_MODEL: u8>(val1: &str, val2: &str, expected: &str, scale: i16) {
3510            let var1 = val1.parse::<Decimal>().unwrap();
3511            let var2 = val2.parse::<Decimal>().unwrap();
3512            let mut expected = expected.parse::<Decimal>().unwrap();
3513            let ret = expected.round_with_precision(38, scale);
3514            assert!(!ret);
3515            let result = unsafe { var1.mul_unchecked::<DECIMAL_MODEL>(&var2, scale) };
3516            assert_eq!(result, expected);
3517        }
3518
3519        assert_unchecked_mul::<DECIMAL64>("2.03", "3.18", "6.4554", 4);
3520        assert_unchecked_mul::<DECIMAL64>("2.03", "-3.18", "-6.4554", 4);
3521        assert_unchecked_mul::<DECIMAL64>("-2.03", "3.18", "-6.4554", 4);
3522        assert_unchecked_mul::<DECIMAL64>("999999999", "999999999", "999999998000000001", 0);
3523        assert_unchecked_mul::<DECIMAL64>("999999999", "9999999999", "9999999989000000001", 0);
3524        assert_unchecked_mul::<DECIMAL64>("999999999", "9999999999", "9999999989000000001", 0);
3525        assert_unchecked_mul::<DECIMAL64>("0.999999999", "0.9999999999", "0.9999999989000000001", 19);
3526        assert_unchecked_mul::<DECIMAL64>("0", "0.9999999999", "0", 19);
3527
3528        assert_unchecked_mul::<DECIMAL128>("2.03", "3.18", "6.4554", 4);
3529        assert_unchecked_mul::<DECIMAL128>("2.03", "-3.18", "-6.4554", 4);
3530        assert_unchecked_mul::<DECIMAL128>("-2.03", "3.18", "-6.4554", 4);
3531        assert_unchecked_mul::<DECIMAL128>("999999999", "999999999", "999999998000000001", 0);
3532        assert_unchecked_mul::<DECIMAL128>("999999999", "9999999999", "9999999989000000001", 0);
3533        assert_unchecked_mul::<DECIMAL128>("999999.999", "99999.99999", "99999999890.00000001", 8);
3534        assert_unchecked_mul::<DECIMAL128>("0.999999999", "0.9999999999", "0.9999999989000000001", 19);
3535        assert_unchecked_mul::<DECIMAL128>("0", "0.9999999999", "0", 19);
3536
3537        assert_unchecked_mul::<DECIMAL128>(
3538            "9999999999999999999",
3539            "9999999999999999999",
3540            "99999999999999999980000000000000000001",
3541            0,
3542        );
3543
3544        assert_unchecked_mul::<DECIMAL128>(
3545            "9999999999999999999",
3546            "9999999999999999999",
3547            "99999999999999999980000000000000000001",
3548            0,
3549        );
3550        assert_unchecked_mul::<DECIMAL128>(
3551            "0.9999999999999999999",
3552            "0.9999999999999999999",
3553            "0.99999999999999999980000000000000000001",
3554            38,
3555        );
3556        assert_unchecked_mul::<DECIMAL128>(
3557            "999999999999.9999999",
3558            "99999999999999.99999",
3559            "99999999999999999980000000.000000000001",
3560            12,
3561        );
3562    }
3563
3564    #[test]
3565    fn test_unchecked_and_compare() {
3566        unsafe {
3567            let left = Decimal::from_raw_parts(123, 2, true);
3568            let right = Decimal::from_raw_parts(0, 1, false);
3569            let mul_val = left.mul_unchecked::<DECIMAL128>(&right, 3);
3570            let expect = Decimal::from_raw_parts(0, 45, false);
3571            assert_eq!(mul_val.cmp(&expect), Ordering::Equal);
3572        }
3573
3574        unsafe {
3575            let left = Decimal::from_raw_parts(0, 2, true);
3576            let right = Decimal::from_raw_parts(0, 2, true);
3577            let val = left.sub_with_same_scale_unchecked::<DECIMAL128>(&right, 2);
3578            let expect = Decimal::from_raw_parts(0, 45, false);
3579            assert_eq!(val.cmp(&expect), Ordering::Equal);
3580        }
3581
3582        unsafe {
3583            let left = Decimal::from_raw_parts(0, 2, true);
3584            let right = Decimal::from_raw_parts(0, 2, true);
3585            let val = left.add_with_same_scale_unchecked::<DECIMAL128>(&right, 2);
3586            let expect = Decimal::from_raw_parts(0, 45, false);
3587            assert_eq!(val.cmp(&expect), Ordering::Equal);
3588        }
3589
3590        unsafe {
3591            let left = Decimal::from_raw_parts(0, 2, true);
3592            let right = Decimal::from_raw_parts(0, 2, true);
3593            let val = left.add_with_same_scale_and_negative_unchecked::<DECIMAL128>(&right, 2, true);
3594            let expect = Decimal::from_raw_parts(0, 45, false);
3595            assert_eq!(val.cmp(&expect), Ordering::Equal);
3596        }
3597    }
3598}