File: php_decimal.c

package info (click to toggle)
php-decimal 1.5.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 456 kB
  • sloc: ansic: 1,928; xml: 102; makefile: 2
file content (2931 lines) | stat: -rw-r--r-- 80,165 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
/**
 * The MIT License (MIT)
 * Copyright (c) 2018 Rudi Theunissen
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including  without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
 * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php_decimal.h"

/**
 * Class entry.
 */
zend_class_entry *php_decimal_ce;

/**
 * Object handlers.
 */
zend_object_handlers php_decimal_handlers;


/******************************************************************************/
/*                          ERRORS AND DEBUGGING                              */
/******************************************************************************/

/**
 * Prints an mpd to stdout.
 */
static void php_decimal_print_mpd(mpd_t *mpd)
{
    char *str;
    mpd_to_sci_size(&str, mpd, 1);
    php_printf("%s", str);
    mpd_free(str);
}

/**
 * Prints a decimal object to stdout.
 */
static void php_decimal_print(php_decimal_t *obj)
{
    char *str;
    mpd_to_sci_size(&str, PHP_DECIMAL_MPD(obj), 1);
    php_printf("{\n  repr: %s\n  prec: %ld\n}\n", str, obj->prec);
    mpd_free(str);
}

/**
 * Throws an exception when an invalid data type was given to create a decimal.
 */
static void php_decimal_wrong_type(zval *arg, int index, const char *expected)
{
    const char *space;
    const char *cname = get_active_class_name(&space);

    zend_throw_exception_ex(zend_ce_type_error, 0, "%s%s%s() expected parameter %d to be %s, %s given",
        cname,
        space,
        get_active_function_name(),
        index,
        expected,
        zend_zval_type_name(arg)
    );
}

/**
 * Called when a decimal is constructed using an unsupported data type.
 */
static void php_decimal_unsupported_type(zval *arg)
{
    php_decimal_wrong_type(arg, 1, "a string, integer, or decimal");
}

/**
 * Called when an operation on many failed, because the values were not given as
 * an array or traversable object.
 */
static void php_decimal_expected_iterable(zval *arg)
{
    php_decimal_wrong_type(arg, 1, "an array or traversable object");
}

/**
 * Throws an exception when an invalid precision was given, eg. -1
 */
static void php_decimal_precision_out_of_range(zend_long prec)
{
    zend_throw_exception(spl_ce_OutOfRangeException, "Decimal precision out of range", 0);
}

/**
 * Called when a memory allocation error has been detected.
 */
static void php_decimal_memory_error()
{
    zend_error(E_ERROR, "Failed to allocate memory for decimal");
}

/**
 * Called when an unexpected error has occurred, to prevent undefined behaviour.
 */
static void php_decimal_unknown_error()
{
    zend_error(E_ERROR, "Unexpected error");
}

/**
 * Called when a rounding operation is attempted with an invalid mode.
 */
static void php_decimal_unsupported_rounding_mode(php_decimal_rounding_t mode)
{
    zend_throw_exception(spl_ce_InvalidArgumentException, "Unsupported rounding mode", 0);
}

/**
 * Called when a string conversion failed.
 */
static void php_decimal_failed_to_parse_string(zend_string * str)
{
    zend_throw_exception_ex(spl_ce_DomainException, 0, "Failed to parse string as decimal: \"%s\"", ZSTR_VAL(str));
}

/**
 * Called when a string conversion did not use all digits of the input.
 */
static void php_decimal_loss_of_data_on_string_conversion()
{
    zend_error(E_WARNING, "Loss of data on string conversion");
}

/**
 * Called when a PHP integer conversion did not use all digits of the input.
 */
static void php_decimal_loss_of_data_on_long_conversion()
{
    zend_error(E_WARNING, "Loss of data on integer conversion");
}

/**
 * Called when a decimal could not be rounded, potentially beyond max prec.
 */
static void php_decimal_failed_to_round()
{
    zend_throw_exception(spl_ce_RuntimeException, "Failed to round decimal", 0);
}

/**
 * Called when an attempt was made to divide a decimal by 0.
 */
static void php_decimal_division_by_zero_error()
{
    zend_throw_exception(zend_ce_division_by_zero_error, "Division by zero", 0);
}

/**
 * Called when a value could not be unserialized. This should never happen unless
 * someone is trying to do something they're not supposed to.
 */
static void php_decimal_unserialize_error()
{
    zend_throw_exception(spl_ce_InvalidArgumentException, "Could not unserialize decimal", 0);
}

/**
 * Called when an attempt is made to read or write object properties.
 */
static void php_decimal_object_properties_not_supported()
{
    zend_error(E_NOTICE, "Object properties are not supported");
}

/**
 * Called when a decimal is too large to be converted to double.
 */
static void php_decimal_floating_point_overflow()
{
    zend_throw_exception(spl_ce_OverflowException, "Floating point overflow", 0);
}

/**
 * Called when a decimal is too small to be converted to double, eg. 1E-1000
 */
static void php_decimal_floating_point_underflow()
{
    zend_throw_exception(spl_ce_UnderflowException, "Floating point underflow", 0);
}

/**
 * Called when a decimal is too large to be converted to int, eg. 1E+1000
 */
static void php_decimal_integer_overflow()
{
    zend_throw_exception(spl_ce_OverflowException, "Integer overflow", 0);
}

/**
 * Called when NaN or Inf is converted to integer.
 */
static void php_decimal_integer_from_special_is_not_defined()
{
    zend_throw_exception(spl_ce_RuntimeException, "Converting NaN or Inf to integer is not defined", 0);
}

/**
 * Called when attempting to query the signum of NaN.
 */
static void php_decimal_sign_of_nan_is_not_defined()
{
    zend_throw_exception(spl_ce_RuntimeException, "Sign of NaN is not defined", 0);
}

/**
 * Called when __construct is called directly on a decimal object.
 */
static void php_decimal_constructor_already_called()
{
    zend_throw_exception(spl_ce_BadMethodCallException, "Decimal objects are immutable", 0);
}

/**
 * Called when some given number of decimal places was not valid.
 */
static void php_decimal_negative_decimal_places_not_defined()
{
    zend_throw_exception(spl_ce_InvalidArgumentException, "The number of decimal places must be non-negative", 0);
}

/**
 * Called when a trap is triggered in mpdecimal when calling signalling
 * functions (non-quiet). These methods usually don't have the "q" prefix in
 * their names and don't require a status argument. The non-signalling functions
 * should be used whenever we do not expect anything to go wrong or when we want
 * to handle the status directly. This is basically a catch-all error handler.
 *
 * See PHP_DECIMAL_TRAPS
 */
static void php_decimal_mpd_traphandler(mpd_context_t *ctx)
{
    uint32_t status = mpd_getstatus(ctx);

    /* Potentially out of memory, which should be caught by the PHP allocator. */
    if (status & MPD_Malloc_error) {
        php_decimal_memory_error();
        return;
    }

    /* ¯\_(ツ)_/¯ */
    php_decimal_unknown_error();
}


/******************************************************************************/
/*                             CONTEXT & PRECISION                            */
/******************************************************************************/

/**
 * The global, shared mpd context.
 */
static zend_always_inline mpd_context_t *php_decimal_context()
{
    return &DECIMAL_G(ctx);
}

/**
 * Sets the significand precision of a given decimal object.
 */
static zend_always_inline void php_decimal_set_precision(php_decimal_t *obj, zend_long prec)
{
    obj->prec = prec;
}

/**
 * Returns the significand precision of a given decimal object.
 */
static zend_always_inline zend_long php_decimal_get_precision(php_decimal_t *obj)
{
    return obj->prec;
}

/**
 * Returns true if the given precision is valid, false otherwise.
 */
static zend_always_inline zend_bool php_decimal_precision_is_valid(zend_long prec)
{
    return prec >= PHP_DECIMAL_MIN_PREC && prec <= PHP_DECIMAL_MAX_PREC;
}

/**
 * Checks that a given precision is valid, and returns immediately if it is not.
 */
#define PHP_DECIMAL_VALID_PRECISION_OR_RETURN(prec) do { \
    zend_long p = prec; \
    if (php_decimal_precision_is_valid(p) == false) { \
        php_decimal_precision_out_of_range(p); \
        return; \
    } \
} while (0)

/******************************************************************************/
/*                         ALLOC, INIT, FREE, CLONE                           */
/******************************************************************************/

/**
 * Resets all flags and allocates the data for a given MPD. We are using this
 * manual approach to avoid allocating an mpd_t when we allocate a decimal.
 *
 * We instead embed the struct itself, rather than a pointer to a new one.
 * This requires that we borrow some internals from mpdecimal to initialize an
 * already allocated mpd_t. This would usually be done by mpd_new.
 */
static void php_decimal_init_mpd(mpd_t *mpd)
{
    mpd->flags  = 0;
    mpd->exp    = 0;
    mpd->digits = 0;
    mpd->len    = 0;
    mpd->alloc  = MPD_MINALLOC;
    mpd->data   = mpd_alloc(MPD_MINALLOC, sizeof(mpd_uint_t));

    if (mpd->data == NULL) {
        php_decimal_memory_error();
    }
}

/**
 * Initializes an allocated decimal object.
 */
static void php_decimal_init(php_decimal_t *obj)
{
    php_decimal_init_mpd(PHP_DECIMAL_MPD(obj));
}

/**
 * Allocates a new php_decimal_t that has not been initialized. We don't want to
 * initialize a decimal until its constructor is called, so that we can check in
 * the constructor whether the object has already been initialized.
 */
static php_decimal_t *php_decimal_alloc()
{
    php_decimal_t *obj = ecalloc(1, sizeof(php_decimal_t));

    if (obj) {
#if PHP_VERSION_ID < 80300
        obj->std.handlers = &php_decimal_handlers;
#endif
        zend_object_std_init((zend_object *) obj, php_decimal_ce);
    } else {
        php_decimal_memory_error();
    }

    return obj;
}

/**
 * Creates a new decimal object, initialized to a given precision.
 */
static php_decimal_t *php_decimal_with_prec(zend_long prec)
{
    php_decimal_t *obj = php_decimal_alloc();

    php_decimal_init(obj);
    php_decimal_set_precision(obj, prec);

    return obj;
}

/**
 * Creates a new decimal object, initialized to the default precision.
 */
static zend_always_inline php_decimal_t *php_decimal()
{
    return php_decimal_with_prec(PHP_DECIMAL_DEFAULT_PRECISION);
}

/**
 * Creates a custom zend_object that is also an uninitialized decimal object.
 */
static zend_object *php_decimal_create_object(zend_class_entry *ce)
{
    return (zend_object *) php_decimal_alloc();
}

/**
 * Creates a copy of the given decimal object.
 */
static  php_decimal_t *php_decimal_create_copy(php_decimal_t *src)
{
    php_decimal_t *dst = php_decimal_with_prec(php_decimal_get_precision(src));

    mpd_copy(PHP_DECIMAL_MPD(dst), PHP_DECIMAL_MPD(src), php_decimal_context());

    return dst;
}

/**
 * Clones the given zval/zend_object, which must be a decimal object.
 */
#if PHP_VERSION_ID >= 80000
static zend_object *php_decimal_clone_obj(zend_object *obj)
{
    return (zend_object *) php_decimal_create_copy(O_DECIMAL_P(obj));
}
#else
static zend_object *php_decimal_clone_obj(zval *obj)
{
    return (zend_object *) php_decimal_create_copy(Z_DECIMAL_P(obj));
}
#endif

/**
 * Frees all internal memory used by a given decimal, but not object itself.
 */
static void php_decimal_release(php_decimal_t *obj)
{
    /* The mpd_t is embedded so will be freed along with the object. */
    if (PHP_DECIMAL_IS_INITIALIZED(obj)) {
        mpd_free(PHP_DECIMAL_MPD(obj)->data);
    }

    zend_object_std_dtor((zend_object *) obj);
}

/**
 * Frees all internal memory used by a given decimal.
 */
static void php_decimal_free(php_decimal_t *obj)
{
    php_decimal_release(obj);
    efree(obj);
}

/**
 * Free handler, should only free internal memory, not the object itself.
 */
static void php_decimal_free_object(zend_object *obj)
{
    php_decimal_release((php_decimal_t*) obj);
}


/******************************************************************************/
/*                                 ROUNDING                                   */
/******************************************************************************/

/**
 * This library supports both its own rounding constants and the PHP rounding
 * mode constants. The user should not have to wonder which constant to use.
 *
 * In order to support both, as well as some modes not supported by mpdecimal,
 * we need to convert the requested mode to an mpdecimal rounding mode.
 */
static php_decimal_rounding_t php_decimal_convert_to_mpd_rounding_mode(mpd_t *mpd, zend_long scale, php_decimal_rounding_t mode)
{
    switch (mode) {

        case PHP_DECIMAL_ROUND_UP:          return MPD_ROUND_UP;
        case PHP_DECIMAL_ROUND_DOWN:        return MPD_ROUND_DOWN;

        case PHP_DECIMAL_ROUND_CEILING:     return MPD_ROUND_CEILING;
        case PHP_DECIMAL_ROUND_FLOOR:       return MPD_ROUND_FLOOR;

        case PHP_DECIMAL_ROUND_HALF_UP:     return MPD_ROUND_HALF_UP;
        case PHP_DECIMAL_ROUND_HALF_DOWN:   return MPD_ROUND_HALF_DOWN;
        case PHP_DECIMAL_ROUND_HALF_EVEN:   return MPD_ROUND_HALF_EVEN;

        case PHP_DECIMAL_ROUND_TRUNCATE:    return MPD_ROUND_TRUNC;

        /* PHP constants */
        case PHP_ROUND_HALF_UP:             return MPD_ROUND_HALF_UP;
        case PHP_ROUND_HALF_DOWN:           return MPD_ROUND_HALF_DOWN;
        case PHP_ROUND_HALF_EVEN:           return MPD_ROUND_HALF_EVEN;

        /**
         * Special case for half-odd.
         *
         * This depends on the value's parity because half-odd is not
         * implemented by mpdecimal. We want to support the PHP constant, so we
         * need to adjust to a mode that is equivalent to an MPD rounding mode.
         */
        case PHP_ROUND_HALF_ODD:
        case PHP_DECIMAL_ROUND_HALF_ODD: {

            /* INF and NAN won't be rounded. */
            if (UNEXPECTED(mpd_isspecial(mpd))) {
                return MPD_ROUND_TRUNC;

            /**
             * Determine the integer parity at the point of rounding to determine
             * which way we should round to get to the nearest odd number.
             *
             * For example, 0.12345, rounded to 4 decimal places is on the 4.
             */
            } else {
                uint32_t status = 0;

                PHP_DECIMAL_TEMP_MPD(tmp);
                mpd_qshiftl(&tmp, mpd, scale, &status);
                mpd_qtrunc(&tmp, &tmp, php_decimal_context(), &status);

                /* An odd digit should round down towards itself. */
                mode = mpd_isodd(&tmp)
                    ? MPD_ROUND_HALF_DOWN
                    : MPD_ROUND_HALF_UP;

                mpd_del(&tmp);
                return mode;
            }
        }

        /* Couldn't determine a match, rounding mode is not supported. */
        default:
            php_decimal_unsupported_rounding_mode(mode);
            return 0;
    }
}

/**
 * Rounds a given mpd to a number of decimal places (scale), using a given
 * php decimal rounding mode. If the scale is beyond the number of decimal
 * places, trailing zeroes should be appended, increasing significance.
 */
static void php_decimal_round_mpd(mpd_t *res, mpd_t *mpd, zend_long scale, php_decimal_rounding_t mode)
{
    uint32_t status = 0;

    /* No need to round if the scale is beyond the number of decimal digits */
    if (-scale <= mpd->exp) {
        mpd_qcopy(res, mpd, &status);
        return;
    }

    mpd_qsetround(php_decimal_context(), php_decimal_convert_to_mpd_rounding_mode(mpd, scale, mode));
    mpd_qrescale(res, mpd, -scale, php_decimal_context(), &status);
    mpd_qsetround(php_decimal_context(), MPD_ROUND_HALF_EVEN);

    if (status & MPD_Invalid_operation) {
        php_decimal_failed_to_round();
    }
}

/**
 * Trims trailing zeroes in-place.
 */
static void php_decimal_trim_trailing_zeroes(php_decimal_t *obj)
{
    mpd_reduce(PHP_DECIMAL_MPD(obj), PHP_DECIMAL_MPD(obj), php_decimal_context());
}


/******************************************************************************/
/*                                CONVERSIONS                                 */
/******************************************************************************/

/**
 * Sets the value of a decimal object to infinity.
 */
static void php_decimal_set_inf(php_decimal_t *obj, zend_bool positive)
{
    mpd_set_infinity(PHP_DECIMAL_MPD(obj));
    mpd_set_sign(PHP_DECIMAL_MPD(obj), positive ? MPD_POS : MPD_NEG);
}

/**
 * Sets the value of an mpd to NAN.
 */
static void php_decimal_mpd_set_nan(mpd_t *mpd)
{
    mpd_set_qnan(mpd);
}

/**
 * Sets the value of a decimal object to NAN.
 */
static void php_decimal_set_nan(php_decimal_t *obj)
{
    php_decimal_mpd_set_nan(PHP_DECIMAL_MPD(obj));
}

/**
 * Parses a string to a given precision. Trailing zeroes are not preserved.
 */
static php_success_t php_decimal_mpd_set_string(mpd_t *mpd, zend_string *str, zend_long prec, zend_bool quiet)
{
    uint32_t status = 0;

    PHP_DECIMAL_WITH_PRECISION(prec, {
        mpd_qset_string(mpd, ZSTR_VAL(str), php_decimal_context(), &status);
    });

    /* Check that the conversion was successful. */
    if (status & MPD_Conversion_syntax) {
        if (!quiet) {
            php_decimal_failed_to_parse_string(str);
        }
        return FAILURE;
    }

    /* Check that we haven't lost data, ie. string wasn't parsed completely. */
    /* Can check MPD_Rounded too if we care about losing trailing zeroes. */
    if (status & MPD_Inexact) {
        php_decimal_loss_of_data_on_string_conversion();
    }

    return SUCCESS;
}

/**
 * Sets an mpd to a given double value. Will only be successful if the double is
 * a special value, ie INF, -INF and NAN.
 */
static php_success_t php_decimal_mpd_set_special_double(mpd_t *res, double dval)
{
    if (zend_isinf(dval)) {
        mpd_set_infinity(res);
        mpd_set_sign(res, dval > 0 ? MPD_POS : MPD_NEG);
        return SUCCESS;
    }

    if (zend_isnan(dval)) {
        mpd_set_qnan(res);
        return SUCCESS;
    }

    return FAILURE;
}

/**
 * Sets an mpd to a given double value. If the double is not a special value, it
 * will be cast to string first. This is useful because we don't want to parse
 * floats when constructing, but we do when comparing.
 */
static void php_decimal_mpd_set_double(mpd_t *res, double dval)
{
    zend_string *str;

    zval tmp;
    ZVAL_DOUBLE(&tmp, dval);

    str = zval_get_string(&tmp);
    php_decimal_mpd_set_string(res, str, PHP_DECIMAL_MAX_PREC, false);
    zend_string_free(str);
}

/**
 * Sets an mpd to a given long value. The precision is to determine whether data
 * was lost, eg. 123 with a precision of 2 would be 120.
 */
static void php_decimal_mpd_set_long(mpd_t *mpd, zend_long lval, zend_long prec)
{
    uint32_t status = 0;

    PHP_DECIMAL_WITH_PRECISION(prec, {
        mpd_qset_ssize(mpd, lval, php_decimal_context(), &status);
    });

    if (status & MPD_Rounded) {
        php_decimal_loss_of_data_on_long_conversion();
    }
}

/**
 * Sets the value of a given decimal object to zero.
 */
static void php_decimal_set_zero(php_decimal_t *obj)
{
    mpd_zerocoeff(PHP_DECIMAL_MPD(obj));
}

/**
 * Attempts to parse a non-object value as a decimal, using a given precision.
 */
static php_success_t php_decimal_parse_scalar_ex(mpd_t *res, zval *value, zend_long prec, zend_bool quiet)
{
    switch (Z_TYPE_P(value)) {
        case IS_STRING:
            return php_decimal_mpd_set_string(res, Z_STR_P(value), prec, quiet);

        case IS_LONG:
            php_decimal_mpd_set_long(res, Z_LVAL_P(value), prec);
            return SUCCESS;

        /* Should only consider special values here - float is not supported. */
        case IS_DOUBLE: {
            if (php_decimal_mpd_set_special_double(res, Z_DVAL_P(value)) == SUCCESS) {
                return SUCCESS;
            }
        }

        default: {
            if (!quiet) {
                php_decimal_unsupported_type(value);
            }
            php_decimal_mpd_set_nan(res);
            return FAILURE;
        }
    }
}

/**
 * Attempts to parse a zval with a non-decimal value.
 */
static php_success_t php_decimal_parse_scalar(mpd_t *mpd, zval *value, zend_long prec)
{
    return php_decimal_parse_scalar_ex(mpd, value, prec, false);
}

/**
 * Attempts to parse a zval with a non-decimal value, ignoring exceptions.
 */
static php_success_t php_decimal_parse_scalar_quiet(mpd_t *mpd, zval *value, zend_long prec)
{
    return php_decimal_parse_scalar_ex(mpd, value, prec, true);
}

/**
 * Attempts to parse a mixed value into a decimal object, using the decimal
 * object's internal mpd and precision. The precision of the result should be
 * the maximum of its already-set precision and the precision of the parsed
 * value if that value is also decimal object. Scalar values should assume that
 * the target precision is already set on the result.
 */
static php_success_t php_decimal_parse_into(php_decimal_t *obj, zval *value)
{
    /* Check if is non-decimal, attempt to parse as scalar */
    if (!Z_IS_DECIMAL_P(value)) {
        return php_decimal_parse_scalar(PHP_DECIMAL_MPD(obj), value, php_decimal_get_precision(obj));

    /* Decimal object, set max precision, copy internal value. */
    } else {
        zend_long prec1 = php_decimal_get_precision(obj);
        zend_long prec2 = php_decimal_get_precision(Z_DECIMAL_P(value));

        php_decimal_set_precision(obj, MAX(prec1, prec2));
        mpd_copy(PHP_DECIMAL_MPD(obj), Z_DECIMAL_MPD_P(value), php_decimal_context());
        return SUCCESS;
    }
}

/**
 * Converts a decimal object to double. Exceptions are thrown if the value of
 * the decimal is outside of the range of a double. There is no warning or error
 * if the value of the decimal can not be represented accurately.
 */
static double php_decimal_to_double(php_decimal_t *obj)
{
    mpd_t *mpd = PHP_DECIMAL_MPD(obj);

    if (mpd_iszero(mpd)) {
        return 0;

    } else if (mpd_isspecial(mpd)) {
        if (mpd_isqnan(mpd)) {
            return php_get_nan();
        }

        /* Infinity */
        return mpd_ispositive(mpd)
            ? +php_get_inf()
            : -php_get_inf();

    } else {
        /* Convert the decimal to a string first. */
        char *str = mpd_to_sci(mpd, 1);

        /* Attempt to parse the string to double. */
        double dval = zend_strtod(str, NULL);

        /* Check if limits were reached. */
        if (zend_isinf(dval)) {
            php_decimal_floating_point_overflow();

        } else if (dval == 0 && !mpd_iszero(mpd)) {
            php_decimal_floating_point_underflow();
        }

        mpd_free(str);
        return dval;
    }
}

/**
 * Converts a decimal object to long, aka PHP int. An exception will be thrown
 * if the decimal is outside of the range of a PHP integer.
 *
 * TODO: PHP magically turn ints into floats when they get too big. Is that
 *       something we should consider here also?
 */
static zend_long php_decimal_to_long(php_decimal_t *obj)
{
    const mpd_t *mpd = PHP_DECIMAL_MPD(obj);

    uint32_t  status = 0;
    zend_long result = 0;

    /* PHP converts to zero but that does not make sense and could hide bugs. */
    if (UNEXPECTED(mpd_isspecial(mpd))) {
        php_decimal_integer_from_special_is_not_defined();
        return 0;
    }

    if (mpd_isinteger(mpd)) {
        result = mpd_qget_ssize(mpd, &status);

    /* Truncate to an integer value first, otherwise mpd_qget_ssize fails. */
    } else {
        PHP_DECIMAL_TEMP_MPD(tmp);
        mpd_qtrunc(&tmp, mpd, php_decimal_context(), &status);

        result = mpd_qget_ssize(&tmp, &status);
        mpd_del(&tmp);
    }

    /* Check for overflow. */
    if (status & MPD_Invalid_operation) {
        php_decimal_integer_overflow();
        return 0;
    }

    return result;
}

/**
 * Converts an mpd to string, following PHP convensions.
 */
static zend_string *php_decimal_mpd_to_string(mpd_t *mpd)
{
    char          *str;
    zend_string   *res;
    mpd_ssize_t    len;

    PHP_DECIMAL_CHECK_SPECIAL_STRING_RETURN(mpd);

    len = mpd_to_sci_size(&str, mpd, 1);
    res = zend_string_init(str, len, 0);
    mpd_free(str);

    return res;
}

/**
 * Converts a given php_decimal_t to a zend_string.
 */
static zend_string *php_decimal_to_string(php_decimal_t *obj)
{
    return php_decimal_mpd_to_string(PHP_DECIMAL_MPD(obj));
}

/**
 * Formats an mpd, used by toFixed.
 */
static zend_string *php_decimal_format_mpd(mpd_t *mpd, zend_long places, zend_bool commas, php_decimal_rounding_t mode)
{
    char        *str;
    zend_string *res;
    smart_str    fmt = {0};

    if (places < 0) {
        php_decimal_negative_decimal_places_not_defined();
    }

    PHP_DECIMAL_TEMP_MPD(tmp);
    PHP_DECIMAL_CHECK_SPECIAL_STRING_RETURN(mpd);

    /* Round first */
    php_decimal_round_mpd(&tmp, mpd, places, mode);

    /* Always show negative sign, but never positive. */
    smart_str_appendc(&fmt, '-');

    /* Specify whether we want to separate thousands with a comma. */
    if (commas) {
        smart_str_appendc(&fmt, ',');
    }

    /* Specify how many decimal places we want. */
    smart_str_appendc(&fmt, '.');
    smart_str_append_long(&fmt, places);

    /* Fixed point representation. */
    smart_str_appendc(&fmt, 'F');
    smart_str_0(&fmt);

    str = mpd_format(&tmp, ZSTR_VAL(fmt.s), php_decimal_context());
    res = zend_string_init(str, strlen(str), 0);

    smart_str_free(&fmt);
    mpd_free(str);
    mpd_del(&tmp);

    return res;
}

/**
 * Formats a decimal object, used by toFixed.
 */
static zend_string *php_decimal_format(php_decimal_t *obj, zend_long places, zend_bool commas, php_decimal_rounding_t mode)
{
    return php_decimal_format_mpd(PHP_DECIMAL_MPD(obj), places, commas, mode);
}


/******************************************************************************/
/*                                OPERATIONS                                  */
/******************************************************************************/

static int php_decimal_signum(const mpd_t *mpd)
{
    if (UNEXPECTED(mpd_isnan(mpd))) {
        php_decimal_sign_of_nan_is_not_defined();
        return 0;
    }

    return mpd_iszero(mpd) ? 0 : mpd_arith_sign(mpd);
}

/**
 * Sets the result of res to op1 + op2, using the precision of res.
 *
 * We are not concerned with invalid operations such as -INF + INF because PHP
 * quietly uses NAN. The intention is to be as consistent with PHP as possible.
 */
static void php_decimal_add(php_decimal_t *res, mpd_t *op1, mpd_t *op2)
{
    uint32_t status = 0;

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qadd(PHP_DECIMAL_MPD(res), op1, op2, php_decimal_context(), &status);
    });
}

/**
 * Sets the result of res to op1 - op2, using the precision of res.
 *
 * We are not concerned with invalid operations such as -INF - INF because PHP
 * quietly uses NAN. The intention is to be as consistent with PHP as possible.
 */
static void php_decimal_sub(php_decimal_t *res, mpd_t *op1, mpd_t *op2)
{
    uint32_t status = 0;

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qsub(PHP_DECIMAL_MPD(res), op1, op2, php_decimal_context(), &status);
    });
}

/**
 * Sets the result of res to op1 * op2, using the precision of res.
 *
 * We are not concerned with invalid operations such as INF * NAN because PHP
 * quietly uses NAN. The intention is to be as consistent with PHP as possible.
 */
static void php_decimal_mul(php_decimal_t *res, mpd_t *op1, mpd_t *op2)
{
    uint32_t status = 0;

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qmul(PHP_DECIMAL_MPD(res), op1, op2, php_decimal_context(), &status);
    });
}

/**
 * Sets the result of res to op1 / op2, using the precision of res.
 *
 * Division by zero will throw an exception, but undefined division such as
 * INF / NAN will quietly return NAN.
 */
static void php_decimal_div(php_decimal_t *res, mpd_t *op1, mpd_t *op2)
{
    uint32_t status = 0;

    if (mpd_iszero(op2)) {
        php_decimal_division_by_zero_error();
        php_decimal_set_inf(res, mpd_ispositive(op1));
        return;
    }

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qdiv(PHP_DECIMAL_MPD(res), op1, op2, php_decimal_context(), &status);
    });
}

/**
 * Sets res to the decimal remainder after dividing op1 by op2. This should not
 * be used as the equivalent of % because modulo is an integer operation.
 *
 * In order to stay consistent with div, invalid operations should quietly
 * return NAN, even though PHP throws for all invalid modulo operations.
 */
static void php_decimal_rem(php_decimal_t *res, mpd_t *op1, mpd_t *op2)
{
    uint32_t status = 0;

    if (mpd_iszero(op2)) {
        php_decimal_division_by_zero_error();
        php_decimal_set_inf(res, mpd_ispositive(op1));
        return;
    }

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qrem(PHP_DECIMAL_MPD(res), op1, op2, php_decimal_context(), &status);
    });
}

/**
 * Sets res to the integer remainder after dividing op1 by op2. This is the
 * equivalent of %, ie. integer mod.
 *
 * In order to stay consistent with div, invalid operations should quietly
 * return NAN, even though PHP throws for all invalid modulo operations.
 */
static void php_decimal_mod(php_decimal_t *res, mpd_t *op1, mpd_t *op2)
{
    PHP_DECIMAL_TEMP_MPD(tmp1);
    PHP_DECIMAL_TEMP_MPD(tmp2);

    /* Truncate op1 if not an integer, use res as temp */
    if (!mpd_isinteger(op1) && !mpd_isspecial(op1)) {
        mpd_trunc(&tmp1, op1, php_decimal_context());
        op1 = &tmp1;
    }

    /* Truncate op2 if not an integer. */
    if (!mpd_isinteger(op2) && !mpd_isspecial(op2)) {
        mpd_trunc(&tmp2, op2, php_decimal_context());
        op2 = &tmp2;
    }

    php_decimal_rem(res, op1, op2);

    mpd_del(&tmp1);
    mpd_del(&tmp2);
}

/**
 * Sets rem to the result of raising base to the power of exp. Anything to the
 * power of zero should equal 1.
 */
static void php_decimal_pow(php_decimal_t *res, mpd_t *base, mpd_t *exp)
{
    uint32_t status = 0;

    if (mpd_iszero(exp)) {
        php_decimal_mpd_set_long(PHP_DECIMAL_MPD(res), 1, php_decimal_get_precision(res));
        return;
    }

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qpow(PHP_DECIMAL_MPD(res), base, exp, php_decimal_context(), &status);
    });
}

/**
 * Sets res to the natural log of op1.
 */
static void php_decimal_ln(php_decimal_t *res, mpd_t *op1)
{
    uint32_t status = 0;

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qln(PHP_DECIMAL_MPD(res), op1, php_decimal_context(), &status);
    });
}

/**
 * Sets res to e to the power of exp.
 */
static void php_decimal_exp(php_decimal_t *res, mpd_t *exp)
{
    uint32_t status = 0;

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qexp(PHP_DECIMAL_MPD(res), exp, php_decimal_context(), &status);
    });
}

/**
 * Sets res to the base-10 log of op1.
 */
static void php_decimal_log10(php_decimal_t *res, mpd_t *op1)
{
    uint32_t status = 0;

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qlog10(PHP_DECIMAL_MPD(res), op1, php_decimal_context(), &status);
    });
}

/**
 * Sets res to the square root of op1. Negative values should quietly return
 * NAN, and special numbers should be copied as is.
 */
static void php_decimal_sqrt(php_decimal_t *res, mpd_t *op1)
{
    uint32_t status = 0;

    if (mpd_isnegative(op1)) {
        php_decimal_set_nan(res);
        return;
    }

    if (mpd_isspecial(op1)) {
        mpd_qcopy(PHP_DECIMAL_MPD(res), op1, &status);
        return;
    }

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qsqrt(PHP_DECIMAL_MPD(res), op1, php_decimal_context(), &status);
    });
}

/**
 * Sets res to the floor of op1, ie. rounded down towards negative infinity.
 */
static void php_decimal_floor(php_decimal_t *res, mpd_t *op1)
{
    uint32_t status = 0;
    if (mpd_isspecial(op1)) {
        mpd_qcopy(PHP_DECIMAL_MPD(res), op1, &status);
        return;
    }
    mpd_qfloor(PHP_DECIMAL_MPD(res), op1, php_decimal_context(), &status);
}

/**
 * Sets res to the ceiling of op1, ie. rounded up towards positive infinity.
 */
static void php_decimal_ceil(php_decimal_t *res, mpd_t *op1)
{
    uint32_t status = 0;
    if (mpd_isspecial(op1)) {
        mpd_qcopy(PHP_DECIMAL_MPD(res), op1, &status);
        return;
    }
    mpd_qceil(PHP_DECIMAL_MPD(res), op1, php_decimal_context(), &status);
}

/**
 * Sets res to the integer value of op1, ie. discard all digits behind the
 * decimal point. The result is guaranteed to be an integer, unless op1 is a
 * special number in which case it should be copied as is.
 */
static void php_decimal_truncate(php_decimal_t *res, mpd_t *op1)
{
    uint32_t status = 0;
    if (mpd_isspecial(op1)) {
        mpd_qcopy(PHP_DECIMAL_MPD(res), op1, &status);
        return;
    }
    mpd_qtrunc(PHP_DECIMAL_MPD(res), op1, php_decimal_context(), &status);
}

/**
 * Sets res to the value of op1 after shifting its decimal point.
 */
static void php_decimal_shift(php_decimal_t *res, mpd_t *op1, zend_long places)
{
    uint32_t status = 0;

    PHP_DECIMAL_TEMP_MPD(exp);
    php_decimal_mpd_set_long(&exp, places, php_decimal_get_precision(res));

    PHP_DECIMAL_WITH_PRECISION(php_decimal_get_precision(res), {
        mpd_qscaleb(PHP_DECIMAL_MPD(res), op1, &exp, php_decimal_context(), &status);
    });

    mpd_del(&exp);
}

/**
 * Sets res to the absolute value of op1.
 */
static void php_decimal_abs(php_decimal_t *res, mpd_t *op1)
{
    uint32_t status = 0;
    mpd_qcopy_abs(PHP_DECIMAL_MPD(res), op1, &status);
}

/**
 * Sets res to the value of op1 with its sign inverted.
 */
static void php_decimal_negate(php_decimal_t *res, mpd_t *op1)
{
    uint32_t status = 0;
    mpd_qcopy_negate(PHP_DECIMAL_MPD(res), op1, &status);
}

/**
 * Sets res to the sum of all values in the given array, returning the number of
 * values that were counted or -1 if the operation failed.
 */
static zend_long php_decimal_sum_array(php_decimal_t *res, HashTable *arr)
{
    zval *value;
    php_decimal_set_zero(res);

    ZEND_HASH_FOREACH_VAL(arr, value) {
        mpd_t *op1;
        mpd_t *op2;
        zend_long prec;
        PHP_DECIMAL_TEMP_MPD(tmp);

        if (Z_IS_DECIMAL_P(value)) {
            op1  = PHP_DECIMAL_MPD(res);
            op2  = Z_DECIMAL_MPD_P(value);
            prec = MAX(php_decimal_get_precision(Z_DECIMAL_P(value)), php_decimal_get_precision(res));

        } else {
            op1  = PHP_DECIMAL_MPD(res);
            op2  = &tmp;
            prec = php_decimal_get_precision(res);

            /* Attempt to parse the value, otherwise bail out. */
            if (php_decimal_parse_scalar(&tmp, value, prec) == FAILURE) {
                mpd_del(&tmp);
                return -1;
            }
        }

        /* Set precision, do add. */
        php_decimal_set_precision(res, prec);
        php_decimal_add(res, op1, op2);
        mpd_del(&tmp);
    }
    ZEND_HASH_FOREACH_END();

    return zend_hash_num_elements(arr);
}

/**
 * Sets res to the sum of all values in the given traversable, returning the
 * number of values that were counted or -1 if the operation failed.
 */
static zend_long php_decimal_sum_traversable(php_decimal_t *res, zval *values)
{
    zend_long count = 0;
    php_decimal_set_zero(res);

    /* Get the iterator from the object. */
    zend_object_iterator *iterator = Z_OBJCE_P(values)->get_iterator(Z_OBJCE_P(values), values, 0);
    if (EG(exception)) {
        goto done;
    }

    /* Attempt to rewind the iterator. */
    iterator->index = 0;
    if (iterator->funcs->rewind) {
        iterator->funcs->rewind(iterator);
        if (EG(exception)) {
            goto done;
        }
    }

    /* While the iterator has a value for us... */
    while (iterator->funcs->valid(iterator) == SUCCESS) {
        mpd_t *op1;
        mpd_t *op2;
        zend_long prec;
        PHP_DECIMAL_TEMP_MPD(tmp);

        /* Attempt to access the current value of the iterator. */
        zval *value = iterator->funcs->get_current_data(iterator);

        if (EG(exception)) {
            goto done;
        }

        if (Z_IS_DECIMAL_P(value)) {
            op1  = PHP_DECIMAL_MPD(res);
            op2  = Z_DECIMAL_MPD_P(value);
            prec = MAX(php_decimal_get_precision(Z_DECIMAL_P(value)), php_decimal_get_precision(res));

        } else {
            op1 = PHP_DECIMAL_MPD(res);
            op2  = &tmp;
            prec = php_decimal_get_precision(res);

            /* Attempt to parse the value, otherwise bail out. */
            if (php_decimal_parse_scalar(&tmp, value, prec) == FAILURE) {
                mpd_del(&tmp);
                goto done;
            }
        }

        /* Set precision, do add. */
        php_decimal_set_precision(res, prec);
        php_decimal_add(res, op1, op2);
        mpd_del(&tmp);

        /* Update count, move iterator forward. */
        count++;
        iterator->index++;
        iterator->funcs->move_forward(iterator);
        if (EG(exception)) {
            goto done;
        }
    }

  done:
    if (iterator) {
        zend_iterator_dtor(iterator);
    }

    return EG(exception) ? -1 : count;
}

/**
 * Sets res to the sum of all given values, returning the number of values that
 * were counted, or -1 if the operation failed.
 */
static zend_long php_decimal_sum(php_decimal_t *res, zval *values)
{
    /* Check array first */
    if (Z_TYPE_P(values) == IS_ARRAY) {
        return php_decimal_sum_array(res, Z_ARR_P(values));
    }

    /* Check traversable object */
    if (Z_TYPE_P(values) == IS_OBJECT && instanceof_function(Z_OBJCE_P(values), zend_ce_traversable)) {
        return php_decimal_sum_traversable(res, values);
    }

    php_decimal_expected_iterable(values);
    return -1;
}

/**
 * Sets res to the average of all given values, or NAN if the operation failed.
 */
static php_success_t php_decimal_avg(php_decimal_t *res, zval *values)
{
    zend_long count = php_decimal_sum(res, values);

    if (count == 0) {
        php_decimal_set_zero(res);
        return SUCCESS;
    }

    if (count > 0) {
        PHP_DECIMAL_TEMP_MPD(tmp);
        php_decimal_mpd_set_long(&tmp, count, PHP_DECIMAL_MAX_PREC);
        php_decimal_div(res, PHP_DECIMAL_MPD(res), &tmp);
        mpd_del(&tmp);
        return SUCCESS;
    }

    php_decimal_set_nan(res);
    return FAILURE;
}

/**
 * Converts a zend opcode to a binary arithmetic function pointer.
 *
 * Returns NULL if a function is not mapped.
 */
static  php_decimal_binary_op_t php_decimal_get_operation_for_opcode(zend_uchar opcode)
{
    switch (opcode) {
        case ZEND_ADD: return php_decimal_add;
        case ZEND_SUB: return php_decimal_sub;
        case ZEND_MUL: return php_decimal_mul;
        case ZEND_DIV: return php_decimal_div;
        case ZEND_MOD: return php_decimal_mod;
        case ZEND_POW: return php_decimal_pow;
        default:
            return NULL;
    }
}

/**
 * Attempts a binary operation on two zval's, writing the result to res.
 *
 * We don't know which of the operands is a decimal, if not both.
 */
static void php_decimal_do_binary_op(php_decimal_binary_op_t op, php_decimal_t *res, zval *op1, zval *op2)
{
    mpd_t *mpd1;
    mpd_t *mpd2;

    zend_long prec;
    PHP_DECIMAL_TEMP_MPD(tmp);

    if (Z_IS_DECIMAL_P(op1)) {
        if (Z_IS_DECIMAL_P(op2)) {
            /* Both operands are decimal */
            mpd1 = Z_DECIMAL_MPD_P(op1);
            mpd2 = Z_DECIMAL_MPD_P(op2);
            prec = MAX(php_decimal_get_precision(Z_DECIMAL_P(op1)), php_decimal_get_precision(Z_DECIMAL_P(op2)));

        } else {
            /* Only op1 is decimal, so attempt to parse op2. */
            mpd1 = Z_DECIMAL_MPD_P(op1);
            mpd2 = &tmp;
            prec = php_decimal_get_precision(Z_DECIMAL_P(op1));

            /* Failing to parse will throw an exception, so set NAN defer.*/
            if (php_decimal_parse_scalar(mpd2, op2, prec) == FAILURE) {
                php_decimal_set_nan(res);
                mpd_del(&tmp);
                return;
            }
        }
    } else {
        /* op1 is NOT a decimal, so op2 must be. */
        mpd1 = &tmp;
        mpd2 = Z_DECIMAL_MPD_P(op2);
        prec = php_decimal_get_precision(Z_DECIMAL_P(op2));

        /* Failing to parse will throw an exception, so set NAN defer.*/
        if (php_decimal_parse_scalar(mpd1, op1, prec) == FAILURE) {
            php_decimal_set_nan(res);
            mpd_del(&tmp);
            return;
        }
    }

    /* Parsed successfully, so we can set the parsed precision and do the op. */
    php_decimal_set_precision(res, prec);
    op(res, mpd1, mpd2);
    mpd_del(&tmp);
}



/******************************************************************************/
/*                               SERIALIZATION                                */
/******************************************************************************/

/**
 * Serialize
 */
static php_success_t php_decimal_serialize(zval *object, unsigned char **buffer, size_t *length, zend_serialize_data *data)
{
    zval tmp;
    smart_str buf = {0};
    php_decimal_t *obj = Z_DECIMAL_P(object);

    php_serialize_data_t serialize_data = (php_serialize_data_t) data;
    PHP_VAR_SERIALIZE_INIT(serialize_data);

    /* Serialize the internal value as a string. */
    ZVAL_STR(&tmp, php_decimal_to_string(obj));
    php_var_serialize(&buf, &tmp, &serialize_data);
    zval_ptr_dtor(&tmp);

    /* Serialize the precision as an integer. */
    ZVAL_LONG(&tmp, php_decimal_get_precision(obj));
    php_var_serialize(&buf, &tmp, &serialize_data);

    PHP_VAR_SERIALIZE_DESTROY(serialize_data);

    *buffer = (unsigned char *) estrndup(ZSTR_VAL(buf.s), ZSTR_LEN(buf.s));
    *length = ZSTR_LEN(buf.s);

    smart_str_free(&buf);

    return SUCCESS;
}

/**
 * Unserialize
 */
static php_success_t php_decimal_unserialize(zval *obj, zend_class_entry *ce, const unsigned char *buffer, size_t length, zend_unserialize_data *data)
{
    zval *value;
    zval *prec;

    php_decimal_t *res = php_decimal();

    php_unserialize_data_t unserialize_data = (php_unserialize_data_t) data;

    const unsigned char *pos = buffer;
    const unsigned char *end = buffer + length;

    PHP_VAR_UNSERIALIZE_INIT(unserialize_data);

    /* Unserialize internal decimal value, which was serialized as a string. */
    value = var_tmp_var(&unserialize_data);
    if (!php_var_unserialize(value, &pos, end, &unserialize_data) || Z_TYPE_P(value) != IS_STRING) {
        goto error;
    }

    /* Unserialize precision, which was serialized as an integer. */
    prec = var_tmp_var(&unserialize_data);
    if (!php_var_unserialize(prec, &pos, end, &unserialize_data) || Z_TYPE_P(prec) != IS_LONG) {
        goto error;
    }

    /* Check that we've parsed the entire serialized string. */
    if (pos != end) {
        goto error;
    }

    /* Check precision is valid. */
    if (php_decimal_precision_is_valid(Z_LVAL_P(prec)) == false) {
        php_decimal_precision_out_of_range(Z_LVAL_P(prec));
        goto error;
    }

    /* Set the precision. */
    php_decimal_set_precision(res, Z_LVAL_P(prec));

    /* Attempt to parse the unserialized string, quietly, delegate to local error. */
    if (php_decimal_mpd_set_string(PHP_DECIMAL_MPD(res), Z_STR_P(value), Z_LVAL_P(prec), true) == FAILURE) {
        goto error;
    }

    /* Success! Set as zval and return. */
    ZVAL_DECIMAL(obj, res);
    PHP_VAR_UNSERIALIZE_DESTROY(unserialize_data);
    return SUCCESS;

error:
    php_decimal_release(res);
    PHP_VAR_UNSERIALIZE_DESTROY(unserialize_data);
    php_decimal_unserialize_error();
    return FAILURE;
}


/******************************************************************************/
/*                                COMPARISON                                  */
/******************************************************************************/

/**
 * Normalizes the result of a decimal comparison to be either -1, 0 or 1. This
 * is necessary because anything compared to NAN should be 1, even when operands
 * are flipped ie op2 <=> op1.
 */
static int php_decimal_normalize_compare_result(int result, int invert)
{
    switch (result) {
        case  0:
        case  1:
        case -1:
            return invert ? -result : result;

        case PHP_DECIMAL_COMPARE_NAN:
            return 1;

        case PHP_DECIMAL_COMPARE_UNKNOWN:
            return invert ? -1 : 1;

        /* Should not be possible. */
        default:
            return 1;
    }
}

/**
 * Attempt to compare op1 and op2. It's possible that the comparison is not
 * defined (when comparing to NAN), so we should return the special comparison
 * flag that indicates an undefined result. Returning 1 here is no good because
 * operations like "greater than" would be true for NAN.
 */
static int php_decimal_compare_mpd(mpd_t *op1, mpd_t *op2)
{
    uint32_t status = 0;

    int result = mpd_qcmp(op1, op2, &status);

    if (UNEXPECTED(status & MPD_Invalid_operation)) {
        return PHP_DECIMAL_COMPARE_NAN;
    }

    return result;
}

/**
 * Compares two decimals using value-only comparison, precision is ignored.
 */
static int php_decimal_compare(php_decimal_t *op1, php_decimal_t *op2)
{
    int result = php_decimal_compare_mpd(PHP_DECIMAL_MPD(op1), PHP_DECIMAL_MPD(op2));

    if (result == 0) {
        zend_long prec1 = php_decimal_get_precision(op1);
        zend_long prec2 = php_decimal_get_precision(op2);

        return prec1 == prec2 ? 0 : (prec1 < prec2 ? -1 : 1);
    }

    return result;
}

/**
 * Compares a decimal object to a double.
 */
static int php_decimal_compare_to_double(php_decimal_t *obj, double dval)
{
    if (UNEXPECTED(zend_isnan(dval))) {
        return PHP_DECIMAL_COMPARE_NAN;

    } else {
        int result;
        PHP_DECIMAL_TEMP_MPD(tmp);

        php_decimal_mpd_set_double(&tmp, dval);
        result = php_decimal_compare_mpd(PHP_DECIMAL_MPD(obj), &tmp);

        mpd_del(&tmp);
        return result;
    }
}

/**
 * Compares a decimal to a non-decimal zval.
 */
static int php_decimal_compare_to_scalar(php_decimal_t *obj, zval *op2)
{
    while (1) {
        switch (Z_TYPE_P(op2)) {
            case IS_NULL:
            case IS_FALSE:
                return 1;

            case IS_TRUE:
                return 0;

            /* Allow comparing to float. */
            case IS_DOUBLE:
                return php_decimal_compare_to_double(obj, Z_DVAL_P(op2));

            /* TODO not sure if this is necessary... */
            case IS_REFERENCE:
                op2 = Z_REFVAL_P(op2);
                continue;

            /* Attempt to parse the value, then compare. */
            /* Return unknown on failure to avoid false "greater than" indicator. */
            default: {
                int result = PHP_DECIMAL_COMPARE_UNKNOWN;
                PHP_DECIMAL_TEMP_MPD(tmp);

                if (EXPECTED(php_decimal_parse_scalar_quiet(&tmp, op2, PHP_DECIMAL_MAX_PREC) == SUCCESS)) {
                    result = php_decimal_compare_mpd(PHP_DECIMAL_MPD(obj), &tmp);
                }

                mpd_del(&tmp);
                return result;
            }
        }
    }
}

/**
 * Compares a decimal to a zval that could also be a decimal.
 */
static int php_decimal_compare_to_zval(php_decimal_t *op1, zval *op2)
{
    if (Z_IS_DECIMAL_P(op2)) {
        return php_decimal_compare(op1, Z_DECIMAL_P(op2));
    }

    return php_decimal_compare_to_scalar(op1, op2);
}


/******************************************************************************/
/*                              OBJECT HANDLERS                               */
/******************************************************************************/

/**
 * Compares two zval's, one of which must be a decimal. This is the function
 * used by the compare handler, as well as compareTo.
 */
#if PHP_VERSION_ID >= 80000
static int php_decimal_compare_zval_to_zval(zval *op1, zval *op2)
{
    int result;
    int invert;

    if (Z_IS_DECIMAL_P(op1)) {
        result = php_decimal_compare_to_zval(Z_DECIMAL_P(op1), op2);
        invert = 0;
    } else {
        result = php_decimal_compare_to_zval(Z_DECIMAL_P(op2), op1);
        invert = 1;
    }

    return php_decimal_normalize_compare_result(result, invert);
}
#else
static php_success_t php_decimal_compare_zval_to_zval(zval *retval, zval *op1, zval *op2)
{
    int result;
    int invert;

    if (Z_IS_DECIMAL_P(op1)) {
        result = php_decimal_compare_to_zval(Z_DECIMAL_P(op1), op2);
        invert = 0;
    } else {
        result = php_decimal_compare_to_zval(Z_DECIMAL_P(op2), op1);
        invert = 1;
    }

    ZVAL_LONG(retval, php_decimal_normalize_compare_result(result, invert));
    return SUCCESS;
}
#endif

/**
 * Compares decimal between two zvals/decimals. This is the function used as between.
 */
static php_success_t php_decimal_compare_between_left_and_right(zval *retval, zval *target, zval *leftOp, zval *rightOp)
{
    int resultLeft;
    int resultRight;

    if (Z_IS_DECIMAL_P(leftOp)) {
        resultLeft = php_decimal_compare(Z_DECIMAL_P(target), Z_DECIMAL_P(leftOp));
    } else {
        resultLeft = php_decimal_compare_to_zval(Z_DECIMAL_P(target), leftOp);
    }

    if (resultLeft == -1) {
        ZVAL_BOOL(retval, 0);

        return SUCCESS;
    }

    if (Z_IS_DECIMAL_P(rightOp)) {
        resultRight = php_decimal_compare(Z_DECIMAL_P(target), Z_DECIMAL_P(rightOp));
    } else {
        resultRight = php_decimal_compare_to_zval(Z_DECIMAL_P(target), rightOp);
    }

    if (resultRight == 1) {
        ZVAL_BOOL(retval, 0);

        return SUCCESS;
    }

    ZVAL_BOOL(retval, 1);

    return SUCCESS;
}

/**
 * var_dump, print_r etc.
 */
#if PHP_VERSION_ID >= 80000
static HashTable *php_decimal_get_debug_info(zend_object *obj, int *is_temp)
{
    zval tmp;
    HashTable *debug_info;

    ALLOC_HASHTABLE(debug_info);
    zend_hash_init(debug_info, 2, NULL, ZVAL_PTR_DTOR, 0);

    ZVAL_STR(&tmp, php_decimal_to_string(O_DECIMAL_P(obj)));
    zend_hash_str_update(debug_info, "value", sizeof("value") - 1, &tmp);

    ZVAL_LONG(&tmp, php_decimal_get_precision(O_DECIMAL_P(obj)));
    zend_hash_str_update(debug_info, "precision", sizeof("precision") - 1, &tmp);

    *is_temp = 1;

    return debug_info;
}
#else
static HashTable *php_decimal_get_debug_info(zval *obj, int *is_temp)
{
    zval tmp;
    HashTable *debug_info;

    ALLOC_HASHTABLE(debug_info);
    zend_hash_init(debug_info, 2, NULL, ZVAL_PTR_DTOR, 0);

    ZVAL_STR(&tmp, php_decimal_to_string(Z_DECIMAL_P(obj)));
    zend_hash_str_update(debug_info, "value", sizeof("value") - 1, &tmp);

    ZVAL_LONG(&tmp, php_decimal_get_precision(Z_DECIMAL_P(obj)));
    zend_hash_str_update(debug_info, "precision", sizeof("precision") - 1, &tmp);

    *is_temp = 1;

    return debug_info;
}
#endif

/**
 * Cast to string, int, float or bool.
 */
#if PHP_VERSION_ID >= 80000
static php_success_t php_decimal_cast_object(zend_object *obj, zval *result, int type)
{
    switch (type) {
        case IS_STRING:
            ZVAL_STR(result, php_decimal_to_string(O_DECIMAL_P(obj)));
            return SUCCESS;

        case IS_LONG:
            ZVAL_LONG(result, php_decimal_to_long(O_DECIMAL_P(obj)));
            return SUCCESS;

        case IS_DOUBLE:
            ZVAL_DOUBLE(result, php_decimal_to_double(O_DECIMAL_P(obj)));
            return SUCCESS;

        case _IS_BOOL:
            ZVAL_BOOL(result, 1); /* Objects are always true */
            return SUCCESS;

        default:
            return FAILURE;
    }
}
#else
static php_success_t php_decimal_cast_object(zval *obj, zval *result, int type)
{
    switch (type) {
        case IS_STRING:
            ZVAL_STR(result, php_decimal_to_string(Z_DECIMAL_P(obj)));
            return SUCCESS;

        case IS_LONG:
            ZVAL_LONG(result, php_decimal_to_long(Z_DECIMAL_P(obj)));
            return SUCCESS;

        case IS_DOUBLE:
            ZVAL_DOUBLE(result, php_decimal_to_double(Z_DECIMAL_P(obj)));
            return SUCCESS;

        case _IS_BOOL:
            ZVAL_BOOL(result, 1); /* Objects are always true */
            return SUCCESS;

        default:
            return FAILURE;
    }
}
#endif

/**
 * Operator overloading.
 *
 * We don't know which of op1 and op2 is a decimal object (if not both).
 */
static php_success_t php_decimal_do_operation(zend_uchar opcode, zval *result, zval *op1, zval *op2)
{
    zval op1_copy;
    php_decimal_binary_op_t op = php_decimal_get_operation_for_opcode(opcode);

    /* Unsupported op type. */
    if (UNEXPECTED(op == NULL)) {
        return FAILURE;
    }

    /* This allows for assign syntax, ie. $op1 /= $op2 */
    if (op1 == result) {
        ZVAL_COPY_VALUE(&op1_copy, op1);
        op1 = &op1_copy;
    }

    /* Attempt operation. */
    ZVAL_DECIMAL(result, php_decimal());
    php_decimal_do_binary_op(op, Z_DECIMAL_P(result), op1, op2);

    /**
     * Something went wrong so unset the result, but we don't want the engine to
     * carry on trying to cast the decimal, so we return success.
     */
    if (UNEXPECTED(EG(exception))) {
        zval_ptr_dtor(result);
        ZVAL_UNDEF(result);
        return SUCCESS;
    }

    if (op1 == &op1_copy) {
        zval_dtor(op1);
    }

    return SUCCESS;
}

#if PHP_VERSION_ID >= 80000
/**
 * Object property read - not supported.
 */
static zval *php_decimal_read_property(zend_object *object, zend_string *member, int type, void **cache_slot, zval *rv)
{
    php_decimal_object_properties_not_supported();
    return &EG(uninitialized_zval);
}

/**
 *   Object property write - not supported.
 */
static zval* php_decimal_write_property(zend_object *object, zend_string *member, zval *value, void **cache_slot)
{
    php_decimal_object_properties_not_supported();
    return &EG(uninitialized_zval);
}

/**
 * Object property isset/empty - not supported.
 */
static int php_decimal_has_property(zend_object *object, zend_string *member, int has_set_exists, void **cache_slot)
{
    php_decimal_object_properties_not_supported();
    return 0;
}

/**
 * Object property unset - not supported.
 */
static void php_decimal_unset_property(zend_object *object, zend_string *member, void **cache_slot)
{
    php_decimal_object_properties_not_supported();
}
#else
/**
 * Object property read - not supported.
 */
static zval *php_decimal_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv)
{
    php_decimal_object_properties_not_supported();
    return &EG(uninitialized_zval);
}

/**
 * Object property write - not supported.
 */
static zval *php_decimal_write_property(zval *object, zval *member, zval *value, void **cache_slot)
{
    php_decimal_object_properties_not_supported();
    return &EG(uninitialized_zval);
}

/**
 * Object property isset/empty - not supported.
 */
static int php_decimal_has_property(zval *object, zval *member, int has_set_exists, void **cache_slot)
{
    php_decimal_object_properties_not_supported();
    return 0;
}

/**
 * Object property unset - not supported.
 */
static void php_decimal_unset_property(zval *object, zval *member, void **cache_slot)
{
    php_decimal_object_properties_not_supported();
}
#endif

/******************************************************************************/
/*                            PARAMETER PARSING                               */
/******************************************************************************/

/**
 * No parameters expected, bail out if there were some.
 */
#define PHP_DECIMAL_PARAMS_PARSE_NONE() \
    if (zend_parse_parameters_none() == FAILURE) { \
        return; \
    }

/**
 * Parse a binary operation (op1 OP op2).
 */
#define PHP_DECIMAL_PARSE_BINARY_OP(op) do { \
    php_decimal_t *res = php_decimal(); \
    zval          *op2 = NULL; \
    \
    ZEND_PARSE_PARAMETERS_START(1, 1) \
        Z_PARAM_ZVAL(op2) \
    ZEND_PARSE_PARAMETERS_END(); \
    php_decimal_do_binary_op(op, res, getThis(), op2); \
    RETURN_DECIMAL(res); \
} while (0)

/**
 * Parse a unary operation (OP op1).
 */
#define PHP_DECIMAL_PARSE_UNARY_OP(op) do { \
    php_decimal_t *obj = THIS_DECIMAL(); \
    php_decimal_t *res = php_decimal_with_prec(php_decimal_get_precision(obj)); \
    \
    PHP_DECIMAL_PARAMS_PARSE_NONE(); \
    \
    op(res, PHP_DECIMAL_MPD(obj)); \
    RETURN_DECIMAL(res); \
} while(0)


/******************************************************************************/
/*                              PHP CLASS METHODS                             */
/******************************************************************************/

/**
 * Decimal::__construct
 */
PHP_DECIMAL_ARGINFO(__construct, 0)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_LONG(precision)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(__construct)
{
    zval *value = NULL;
    zend_long prec = 0;

    /* Check if already constructed, because decimals are immutable */
    if (PHP_DECIMAL_IS_INITIALIZED(THIS_DECIMAL())) {
        php_decimal_constructor_already_called();
        return;
    }

    ZEND_PARSE_PARAMETERS_START(0, 2)
        Z_PARAM_OPTIONAL
        Z_PARAM_ZVAL(value)
#if PHP_VERSION_ID >= 80000
        Z_PARAM_LONG(prec)
#else
        Z_PARAM_STRICT_LONG(prec)
#endif
    ZEND_PARSE_PARAMETERS_END();
    {
        php_decimal_t *obj = THIS_DECIMAL();

        /* No value or precision given: init using default precision, set zero. */
        if (value == NULL) {
            php_decimal_init(obj);
            php_decimal_set_precision(obj, PHP_DECIMAL_DEFAULT_PRECISION);
            php_decimal_set_zero(obj);

        /* Value given, but not precision: init using default precision, parse. */
        } else if (ZEND_NUM_ARGS() == 1) {
            php_decimal_init(obj);
            php_decimal_set_precision(obj, PHP_DECIMAL_DEFAULT_PRECISION);
            php_decimal_parse_into(obj, value);

        /* Both value and precision given: validate, init, parse. */
        } else {
            PHP_DECIMAL_VALID_PRECISION_OR_RETURN(prec);
            php_decimal_init(obj);
            php_decimal_set_precision(obj, prec);
            php_decimal_parse_into(obj, value);
        }
    }
}

/**
 * Decimal::add
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(add, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(add)
{
    PHP_DECIMAL_PARSE_BINARY_OP(php_decimal_add);
}

/**
 * Decimal::sub
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(sub, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(sub)
{
    PHP_DECIMAL_PARSE_BINARY_OP(php_decimal_sub);
}

/**
 * Decimal::mul
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(mul, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(mul)
{
    PHP_DECIMAL_PARSE_BINARY_OP(php_decimal_mul);
}

/**
 * Decimal::div
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(div, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(div)
{
    PHP_DECIMAL_PARSE_BINARY_OP(php_decimal_div);
}

/**
 * Decimal::mod
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(mod, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(mod)
{
    PHP_DECIMAL_PARSE_BINARY_OP(php_decimal_mod);
}

/**
 * Decimal::pow
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(pow, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(pow)
{
    PHP_DECIMAL_PARSE_BINARY_OP(php_decimal_pow);
}

/**
 * Decimal::rem
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(rem, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(rem)
{
    PHP_DECIMAL_PARSE_BINARY_OP(php_decimal_rem);
}

/**
 * Decimal::ln
 * Decimal::log
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(ln, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(ln)
{
    PHP_DECIMAL_PARSE_UNARY_OP(php_decimal_ln);
}

/**
 * Decimal::exp
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(exp, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(exp)
{
    PHP_DECIMAL_PARSE_UNARY_OP(php_decimal_exp);
}

/**
 * Decimal::log10
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(log10, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(log10)
{
    PHP_DECIMAL_PARSE_UNARY_OP(php_decimal_log10);
}

/**
 * Decimal::sqrt
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(sqrt, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(sqrt)
{
    PHP_DECIMAL_PARSE_UNARY_OP(php_decimal_sqrt);
}

/**
 * Decimal::round
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(round, 0)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(places)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(rounding)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(round)
{
    php_decimal_t *obj = THIS_DECIMAL();
    php_decimal_t *res = php_decimal_with_prec(php_decimal_get_precision(obj));

    zend_long places   = 0;
    zend_long rounding = PHP_DECIMAL_DEFAULT_ROUNDING;

    ZEND_PARSE_PARAMETERS_START(0, 2)
        Z_PARAM_OPTIONAL
        #if PHP_VERSION_ID >= 80000
        Z_PARAM_LONG(places)
        Z_PARAM_LONG(rounding)
        #else
        Z_PARAM_STRICT_LONG(places)
        Z_PARAM_STRICT_LONG(rounding)
        #endif
    ZEND_PARSE_PARAMETERS_END();

    php_decimal_round_mpd(PHP_DECIMAL_MPD(res), PHP_DECIMAL_MPD(obj), places, rounding);
    RETURN_DECIMAL(res);
}

/**
 * Decimal::floor
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(floor, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(floor)
{
    PHP_DECIMAL_PARSE_UNARY_OP(php_decimal_floor);
}

/**
 * Decimal::ceil
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(ceil, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(ceil)
{
    PHP_DECIMAL_PARSE_UNARY_OP(php_decimal_ceil);
}


/**
 * Decimal::truncate
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(truncate, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(truncate)
{
    PHP_DECIMAL_PARSE_UNARY_OP(php_decimal_truncate);
}

/**
 * Decimal::shift
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(shift, 1)
PHP_DECIMAL_ARGINFO_LONG(places)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(shift)
{
    php_decimal_t *obj = THIS_DECIMAL();
    php_decimal_t *res = php_decimal_with_prec(php_decimal_get_precision(obj));

    zend_long places = 0;

    ZEND_PARSE_PARAMETERS_START(1, 1)
        #if PHP_VERSION_ID >= 80000
        Z_PARAM_LONG(places)
        #else
        Z_PARAM_STRICT_LONG(places)
        #endif
    ZEND_PARSE_PARAMETERS_END();

    php_decimal_shift(res, PHP_DECIMAL_MPD(obj), places);
    RETURN_DECIMAL(res);
}

/**
 * Decimal::trim
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(trim, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(trim)
{
    php_decimal_t *obj = THIS_DECIMAL();
    php_decimal_t *res = php_decimal_create_copy(obj);

    PHP_DECIMAL_PARAMS_PARSE_NONE();

    php_decimal_trim_trailing_zeroes(res);
    RETURN_DECIMAL(res);
}

/**
 * Decimal::precision
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(precision, IS_LONG, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(precision)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_LONG(php_decimal_get_precision(THIS_DECIMAL()));
}

/**
 * Decimal::signum
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(signum, IS_LONG, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(signum)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_LONG(php_decimal_signum(THIS_MPD()));
}

/**
 * Decimal::parity
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(parity, IS_LONG, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(parity)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();

    if (UNEXPECTED(mpd_isspecial(THIS_MPD()))) {
        RETURN_LONG(1);

    } else {
        PHP_DECIMAL_TEMP_MPD(tmp);
        mpd_trunc(&tmp, THIS_MPD(), php_decimal_context());
        RETVAL_LONG(mpd_isodd(&tmp));
        mpd_del(&tmp);
    }
}

/**
 * Decimal::abs
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(abs, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(abs)
{
    PHP_DECIMAL_PARSE_UNARY_OP(php_decimal_abs);
}

/**
 * Decimal::negate
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(negate, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(negate)
{
    PHP_DECIMAL_PARSE_UNARY_OP(php_decimal_negate);
}

/**
 * Decimal::isEven
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(isEven, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(isEven)
{
    mpd_t *mpd = THIS_MPD();
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_BOOL(mpd_isinteger(mpd) && !mpd_isodd(mpd));
}


/**
 * Decimal::isOdd
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(isOdd, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(isOdd)
{
    mpd_t *mpd = THIS_MPD();
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_BOOL(mpd_isinteger(mpd) && mpd_isodd(mpd));
}


/**
 * Decimal::isPositive
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(isPositive, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(isPositive)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();

    mpd_t *mpd = THIS_MPD();

    RETURN_BOOL(!mpd_isnan(mpd) && mpd_ispositive(mpd));
}

/**
 * Decimal::isNegative
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(isNegative, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(isNegative)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();

    mpd_t *mpd = THIS_MPD();

    RETURN_BOOL(!mpd_isnan(mpd) && mpd_isnegative(mpd));
}

/**
 * Decimal::isNaN
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(isNaN, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(isNaN)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_BOOL(mpd_isqnan(THIS_MPD()));
}

/**
 * Decimal::isInf
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(isInf, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(isInf)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_BOOL(mpd_isinfinite(THIS_MPD()));
}

/**
 * Decimal::isInteger
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(isInteger, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(isInteger)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_BOOL(mpd_isinteger(THIS_MPD()));
}

/**
 * Decimal::isZero
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(isZero, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(isZero)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_BOOL(mpd_iszero(THIS_MPD()));
}

/**
 * Decimal::toFixed
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(toFixed, IS_STRING, 0)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(places)
PHP_DECIMAL_ARGINFO_OPTIONAL_BOOL(commas)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(rounding)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(toFixed)
{
    zend_long places   = 0;
    zend_bool commas   = false;
    zend_long rounding = PHP_DECIMAL_DEFAULT_ROUNDING;

    ZEND_PARSE_PARAMETERS_START(0, 3)
        Z_PARAM_OPTIONAL
        #if PHP_VERSION_ID >= 80000
        Z_PARAM_LONG(places)
        #else
        Z_PARAM_STRICT_LONG(places)
        #endif
        Z_PARAM_BOOL(commas)
        #if PHP_VERSION_ID >= 80000
        Z_PARAM_LONG(rounding)
        #else
        Z_PARAM_STRICT_LONG(rounding)
        #endif
    ZEND_PARSE_PARAMETERS_END();

    RETURN_STR(php_decimal_format(THIS_DECIMAL(), places, commas, rounding));
}


/**
 * Decimal::__toString
 * Decimal::toString
 * Decimal::jsonSerialize
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(toString, IS_STRING, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(toString)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_STR(php_decimal_to_string(THIS_DECIMAL()));
}

/**
 * Decimal::toInt
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(toInt, IS_LONG, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(toInt)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_LONG(php_decimal_to_long(THIS_DECIMAL()));
}

/**
 * Decimal::toFloat
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(toFloat, IS_DOUBLE, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(toFloat)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_DOUBLE(php_decimal_to_double(THIS_DECIMAL()));
}

/**
 * Decimal::copy
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(copy, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(copy)
{
    PHP_DECIMAL_PARAMS_PARSE_NONE();
    RETURN_DECIMAL(php_decimal_create_copy(THIS_DECIMAL()));
}

/**
 * Decimal::equals
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(equals, _IS_BOOL, 1)
PHP_DECIMAL_ARGINFO_ZVAL(other)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(equals)
{
    zval *op2 = NULL;

    ZEND_PARSE_PARAMETERS_START(1, 1)
        Z_PARAM_ZVAL(op2)
    ZEND_PARSE_PARAMETERS_END();

    RETURN_BOOL(php_decimal_compare_to_zval(THIS_DECIMAL(), op2) == 0);
}

/**
 * Decimal::compareTo
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(compareTo, IS_LONG, 1)
PHP_DECIMAL_ARGINFO_ZVAL(other)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(compareTo)
{
    zval *op2 = NULL;

    ZEND_PARSE_PARAMETERS_START(1, 1)
        Z_PARAM_ZVAL(op2)
    ZEND_PARSE_PARAMETERS_END();

    #if PHP_VERSION_ID >= 80000
    RETURN_LONG(php_decimal_compare_zval_to_zval(getThis(), op2));
    #else
    php_decimal_compare_zval_to_zval(return_value, getThis(), op2);
    #endif
}

/**
 * Decimal::between
 */
PHP_DECIMAL_ARGINFO_RETURN_TYPE(between, _IS_BOOL, 1)
PHP_DECIMAL_ARGINFO_ZVAL(op1)
PHP_DECIMAL_ARGINFO_ZVAL(op2)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(between)
{
    zval *opLeft = NULL;
    zval *opRight = NULL;

    ZEND_PARSE_PARAMETERS_START(2, 2)
        Z_PARAM_ZVAL(opLeft)
        Z_PARAM_ZVAL(opRight)
    ZEND_PARSE_PARAMETERS_END();

    php_decimal_compare_between_left_and_right(return_value, getThis(), opLeft, opRight);
}

/**
 * Decimal::sum
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(sum, 1)
PHP_DECIMAL_ARGINFO_ZVAL(values)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(precision)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(sum)
{
    php_decimal_t     *res    = php_decimal();
    zval              *values = NULL;
    zend_long prec   = PHP_DECIMAL_DEFAULT_PRECISION;

    ZEND_PARSE_PARAMETERS_START(1, 2)
        Z_PARAM_ZVAL(values)
        Z_PARAM_OPTIONAL
        #if PHP_VERSION_ID >= 80000
        Z_PARAM_LONG(prec)
        #else
        Z_PARAM_STRICT_LONG(prec)
        #endif
    ZEND_PARSE_PARAMETERS_END();

    PHP_DECIMAL_VALID_PRECISION_OR_RETURN(prec);
    php_decimal_set_precision(res, prec);
    php_decimal_sum(res, values);
    RETURN_DECIMAL(res);
}

/**
 * Decimal::avg
 */
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(avg, 1)
PHP_DECIMAL_ARGINFO_ZVAL(values)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(precision)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(avg)
{
    php_decimal_t     *res    = php_decimal();
    zval              *values = NULL;
    zend_long prec   = PHP_DECIMAL_DEFAULT_PRECISION;

    ZEND_PARSE_PARAMETERS_START(1, 2)
        Z_PARAM_ZVAL(values)
        Z_PARAM_OPTIONAL
        #if PHP_VERSION_ID >= 80000
        Z_PARAM_LONG(prec)
        #else
        Z_PARAM_STRICT_LONG(prec)
        #endif
    ZEND_PARSE_PARAMETERS_END();

    PHP_DECIMAL_VALID_PRECISION_OR_RETURN(prec);
    php_decimal_set_precision(res, prec);
    php_decimal_avg(res, values);
    RETURN_DECIMAL(res);
}

/******************************************************************************/
/*                                 CLASS ENTRY                                */
/******************************************************************************/

static zend_function_entry decimal_methods[] = {
    PHP_DECIMAL_ME(__construct)
    PHP_DECIMAL_ME(copy)

    PHP_DECIMAL_ME(add)
    PHP_DECIMAL_ME(sub)
    PHP_DECIMAL_ME(mul)
    PHP_DECIMAL_ME(div)
    PHP_DECIMAL_ME(rem)
    PHP_DECIMAL_ME(mod)
    PHP_DECIMAL_ME(pow)

    PHP_DECIMAL_ME(ln)
    PHP_DECIMAL_ME(exp)
    PHP_DECIMAL_ME(log10)
    PHP_DECIMAL_ME(sqrt)

    PHP_DECIMAL_ME(floor)
    PHP_DECIMAL_ME(ceil)
    PHP_DECIMAL_ME(truncate)

    PHP_DECIMAL_ME(round)
    PHP_DECIMAL_ME(shift)
    PHP_DECIMAL_ME(trim)
    PHP_DECIMAL_ME(precision)

    PHP_DECIMAL_ME(signum)
    PHP_DECIMAL_ME(parity)

    PHP_DECIMAL_ME(abs)
    PHP_DECIMAL_ME(negate)

    PHP_DECIMAL_ME(isEven)
    PHP_DECIMAL_ME(isOdd)

    PHP_DECIMAL_ME(isPositive)
    PHP_DECIMAL_ME(isNegative)

    PHP_DECIMAL_ME(isNaN)
    PHP_DECIMAL_ME(isInf)
    PHP_DECIMAL_ME(isInteger)
    PHP_DECIMAL_ME(isZero)

    PHP_DECIMAL_ME(toFixed)
    PHP_DECIMAL_ME(toString)
    PHP_DECIMAL_ME(toInt)
    PHP_DECIMAL_ME(toFloat)

    PHP_DECIMAL_ME(equals)
    PHP_DECIMAL_ME(compareTo)
    PHP_DECIMAL_ME(between)

    /* Static methods */
    PHP_DECIMAL_STATIC_ME(sum)
    PHP_DECIMAL_STATIC_ME(avg)

    /* Aliases:    Alias          Defined */
    PHP_DECIMAL_AL(__toString,    toString)
    PHP_DECIMAL_AL(jsonSerialize, toString)
    PHP_FE_END
};

/**
 * Decimal functions.
 */
static zend_function_entry decimal_functions[] = {
    PHP_FE_END
};

/**
 * Sets the object handlers.
 */
static void php_decimal_register_class_handlers()
{
    memcpy(&php_decimal_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));

    /**
     * No need for an offset because we're casting back and forth between
     * zend_object and php_decimal. Malloc should know the size of the block so
     * when the engine frees the zend_object, it will free the php_decimal. We
     * also don't have any class properties and the class is final.
     */
    php_decimal_handlers.offset = 0;

    php_decimal_handlers.free_obj         = php_decimal_free_object;
    php_decimal_handlers.clone_obj        = php_decimal_clone_obj;
    php_decimal_handlers.cast_object      = php_decimal_cast_object;
    php_decimal_handlers.compare          = php_decimal_compare_zval_to_zval;
    php_decimal_handlers.do_operation     = php_decimal_do_operation;
    php_decimal_handlers.get_debug_info   = php_decimal_get_debug_info;
    php_decimal_handlers.read_property    = php_decimal_read_property;
    php_decimal_handlers.write_property   = php_decimal_write_property;
    php_decimal_handlers.has_property     = php_decimal_has_property;
    php_decimal_handlers.unset_property   = php_decimal_unset_property;
}

/**
 * Registers the class entry and constants.
 */
static void php_decimal_register_class_entry()
{
    zend_class_entry ce;
    INIT_CLASS_ENTRY(ce, PHP_DECIMAL_FQCN, decimal_methods);

    php_decimal_ce = zend_register_internal_class(&ce);
    php_decimal_ce->ce_flags      |= ZEND_ACC_FINAL;
    php_decimal_ce->create_object  = php_decimal_create_object;
    php_decimal_ce->serialize      = php_decimal_serialize;
    php_decimal_ce->unserialize    = php_decimal_unserialize;

#if PHP_VERSION_ID >= 80300
    php_decimal_ce->default_object_handlers = &php_decimal_handlers;
#endif

    zend_class_implements(php_decimal_ce, 1, php_json_serializable_ce);

    PHP_DECIMAL_LONG_CONSTANT("ROUND_UP",           PHP_DECIMAL_ROUND_UP);
    PHP_DECIMAL_LONG_CONSTANT("ROUND_DOWN",         PHP_DECIMAL_ROUND_DOWN);
    PHP_DECIMAL_LONG_CONSTANT("ROUND_CEILING",      PHP_DECIMAL_ROUND_CEILING);
    PHP_DECIMAL_LONG_CONSTANT("ROUND_FLOOR",        PHP_DECIMAL_ROUND_FLOOR);
    PHP_DECIMAL_LONG_CONSTANT("ROUND_HALF_UP",      PHP_DECIMAL_ROUND_HALF_UP);
    PHP_DECIMAL_LONG_CONSTANT("ROUND_HALF_DOWN",    PHP_DECIMAL_ROUND_HALF_DOWN);
    PHP_DECIMAL_LONG_CONSTANT("ROUND_HALF_EVEN",    PHP_DECIMAL_ROUND_HALF_EVEN);
    PHP_DECIMAL_LONG_CONSTANT("ROUND_HALF_ODD",     PHP_DECIMAL_ROUND_HALF_ODD);
    PHP_DECIMAL_LONG_CONSTANT("ROUND_TRUNCATE",     PHP_DECIMAL_ROUND_TRUNCATE);

    PHP_DECIMAL_LONG_CONSTANT("DEFAULT_PRECISION",  PHP_DECIMAL_DEFAULT_PRECISION);
    PHP_DECIMAL_LONG_CONSTANT("DEFAULT_ROUNDING",   PHP_DECIMAL_DEFAULT_ROUNDING);

    PHP_DECIMAL_LONG_CONSTANT("MIN_PRECISION", PHP_DECIMAL_MIN_PREC);
    PHP_DECIMAL_LONG_CONSTANT("MAX_PRECISION", PHP_DECIMAL_MAX_PREC);
}

/******************************************************************************/
/*                                    INI                                     */
/******************************************************************************/

PHP_INI_BEGIN()
PHP_INI_END()

/******************************************************************************/
/*                                   MODULE                                   */
/******************************************************************************/

ZEND_DECLARE_MODULE_GLOBALS(decimal)

static void php_decimal_init_globals(zend_decimal_globals *g)
{
    memset(g, 0, sizeof(zend_decimal_globals));
}

/**
 * Module entry
 */
zend_module_entry decimal_module_entry = {
    STANDARD_MODULE_HEADER,
    PHP_DECIMAL_EXTNAME,
    decimal_functions,
    PHP_MINIT(decimal),
    PHP_MSHUTDOWN(decimal),
    PHP_RINIT(decimal),
    PHP_RSHUTDOWN(decimal),
    PHP_MINFO(decimal),
    PHP_DECIMAL_VERSION,
    STANDARD_MODULE_PROPERTIES
};

/**
 * Module information displayed by phpinfo()
 */
PHP_MINFO_FUNCTION(decimal)
{
    php_info_print_table_start();
    php_info_print_table_row(2, "decimal support", "enabled");
    php_info_print_table_row(2, "decimal version", PHP_DECIMAL_VERSION);
    php_info_print_table_row(2, "libmpdec version", MPD_VERSION);
    php_info_print_table_end();

    DISPLAY_INI_ENTRIES();
}

/**
 * Set custom allocators.
 */
static void *php_decimal_mpd_malloc(size_t size)
{
    return emalloc(size);
}

static void *php_decimal_mpd_calloc(size_t nmemb, size_t size)
{
    return ecalloc(nmemb, size);
}

static void *php_decimal_mpd_realloc(void *ptr, size_t size)
{
    return erealloc(ptr, size);
}

static void php_decimal_mpd_free(void *ptr)
{
    efree(ptr);
}

/**
 * The second Opcache pass will convert numeric string constants to float,
 * so statements like `$decimal * "0.75"` will throw because floats are not
 * supported. Otherwise, this conversion will be transparent which means you
 * are using float internally when your code uses a string.
 *
 * Disabling it gives us guaranteed consistency at a small performance cost.
 */
static void php_decimal_disable_opcache_pass2()
{
    zend_long level = INI_INT("opcache.optimization_level");

    if (level) {
        zend_string *key = zend_string_init(ZEND_STRL("opcache.optimization_level"), 1);
        zend_string *val = strpprintf(0, "0x%08X", (unsigned int) (level & ~2));

        zend_alter_ini_entry(key, val, ZEND_INI_SYSTEM, ZEND_INI_STAGE_ACTIVATE);
        zend_string_release(key);
        zend_string_release(val);
    }
}

/**
 * Module startup
 */
PHP_MINIT_FUNCTION(decimal)
{
    php_decimal_register_class_entry();
    php_decimal_register_class_handlers();

    ZEND_INIT_MODULE_GLOBALS(decimal, php_decimal_init_globals, NULL);

    /* Set guaranteed minimum number of coefficient words based on default prec. */
    mpd_setminalloc(2 * ((PHP_DECIMAL_DEFAULT_PRECISION + MPD_RDIGITS - 1) / MPD_RDIGITS));

    /* Set custom memory allocation and trap handler functions. */
    mpd_callocfunc  = php_decimal_mpd_calloc;
    mpd_mallocfunc  = php_decimal_mpd_malloc;
    mpd_reallocfunc = php_decimal_mpd_realloc;
    mpd_free        = php_decimal_mpd_free;
    mpd_traphandler = php_decimal_mpd_traphandler;

    return SUCCESS;
}

/**
 * Module shutdown
 */
PHP_MSHUTDOWN_FUNCTION(decimal)
{
    return SUCCESS;
}

/**
 * Request startup
 */
PHP_RINIT_FUNCTION(decimal)
{
#if defined(COMPILE_DL_DECIMAL) && defined(ZTS)
    ZEND_TSRMLS_CACHE_UPDATE();
#endif
    php_decimal_disable_opcache_pass2();

    /* Initialize the shared context */
    mpd_defaultcontext(php_decimal_context());

    /* Set default rounding */
    mpd_qsettraps(php_decimal_context(), PHP_DECIMAL_TRAPS);
    mpd_qsetround(php_decimal_context(), PHP_DECIMAL_DEFAULT_ROUNDING);

    return SUCCESS;
}

/**
 * Request shutdown
 */
PHP_RSHUTDOWN_FUNCTION(decimal)
{
    return SUCCESS;
}

#ifdef COMPILE_DL_DECIMAL
#ifdef ZTS
    ZEND_TSRMLS_CACHE_DEFINE();
#endif
    ZEND_GET_MODULE(decimal)
#endif