-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecimal.c
2326 lines (2141 loc) · 58.2 KB
/
decimal.c
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
/*
* decimal.c - implementation of Decimal,
* a multi-precision decimal arithmetic library
*
* Copyright (C) 2003-2010 Tadashi Saito
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Ruby License. See the file "COPYING" for
* more details.
*/
#include <ctype.h>
#include <float.h>
#define _ISOC99_SOURCE
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <ruby.h>
#ifdef HAVE_RUBY_UTIL_H
#include <ruby/util.h>
#else
#include <util.h>
#endif
/*
* unfortunately, few copies of Integer functions
* are needed from original Ruby
*/
#include INUM_SOURCE_FILE
/*
* INUM_* macros: receive both Fixnum and Bignum,
* to operate any types of Integers transparently
*/
#define INUM_PLUS(a, b) \
(FIXNUM_P(a) ? fix_plus(a, b) : rb_big_plus(a, b))
#define INUM_MINUS(a, b) \
(FIXNUM_P(a) ? fix_minus(a, b) : rb_big_minus(a, b))
#define INUM_MUL(a, b) \
(FIXNUM_P(a) ? fix_mul(a, b) : rb_big_mul(a, b))
#define INUM_DIV(a, b) \
(FIXNUM_P(a) ? fix_div(a, b) : rb_big_div(a, b))
#define INUM_DIVMOD(a, b) \
(FIXNUM_P(a) ? fix_divmod(a, b) : rb_big_divmod(a, b))
#define INUM_POW(a, b) \
(FIXNUM_P(a) ? fix_pow(a, b) : rb_big_pow(a, b))
#define INUM_EQ(a, b) \
(FIXNUM_P(a) ? fix_equal(a, b) : rb_big_eq(a, b))
#define INUM_CMP(a, b) \
(FIXNUM_P(a) ? fix_cmp(a, b) : rb_big_cmp(a, b))
#define INUM_GT(a, b) (FIX2INT(INUM_CMP(a, b)) > 0)
#define INUM_UMINUS(n) \
(FIXNUM_P(n) ? LONG2NUM(-FIX2LONG(n)) : rb_big_uminus(n))
#define INUM_HASH(n) \
(FIXNUM_P(n) ? rb_obj_id(n) : rb_big_hash(n))
#define INUM2STR(n) \
(FIXNUM_P(n) ? rb_fix2str(n, 10) : rb_big2str(n, 10))
#define INUM_ODD_P(n) \
(FIXNUM_P(n) ? fix_odd_p(n) : rb_big_odd_p(n))
/* implementation-independent INUM_* macros */
#define INUM_INC(n) do { n = INUM_PLUS(n, INT2FIX(1)); } while (0)
#define INUM_DEC(n) do { n = INUM_MINUS(n, INT2FIX(1)); } while (0)
#define INUM_ZERO_P(n) (FIXNUM_P(n) && FIX2LONG(n) == 0)
#define INUM_NEGATIVE_P(n) (FIXNUM_P(n) ? FIX2LONG(n) < 0 : RBIGNUM_NEGATIVE_P(n))
#define INUM_BOTTOMDIG(n) (FIXNUM_P(n) ? FIX2LONG(n) % 10 : \
!rb_bigzero_p(n) ? FIX2INT(rb_big_modulo(n, INT2FIX(10))) : 0)
/* the body */
typedef struct {
VALUE inum;
long scale;
} Decimal;
/* singleton objects for NaN, +Infinity, -Infinity */
static Decimal *const DEC_NaN = (Decimal *)1;
static Decimal *const DEC_PINF = (Decimal *)3;
static Decimal *const DEC_NINF = (Decimal *)7;
/* and their representation as Ruby objects */
static VALUE VALUE_NaN, VALUE_PINF, VALUE_NINF;
#define CHECK_NAN_WITH_VAL(v, retval) do { \
if (v == VALUE_NaN) return retval; } while (0)
#define CHECK_NAN2_WITH_VAL(v1, v2, retval) do { \
if (v1 == VALUE_NaN || v2 == VALUE_NaN) return retval; } while (0)
#define CHECK_NAN(v) CHECK_NAN_WITH_VAL(v, VALUE_NaN)
#define CHECK_NAN2(v1, v2) CHECK_NAN2_WITH_VAL(v1, v2, VALUE_NaN)
/* special constants - i.e. non-zero and non-fixnum */
/* used for signed zeros that never meet any fixnums nor normal VALUEs */
static const VALUE DEC_PZERO = 2, DEC_NZERO = 6;
#define dec_pzero(scale) WrapDecimal(dec_raw_new(DEC_PZERO, scale))
#define dec_nzero(scale) WrapDecimal(dec_raw_new(DEC_NZERO, scale))
#define DEC_ISINF(d) ((d) == DEC_PINF || (d) == DEC_NINF)
#define DEC_VALUE_ISINF(v) ((v) == VALUE_PINF || (v) == VALUE_NINF)
/* immediate means non-finite */
#define DEC_IMMEDIATE_P(d) (DEC_ISINF(d) || (d) == DEC_NaN)
/* special signed zeros */
#define INUM_SPZERO_P(n) ((n) == DEC_PZERO || (n) == DEC_NZERO)
#define DEC_ZERO_P(d) INUM_SPZERO_P((d)->inum)
/* use internally in to_f */
static Decimal *DEC_DBL_MIN = NULL, *DEC_DBL_MAX = NULL;
static VALUE INUM_DBL_MAX = Qnil;
#define GET_DEC_DBL_MAX() (DEC_DBL_MAX != NULL ? DEC_DBL_MAX : \
(DEC_DBL_MAX = dbl_threshold_to_dec(DBL_MAX)))
#define GET_DEC_DBL_MIN() (DEC_DBL_MIN != NULL ? DEC_DBL_MIN : \
(DEC_DBL_MIN = dbl_threshold_to_dec(DBL_MIN)))
#define GET_INUM_DBL_MAX() (INUM_DBL_MAX != Qnil ? INUM_DBL_MAX : \
dbl_threshold_to_inum(DBL_MAX, &INUM_DBL_MAX))
/*
* all rounding modes
*/
static VALUE ROUND_CEILING;
static VALUE ROUND_DOWN;
static VALUE ROUND_FLOOR;
static VALUE ROUND_HALF_DOWN;
static VALUE ROUND_HALF_EVEN;
static VALUE ROUND_HALF_UP;
static VALUE ROUND_UP;
static VALUE ROUND_UNNECESSARY;
#define GetDecimal(obj, d) do { \
Data_Get_Struct(obj, Decimal, d); \
if (d == NULL) rb_raise(rb_eArgError, "uninitialized Decimal object"); \
} while (0)
#define WrapDecimal(d) Data_Wrap_Struct(cDecimal, dec_mark, dec_free, d)
#define WrapStatic(d) Data_Wrap_Struct(cDecimal, NULL, NULL, d)
#define DECIMAL_P(d) (CLASS_OF(d) == cDecimal)
static VALUE cDecimal;
static VALUE eDomainError;
static VALUE eArithmeticError;
/* mark if d->inum is a Bignum */
static void
dec_mark(void *p)
{
const Decimal *const d = p;
if (d == NULL) return; /* uninitialized object */
if (!FIXNUM_P(d->inum) && !INUM_SPZERO_P(d->inum)) {
rb_gc_mark(d->inum); /* mark a Bignum */
}
}
#ifndef DEBUG
#define dec_free (-1) /* just xfree() the objects */
#else
static void
dec_free(void *p)
{
static void *prev = NULL;
if (p == prev) {
fprintf(stderr, "dec_free(): double-free occurred on %p\n", p);
}
xfree(p);
prev = p;
}
#endif
static inline Decimal *
dec_raw_new(VALUE inum, long scale)
{
Decimal *d = ALLOC(Decimal);
d->inum = inum;
d->scale = scale;
return d;
}
static Decimal *
inum_to_dec(VALUE x)
{
return dec_raw_new(INUM_ZERO_P(x) ? DEC_PZERO : x, 0);
}
static VALUE
cstr_to_inum(VALUE str)
{
return rb_cstr_to_inum((const char *)str, 10, Qtrue);
}
static VALUE
invalid_str(VALUE arg)
{
VALUE *assoc = (VALUE *)arg;
xfree((char *)assoc[0]);
rb_invalid_str((const char *)assoc[1], "Decimal");
return Qnil; /* not reached */
}
static Decimal *
cstr_to_dec(const char *str)
{
char *const s = strdup(str);
char *ss;
long scale = 0;
VALUE inum, assoc[2];
assoc[0] = (VALUE)s;
assoc[1] = (VALUE)str;
if (ss = strpbrk(s, "Ee")) {
*ss++ = '\0'; /* for strchr() */
inum = rb_rescue(cstr_to_inum, (VALUE)ss, invalid_str, (VALUE)assoc);
scale -= NUM2LONG(inum);
}
if (ss = strchr(s, '.')) {
const char *p;
*ss = '_'; /* so that rb_cstr_to_inum() can ignore '.' */
for (p = ss + 1; ISDIGIT(*p) || *p == '_'; p++) {
if (ISDIGIT(*p)) scale++;
}
}
inum = rb_rescue(cstr_to_inum, (VALUE)s, invalid_str, (VALUE)assoc);
if (INUM_ZERO_P(inum)) {
inum = strchr(s, '-') ? DEC_NZERO : DEC_PZERO;
}
xfree(s);
return dec_raw_new(inum, scale);
}
static Decimal *
finite_dup(const Decimal *d)
{
VALUE inum;
if (FIXNUM_P(d->inum) || INUM_SPZERO_P(d->inum)) {
inum = d->inum;
}
else {
inum = rb_big_clone(d->inum); /* inum is a Bignum */
}
return dec_raw_new(inum, d->scale);
}
static Decimal *
create_dec(VALUE arg)
{
switch (TYPE(arg)) {
case T_FIXNUM:
case T_BIGNUM:
return inum_to_dec(arg);
case T_STRING:
return cstr_to_dec(StringValueCStr(arg));
case T_FLOAT:
rb_raise(rb_eArgError, "invalid type Float: %s",
RSTRING_PTR(rb_inspect(arg)));
default:
rb_raise(rb_eArgError, "invalid value for Decimal: %s",
RSTRING_PTR(rb_inspect(arg)));
}
return NULL; /* not reached */
}
/* TODO: should know about allocation framework for dumping/loading */
static VALUE
dec_s_allocate(VALUE klass)
{
return Data_Wrap_Struct(klass, dec_mark, dec_free, NULL);
}
/*
* call-seq:
* Decimal.new(arg) => decimal
*
* Returns a new decimal made from _arg_. The _arg_ must be an +Integer+
* or a +String+. An acceptable format of +String+ is equal to
* <code>Kernel.Float()</code>'s one. In a +Regexp+, it should be:
*
* digits = /(\d+_)*\d+/
* number = /(\+-)?#{digits}/
* body = /#{number}(\.#{digits})?([eE]#{number})?/
* decimal = /\A\s*#{body}\s*\z/
*
* And its samples are:
*
* Decimal(1) #=> Decimal(1)
* Decimal(2**64) #=> Decimal(18446744073709551616)
* Decimal("1") #=> Decimal(1)
* Decimal("1.1") #=> Decimal(1.1)
* Decimal("1e10") #=> Decimal(10000000000)
* Decimal("299_792_458") #=> Decimal(299792458)
* Decimal("2.99_792_458e8") #=> Decimal(299792458)
*
* Notice that a +Float+ is *not* acceptable for _arg_ to keep exactness.
*
* Decimal.new(1.1) #=> (ArgumentError)
*/
static VALUE
dec_initialize(VALUE self, VALUE arg)
{
if (DECIMAL_P(arg)) {
return arg;
}
DATA_PTR(self) = create_dec(arg);
return self;
}
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED /* nothing */
#endif
/*
* call-seq:
* Decimal(arg) => decimal
*
* Identical to <code>Decimal.new(arg)</code>, except that this method
* never be affected from overriding <code>Decimal#initialize</code>.
*/
static VALUE
f_decimal(VALUE klass UNUSED, VALUE arg)
{
return dec_initialize(dec_s_allocate(cDecimal), arg);
}
#ifdef DEBUG
/* :nodoc: */
static VALUE
dec_scale(VALUE self)
{
Decimal *d;
GetDecimal(self, d);
if (DEC_IMMEDIATE_P(d)) return Qnil;
return LONG2NUM(d->scale);
}
/* :nodoc: */
static VALUE
dec_unscaled_value(VALUE self)
{
Decimal *d;
GetDecimal(self, d);
if (DEC_IMMEDIATE_P(d)) return Qnil;
return DEC_ZERO_P(d) ? INT2FIX(0) : d->inum;
}
/* :nodoc: */
static VALUE
dec_strip_trailing_zeros(VALUE self)
{
Decimal *d, *d2;
GetDecimal(self, d);
if (DEC_IMMEDIATE_P(d))
return self;
if (DEC_ZERO_P(d)) { /* XXX: negative scale? */
if (d->scale <= 0) return self;
d2 = finite_dup(d);
d2->scale = 0;
return WrapDecimal(d2);
}
d2 = finite_dup(d);
/* TODO: can be optimized with dividing each part
* for Bignums and Fixnums */
while (INUM_BOTTOMDIG(d2->inum) == 0) {
d2->inum = INUM_DIV(d2->inum, INT2FIX(10));
d2->scale--;
}
return WrapDecimal(d2);
}
#endif /* DEBUG */
/* FIXME: should return "%g" format string */
static VALUE
finite_to_s(const Decimal *d)
{
const VALUE str = INUM2STR(d->inum);
const char *s = RSTRING_PTR(str);
const long slen = RSTRING_LEN(str);
const long scale = d->scale;
long snumlen, sslen, diff;
int negative;
char *ss; /* source of newstr */
VALUE newstr; /* to be returned */
if (scale == 0) return str;
if (scale < 0) { /* "xx00" */
sslen = slen - scale;
ss = ALLOC_N(char, sslen);
memcpy(ss, s, slen);
memset(ss+slen, '0', -scale);
goto coda;
}
negative = (*s == '-');
snumlen = negative ? slen-1 : slen;
if (scale < snumlen) { /* "xx.xx" */
diff = slen - scale;
sslen = slen + 1;
ss = ALLOC_N(char, sslen);
memcpy(ss, s, diff);
ss[diff] = '.';
memcpy(ss+diff+1, s+diff, scale);
}
else { /* "0.00xx" */
char *ss2; /* alias of ss */
diff = scale - snumlen;
/* "0." + "00..." + "-?xx" */
sslen = 2 + diff + slen;
ss = ss2 = ALLOC_N(char, sslen);
if (negative) *ss2++ = '-', s++;
memcpy(ss2, "0.", 2);
ss2 += 2;
if (diff) memset(ss2, '0', diff);
memcpy(ss2+diff, s, snumlen);
}
coda:
newstr = rb_usascii_str_new(ss, sslen);
xfree(ss);
return newstr;
}
/*
* call-seq:
* dec.to_s => string
*
* *WARNING*: The behavior of this method may change.
*
* Returns a string containing a simple representation of self.
*
* Decimal(1).to_s #=> "1"
* Decimal("1.1").to_s #=> "1.1"
* Decimal::INFINITY.to_s #=> "Infinity"
*/
static VALUE
dec_to_s(VALUE self)
{
Decimal *d;
CHECK_NAN_WITH_VAL(self, rb_usascii_str_new_cstr("NaN"));
if (self == VALUE_PINF) return rb_usascii_str_new_cstr("Infinity");
if (self == VALUE_NINF) return rb_usascii_str_new_cstr("-Infinity");
GetDecimal(self, d);
if (DEC_ZERO_P(d)) {
const size_t HEAD_LEN = d->inum == DEC_PZERO ? 2U : 3U; /* "-0.".length */
long len = HEAD_LEN + d->scale;
char *buf;
/* FIXME: use "0eN" style when the scale is negative? */
if (d->scale <= 0) /* ignore the case of negative scale */
return d->inum == DEC_PZERO ?
rb_usascii_str_new_cstr("0") : rb_usascii_str_new_cstr("-0");
buf = xmalloc(len);
if (d->inum == DEC_PZERO)
memcpy(buf, "0.", HEAD_LEN);
else
memcpy(buf, "-0.", HEAD_LEN);
memset(buf + HEAD_LEN, '0', d->scale);
return rb_usascii_str_new(buf, len);
}
return finite_to_s(d);
}
/*
* call-seq:
* dec.inspect => string
*
* Returns a easy-to-distinguish string: <code>"Decimal(#{dec})"</code>.
*
* Decimal(1).inspect #=> "Decimal(1)"
* Decimal("1.1").inspect #=> "Decimal(1.1)"
* Decimal::INFINITY.inspect #=> "Decimal(Infinity)"
*/
static VALUE
dec_inspect(VALUE self)
{
char *s;
VALUE str, newstr;
long len;
str = dec_to_s(self);
len = 9 + RSTRING_LEN(str); /* 9 == strlen("Decimal()") */
s = ALLOC_N(char, len + 1); /* +1 for NUL */
sprintf(s, "Decimal(%s)", RSTRING_PTR(str));
newstr = rb_usascii_str_new(s, len);
xfree(s);
return newstr;
}
/*
* call-seq:
* dec.coerce(other) => array
*
* Returns array <code>[Decimal(other), dec]</code> if _other_ has a
* compatible type, +Integer+ or +Decimal+.
* Otherwise raises a +TypeError+.
*
* Decimal(1).coerce(2) #=> [Decimal(2), Decimal(1)]
* Decimal(1).coerce(Decimal(2)) #=> [Decimal(2), Decimal(1)]
* Decimal(1).coerce(2.5) #=> (TypeError)
*/
static VALUE
dec_coerce(VALUE x, VALUE y)
{
VALUE yy;
switch (TYPE(y)) {
case T_FIXNUM:
case T_BIGNUM:
yy = WrapDecimal(inum_to_dec(y));
return rb_assoc_new(yy, x);
case T_FLOAT:
rb_raise(rb_eTypeError, "can't coerce Float to Decimal; "
"use Decimal#to_f explicitly if needed");
break;
case T_DATA:
if (DECIMAL_P(y)) return rb_assoc_new(y, x);
/* fall through */
default:
rb_raise(rb_eTypeError, "can't coerce %s to Decimal",
rb_obj_classname(y));
break;
}
return Qnil; /* not reached */
}
/*
* call-seq:
* -dec => decimal
*
* Returns a negated value of _dec_.
*/
static VALUE
dec_uminus(VALUE num)
{
VALUE inum;
Decimal *d;
CHECK_NAN(num);
if (num == VALUE_PINF) return VALUE_NINF;
if (num == VALUE_NINF) return VALUE_PINF;
GetDecimal(num, d);
if (d->inum == DEC_PZERO)
inum = DEC_NZERO;
else if (d->inum == DEC_NZERO)
inum = DEC_PZERO;
else
inum = INUM_UMINUS(d->inum);
return WrapDecimal(dec_raw_new(inum, d->scale));
}
/* returns x * (10 ** n) */
static VALUE
inum_lshift(VALUE x, long n)
{
VALUE y;
if (n <= 0) rb_bug("inum_lshift(): not reached");
y = fix_pow(INT2FIX(10), LONG2NUM(n));
return INUM_MUL(x, y);
}
/* the "normal" number means "finite and non-zero" */
static Decimal *
normal_plus(const Decimal *x, const Decimal *y, const int add)
{
VALUE inum;
long scale;
if (x->scale == y->scale) {
inum = add ? INUM_PLUS(x->inum, y->inum)
: INUM_MINUS(x->inum, y->inum);
scale = x->scale;
}
else {
const Decimal *max, *min;
VALUE min_inum;
if (x->scale > y->scale) max = x, min = y;
else max = y, min = x;
scale = max->scale;
min_inum = inum_lshift(min->inum, max->scale - min->scale);
if (add) inum = INUM_PLUS(min_inum, max->inum);
else if (max == x) inum = INUM_MINUS(max->inum, min_inum);
else inum = INUM_MINUS(min_inum, max->inum);
}
if (INUM_ZERO_P(inum)) inum = DEC_PZERO;
return dec_raw_new(inum, scale);
}
#define MAX(x, y) ((x) > (y) ? (x) : (y))
/*
* call-seq:
* dec + other => decimal
*
* Returns a new decimal which is the sum of _dec_ and _other_.
*/
static VALUE
dec_plus(VALUE x, VALUE y)
{
Decimal *a, *b;
CHECK_NAN2(x, y);
switch (TYPE(y)) {
case T_FIXNUM:
case T_BIGNUM:
b = inum_to_dec(y);
break;
case T_FLOAT:
rb_raise(rb_eTypeError, "can't operate with Float");
break;
case T_DATA:
if (DECIMAL_P(y)) {
GetDecimal(y, b);
break;
}
/* fall through */
default:
return rb_num_coerce_bin(x, y, '+');
}
if (DEC_VALUE_ISINF(x)) {
if (DEC_VALUE_ISINF(y) && x != y) return VALUE_NaN;
return x;
}
if (DEC_VALUE_ISINF(y)) return y;
/* now, x and y are not NaN nor +-INFINITY */
GetDecimal(x, a);
if (DEC_ZERO_P(a)) {
VALUE inum;
if (DEC_ZERO_P(b)) {
const long scale = MAX(a->scale, b->scale);
if (a->inum == DEC_NZERO && b->inum == DEC_NZERO)
return dec_nzero(scale);
return dec_pzero(scale);
}
if (a->scale <= b->scale)
return y;
inum = inum_lshift(b->inum, a->scale - b->scale);
return WrapDecimal(dec_raw_new(inum, a->scale));
}
if (DEC_ZERO_P(b)) {
VALUE inum;
if (a->scale >= b->scale)
return x;
inum = inum_lshift(a->inum, b->scale - a->scale);
return WrapDecimal(dec_raw_new(inum, b->scale));
}
/* "true" means addition */
return WrapDecimal(normal_plus(a, b, Qtrue));
}
#define NEGATE_INF(x) ((x) == VALUE_PINF ? VALUE_NINF : VALUE_PINF)
/*
* call-seq:
* dec - other => decimal
*
* Returns a new float which is the difference of _dec_ and _other_.
*/
static VALUE
dec_minus(VALUE x, VALUE y)
{
Decimal *a, *b;
CHECK_NAN2(x, y);
switch (TYPE(y)) {
case T_FIXNUM:
case T_BIGNUM:
b = inum_to_dec(y);
break;
case T_FLOAT:
rb_raise(rb_eTypeError, "can't operate with Float");
break;
case T_DATA:
if (DECIMAL_P(y)) {
GetDecimal(y, b);
break;
}
/* fall through */
default:
return rb_num_coerce_bin(x, y, '-');
}
if (DEC_VALUE_ISINF(x)) {
if (x == y) return VALUE_NaN;
return x;
}
if (DEC_VALUE_ISINF(y)) return NEGATE_INF(y);
GetDecimal(x, a);
if (DEC_ZERO_P(a)) { /* FIXME: needs refactoring */
if (!DEC_ISINF(b) && DEC_ZERO_P(b) && a->inum == b->inum) {
/* FIXME: UNDER CONSTRUCTION for scaling */
return dec_pzero(MAX(a->scale, b->scale));
}
return dec_uminus(y);
}
if (DEC_ZERO_P(b)) return x;
/* "false" means subtraction */
return WrapDecimal(normal_plus(a, b, Qfalse));
}
static Decimal *
normal_mul(const Decimal *x, const Decimal *y)
{
return dec_raw_new(INUM_MUL(x->inum, y->inum), x->scale + y->scale);
}
/*
* call-seq:
* dec * other => decimal
*
* Returns a new decimal which is the product of _dec_ and _other_.
*/
static VALUE
dec_mul(VALUE x, VALUE y)
{
Decimal *a, *b;
CHECK_NAN2(x, y);
switch (TYPE(y)) {
case T_FIXNUM:
/* TODO: can be optimized if y = 0, 1 or -1 */
case T_BIGNUM:
b = inum_to_dec(y);
break;
case T_FLOAT:
rb_raise(rb_eTypeError, "can't operate with Float");
break;
case T_DATA:
if (DECIMAL_P(y)) {
GetDecimal(y, b);
break;
}
/* fall through */
default:
return rb_num_coerce_bin(x, y, '*');
}
GetDecimal(x, a);
if (DEC_ISINF(a)) {
if (DEC_ISINF(b)) return x == y ? VALUE_PINF : VALUE_NINF;
if (DEC_ZERO_P(b)) return VALUE_NaN;
if (!INUM_NEGATIVE_P(b->inum)) return x;
return dec_uminus(x);
}
if (DEC_ZERO_P(a)) {
if (DEC_ISINF(b)) return VALUE_NaN;
if (DEC_ZERO_P(b)) {
return a->inum == DEC_PZERO ? y : dec_uminus(y);
}
if (INUM_NEGATIVE_P(b->inum)) return dec_uminus(x);
return x;
}
if (DEC_IMMEDIATE_P(b) || DEC_ZERO_P(b)) {
if (INUM_NEGATIVE_P(a->inum)) return dec_uminus(y);
return y;
}
return WrapDecimal(normal_mul(a, b));
}
static Decimal *
do_round(const Decimal *d, long scale, VALUE mode, VALUE *inump)
{
Decimal *d2;
long diff;
int lower;
int trailing_nonzero, negative;
VALUE inum = Qundef, inumabs, shift, ary;
if (d == DEC_PINF) rb_raise(eDomainError, "Infinity");
if (d == DEC_NINF) rb_raise(eDomainError, "-Infinity");
if (d == DEC_NaN) rb_raise(eDomainError, "NaN");
if (INUM_SPZERO_P(d->inum)) {
if (inump) {
if (scale > 0) rb_bug("do_round(): "
"scale > 0 with Integer request");
*inump = INT2FIX(0);
return NULL;
}
d2 = finite_dup(d);
if (d->scale > scale) d2->scale = scale;
return d2;
}
if (d->scale <= scale) { /* no need to round */
if (scale) return finite_dup(d); /* return Decimal */
/* return Integer */
if (!inump) /* XXX: may be reached when Decimal(1)/1 */
rb_bug("do_round(): not reached[2]");
/* FIXME: scaling policy, no need to grow scale? */
if (d->scale == 0) *inump = d->inum;
else *inump = inum_lshift(d->inum, -d->scale);
return NULL;
}
negative = INUM_NEGATIVE_P(d->inum);
diff = d->scale - scale;
inumabs = negative ? INUM_UMINUS(d->inum) : d->inum;
if (mode == ROUND_CEILING || /* don't need lower digit */
mode == ROUND_DOWN ||
mode == ROUND_FLOOR ||
mode == ROUND_UP ||
mode == ROUND_UNNECESSARY) {
shift = inum_lshift(INT2FIX(1), diff);
ary = INUM_DIVMOD(inumabs, shift);
inum = RARRAY_PTR(ary)[0];
if (mode == ROUND_DOWN) goto coda;
trailing_nonzero = !INUM_ZERO_P(RARRAY_PTR(ary)[1]);
if (mode == ROUND_CEILING) {
if (!negative && trailing_nonzero) INUM_INC(inum);
}
else if (mode == ROUND_FLOOR) {
if (negative && trailing_nonzero) INUM_INC(inum);
}
else if (mode == ROUND_UP) {
if (trailing_nonzero) INUM_INC(inum);
}
else { /* mode == ROUND_UNNECESSARY */
if (trailing_nonzero) {
rb_raise(eArithmeticError, "rounding necessary");
}
}
}
else if (mode == ROUND_HALF_DOWN || /* needs lower digit */
mode == ROUND_HALF_UP ||
mode == ROUND_HALF_EVEN) {
if (diff > 1) { /* needs shift */
shift = inum_lshift(INT2FIX(1), diff-1);
inumabs = INUM_DIV(inumabs, shift);
}
ary = INUM_DIVMOD(inumabs, INT2FIX(10));
inum = RARRAY_PTR(ary)[0];
lower = FIX2INT(RARRAY_PTR(ary)[1]);
if (mode == ROUND_HALF_DOWN) {
if (lower > 5) INUM_INC(inum);
}
else if (mode == ROUND_HALF_UP) {
if (lower >= 5) INUM_INC(inum);
}
else { /* mode == ROUND_HALF_EVEN */
if (INUM_ODD_P(inum)) {
if (lower >= 5) INUM_INC(inum);
}
else {
if (lower > 5) INUM_INC(inum);
}
}
}
coda:
if (negative) inum = INUM_UMINUS(inum);
if (scale <= 0 && inump != NULL) {
/* return Integer */
if (scale < 0) inum = inum_lshift(inum, -scale);
*inump = inum;
return NULL;
}
/* return Decimal */
if (INUM_ZERO_P(inum)) {
inum = negative ? DEC_NZERO : DEC_PZERO;
scale = 0;
}
return dec_raw_new(inum, scale);
}
static Decimal *
normal_divide(const Decimal *x, const Decimal *y, long scale, VALUE mode)
{
long diff, z_scale;
VALUE xx;
Decimal *z;
diff = x->scale - y->scale;
if (diff <= scale) {
xx = inum_lshift(x->inum, scale-diff+1); /* +1 for rounding */
z_scale = scale + 1;
}
else {
/* FIXME: may be a bug...? */
xx = x->inum;
z_scale = diff;
}
z = dec_raw_new(INUM_DIV(xx, y->inum), z_scale);
return do_round(z, scale, mode, NULL);
}
static int
valid_rounding_mode_p(VALUE sym)
{
if (sym == ROUND_CEILING ||
sym == ROUND_DOWN ||
sym == ROUND_FLOOR ||
sym == ROUND_HALF_DOWN ||
sym == ROUND_HALF_EVEN ||
sym == ROUND_HALF_UP ||
sym == ROUND_UP ||
sym == ROUND_UNNECESSARY) {
return Qtrue;
}
return Qfalse;
}
/*
* call-seq:
* dec.divide(other, scale=0, mode=Decimal::ROUND_UNNECESSARY) #=> decimal or integer
*
* *WARNING*: The behavior of this method may change.
*
* Returns a new decimal which is the result of dividing _dec_ by _other_.
*
* *FIXME*: write details
*/
static VALUE
dec_divide(int argc, VALUE *argv, VALUE x)
{
VALUE y;
Decimal *a, *b;
VALUE mode = ROUND_UNNECESSARY;
long l, scale = 0; /* FIXME: dummy 0 */
VALUE vscale, vmode;
CHECK_NAN(x);
GetDecimal(x, a);
rb_scan_args(argc, argv, "12", &y, &vscale, &vmode);
switch (argc) {
case 3:
Check_Type(vmode, T_SYMBOL);
if (!valid_rounding_mode_p(vmode)) {
rb_raise(rb_eArgError, "invalid rounding mode %s",
RSTRING_PTR(rb_inspect(vmode)));
}
mode = vmode;
/* fall through */
case 2:
scale = NUM2LONG(vscale);
break;
case 1:
if (mode != ROUND_UNNECESSARY) {
rb_raise(rb_eArgError, "scale number argument needed");
}
}
CHECK_NAN(y);
switch (TYPE(y)) {
case T_FIXNUM:
l = FIX2LONG(y);
if (l == 0) {
if (DEC_ISINF(a)) return x;
if (DEC_ZERO_P(a)) return VALUE_NaN;
return INUM_NEGATIVE_P(a->inum) ? VALUE_NINF : VALUE_PINF;
}
else if (l == 1) return x;
else if (l == -1) return dec_uminus(x);
/* fall through */
case T_BIGNUM:
b = inum_to_dec(y);
break;
case T_FLOAT:
rb_raise(rb_eTypeError, "can't operate with Float");
return Qnil; /* not reached */
case T_DATA:
if (DECIMAL_P(y)) {
GetDecimal(y, b);
break;
}
/* fall through */
default:
return rb_num_coerce_bin(x, y, rb_intern("divide"));
}
if (DEC_ISINF(a)) {
if (DEC_ISINF(b)) return VALUE_NaN;
if (b->inum == DEC_PZERO) return x;
if (b->inum == DEC_NZERO) return NEGATE_INF(x);
return INUM_NEGATIVE_P(b->inum) ? NEGATE_INF(x) : x;
}
if (DEC_ZERO_P(a)) {
if (b == DEC_PINF) return x;
if (b == DEC_NINF) return dec_uminus(x);
if (INUM_SPZERO_P(b->inum)) return VALUE_NaN;
return INUM_NEGATIVE_P(b->inum) ? dec_uminus(x) : x;
}
if (DEC_ISINF(b)) {
if (INUM_NEGATIVE_P(a->inum) == (b == DEC_NINF)) {
return dec_pzero(0); /* FIXME for scaling */
}
return dec_nzero(0); /* FIXME for scaling */
}
if (DEC_ZERO_P(b)) {
if (INUM_NEGATIVE_P(a->inum) == (b->inum == DEC_NZERO)) {
return VALUE_PINF;
}
return VALUE_NINF;
}
return WrapDecimal(normal_divide(a, b, scale, mode));
}
#ifdef DEBUG