Skip to main content

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