Debian Codegraph @

src/ops/add.rs

raw symbols SCIP
1 use crate::constants::{MAX_I32_SCALE, POWERS_10, SCALE_MASK, SCALE_SHIFT, SIGN_MASK, U32_MASK, U32_MAX};
2 use crate::decimal::{CalculationResult, Decimal};
3 use crate::ops::common::{Buf24, Dec64};
4
5 #[inline(always)]
6 pub(crate) fn add_impl(d1: &Decimal, d2: &Decimal) -> CalculationResult {
7 add_sub_internal(d1, d2, false)
8 }
9
10 #[inline(always)]
11 pub(crate) fn sub_impl(d1: &Decimal, d2: &Decimal) -> CalculationResult {
12 add_sub_internal(d1, d2, true)
13 }
14
15 #[inline(always)]
16 fn add_sub_internal(d1: &Decimal, d2: &Decimal, subtract: bool) -> CalculationResult {
17 // Compute flags and effective subtract early
18 let flags = d1.flags() ^ d2.flags();
19 let effective_subtract = subtract ^ ((flags & SIGN_MASK) != 0);
20 let rescale = (flags & SCALE_MASK) > 0;
21
22 // Fast path: both operands fit in 32 bits (very common in fold operations)
23 if d1.mid() | d1.hi() == 0 && d2.mid() | d2.hi() == 0 {
24 let lo1 = d1.lo();
25 let lo2 = d2.lo();
26
27 // Handle zeros inline (cheaper: only check lo since mid|hi are already 0)
28 if lo1 == 0 {
29 let mut result = *d2;
30 // Use original subtract parameter for zero handling (not effective_subtract)
31 if subtract && lo2 != 0 {
32 result.set_sign_negative(d2.is_sign_positive());
33 }
34 return CalculationResult::Ok(result);
35 }
36 if lo2 == 0 {
37 return CalculationResult::Ok(*d1);
38 }
39
40 if rescale {
41 let rescale_factor = ((d2.flags() & SCALE_MASK) as i32 - (d1.flags() & SCALE_MASK) as i32) >> SCALE_SHIFT;
42 if rescale_factor < 0 {
43 // We try to rescale the rhs
44 if let Some(rescaled) = rescale32(lo2, -rescale_factor) {
45 return fast_add(lo1, rescaled, d1.flags(), effective_subtract);
46 }
47 } else {
48 // We try to rescale the lhs
49 if let Some(rescaled) = rescale32(lo1, rescale_factor) {
50 return fast_add(
51 rescaled,
52 lo2,
53 (d2.flags() & SCALE_MASK) | (d1.flags() & SIGN_MASK),
54 effective_subtract,
55 );
56 }
57 }
58 } else {
59 return fast_add(lo1, lo2, d1.flags(), effective_subtract);
60 }
61 }
62
63 // Slower path: handle zero cases for > 32-bit operands
64 if d1.is_zero() {
65 // 0 - x or 0 + x
66 let mut result = *d2;
67 if subtract && !d2.is_zero() {
68 result.set_sign_negative(d2.is_sign_positive());
69 }
70 return CalculationResult::Ok(result);
71 }
72 if d2.is_zero() {
73 // x - 0 or x + 0
74 return CalculationResult::Ok(*d1);
75 }
76
77 // Continue on with the slower 64 bit method
78 let d1 = Dec64::new(d1);
79 let d2 = Dec64::new(d2);
80
81 // If we're not the same scale then make sure we're there first before starting addition
82 if rescale {
83 let rescale_factor = d2.scale as i32 - d1.scale as i32;
84 if rescale_factor < 0 {
85 let negative = effective_subtract ^ d1.negative;
86 let scale = d1.scale;
87 unaligned_add(d2, d1, negative, scale, -rescale_factor, effective_subtract)
88 } else {
89 let negative = d1.negative;
90 let scale = d2.scale;
91 unaligned_add(d1, d2, negative, scale, rescale_factor, effective_subtract)
92 }
93 } else {
94 let neg = d1.negative;
95 let scale = d1.scale;
96 aligned_add(d1, d2, neg, scale, effective_subtract)
97 }
98 }
99
100 #[inline(always)]
101 fn rescale32(num: u32, rescale_factor: i32) -> Option<u32> {
102 if rescale_factor > MAX_I32_SCALE {
103 return None;
104 }
105 num.checked_mul(POWERS_10[rescale_factor as usize])
106 }
107
108 #[inline(always)]
109 fn fast_add(lo1: u32, lo2: u32, flags: u32, subtract: bool) -> CalculationResult {
110 if subtract {
111 // Sub can't overflow because we're ensuring the bigger number always subtracts the smaller number
112 if lo1 < lo2 {
113 return CalculationResult::Ok(Decimal::from_parts_raw(lo2 - lo1, 0, 0, flags ^ SIGN_MASK));
114 }
115 return CalculationResult::Ok(Decimal::from_parts_raw(lo1 - lo2, 0, 0, flags));
116 }
117 // Add can overflow however, so we check for that explicitly
118 // Both inputs are non-zero (checked earlier), so result is guaranteed non-zero
119 let lo = lo1.wrapping_add(lo2);
120 let mid = if lo < lo1 { 1 } else { 0 };
121 CalculationResult::Ok(Decimal::from_parts_raw_unchecked(lo, mid, 0, flags))
122 }
123
124 #[inline(always)]
125 fn aligned_add(lhs: Dec64, rhs: Dec64, negative: bool, scale: u32, subtract: bool) -> CalculationResult {
126 if subtract {
127 // Signs differ, so subtract
128 let mut result = Dec64 {
129 negative,
130 scale,
131 low64: lhs.low64.wrapping_sub(rhs.low64),
132 hi: lhs.hi.wrapping_sub(rhs.hi),
133 };
134
135 // Check for carry
136 if result.low64 > lhs.low64 {
137 result.hi = result.hi.wrapping_sub(1);
138 if result.hi >= lhs.hi {
139 flip_sign(&mut result);
140 }
141 } else if result.hi > lhs.hi {
142 flip_sign(&mut result);
143 }
144 CalculationResult::Ok(result.to_decimal())
145 } else {
146 // Signs are the same, so add
147 let mut result = Dec64 {
148 negative,
149 scale,
150 low64: lhs.low64.wrapping_add(rhs.low64),
151 hi: lhs.hi.wrapping_add(rhs.hi),
152 };
153
154 // Check for carry
155 if result.low64 < lhs.low64 {
156 result.hi = result.hi.wrapping_add(1);
157 if result.hi <= lhs.hi {
158 if result.scale == 0 {
159 return CalculationResult::Overflow;
160 }
161 reduce_scale(&mut result);
162 }
163 } else if result.hi < lhs.hi {
164 if result.scale == 0 {
165 return CalculationResult::Overflow;
166 }
167 reduce_scale(&mut result);
168 }
169 CalculationResult::Ok(result.to_decimal())
170 }
171 }
172
173 fn flip_sign(result: &mut Dec64) {
174 // Bitwise not the high portion
175 result.hi = !result.hi;
176 let low64 = ((result.low64 as i64).wrapping_neg()) as u64;
177 if low64 == 0 {
178 result.hi += 1;
179 }
180 result.low64 = low64;
181 result.negative = !result.negative;
182 }
183
184 fn reduce_scale(result: &mut Dec64) {
185 let mut low64 = result.low64;
186 let mut hi = result.hi;
187
188 let mut num = (hi as u64) + (1u64 << 32);
189 hi = (num / 10u64) as u32;
190 num = ((num - (hi as u64) * 10u64) << 32) + (low64 >> 32);
191 let mut div = (num / 10) as u32;
192 num = ((num - (div as u64) * 10u64) << 32) + (low64 & U32_MASK);
193 low64 = (div as u64) << 32;
194 div = (num / 10u64) as u32;
195 low64 = low64.wrapping_add(div as u64);
196 let remainder = (num as u32).wrapping_sub(div.wrapping_mul(10));
197
198 // Finally, round. This is optimizing slightly toward non-rounded numbers
199 if remainder >= 5 && (remainder > 5 || (low64 & 1) > 0) {
200 low64 = low64.wrapping_add(1);
201 if low64 == 0 {
202 hi += 1;
203 }
204 }
205
206 result.low64 = low64;
207 result.hi = hi;
208 result.scale -= 1;
209 }
210
211 // Assumption going into this function is that the LHS is the larger number and will "absorb" the
212 // smaller number.
213 fn unaligned_add(
214 lhs: Dec64,
215 rhs: Dec64,
216 negative: bool,
217 scale: u32,
218 rescale_factor: i32,
219 subtract: bool,
220 ) -> CalculationResult {
221 let mut lhs = lhs;
222 let mut low64 = lhs.low64;
223 let mut high = lhs.hi;
224 let mut rescale_factor = rescale_factor;
225
226 // First off, we see if we can get away with scaling small amounts (or none at all)
227 if high == 0 {
228 if low64 <= U32_MAX {
229 // We know it's not zero, so we start scaling.
230 // Start with reducing the scale down for the low portion
231 while low64 <= U32_MAX {
232 if rescale_factor <= MAX_I32_SCALE {
233 low64 *= POWERS_10[rescale_factor as usize] as u64;
234 lhs.low64 = low64;
235 return aligned_add(lhs, rhs, negative, scale, subtract);
236 }
237 rescale_factor -= MAX_I32_SCALE;
238 low64 *= POWERS_10[9] as u64;
239 }
240 }
241
242 // Reduce the scale for the high portion
243 while high == 0 {
244 let power = if rescale_factor <= MAX_I32_SCALE {
245 POWERS_10[rescale_factor as usize] as u64
246 } else {
247 POWERS_10[9] as u64
248 };
249
250 let tmp_low = (low64 & U32_MASK) * power;
251 let tmp_hi = (low64 >> 32) * power + (tmp_low >> 32);
252 low64 = (tmp_low & U32_MASK) + (tmp_hi << 32);
253 high = (tmp_hi >> 32) as u32;
254 rescale_factor -= MAX_I32_SCALE;
255 if rescale_factor <= 0 {
256 lhs.low64 = low64;
257 lhs.hi = high;
258 return aligned_add(lhs, rhs, negative, scale, subtract);
259 }
260 }
261 }
262
263 // See if we can get away with keeping it in the 96 bits. Otherwise, we need a buffer
264 let mut tmp64: u64;
265 loop {
266 let power = if rescale_factor <= MAX_I32_SCALE {
267 POWERS_10[rescale_factor as usize] as u64
268 } else {
269 POWERS_10[9] as u64
270 };
271
272 let tmp_low = (low64 & U32_MASK) * power;
273 tmp64 = (low64 >> 32) * power + (tmp_low >> 32);
274 low64 = (tmp_low & U32_MASK) + (tmp64 << 32);
275 tmp64 >>= 32;
276 tmp64 += (high as u64) * power;
277
278 rescale_factor -= MAX_I32_SCALE;
279
280 if tmp64 > U32_MAX || scale > Decimal::MAX_SCALE {
281 break;
282 } else {
283 high = tmp64 as u32;
284 if rescale_factor <= 0 {
285 lhs.low64 = low64;
286 lhs.hi = high;
287 return aligned_add(lhs, rhs, negative, scale, subtract);
288 }
289 }
290 }
291
292 let mut buffer = Buf24::zero();
293 buffer.set_low64(low64);
294 buffer.set_mid64(tmp64);
295
296 let mut upper_word = buffer.upper_word();
297 while rescale_factor > 0 {
298 let power = if rescale_factor <= MAX_I32_SCALE {
299 POWERS_10[rescale_factor as usize] as u64
300 } else {
301 POWERS_10[9] as u64
302 };
303 tmp64 = 0;
304 for (index, part) in buffer.data.iter_mut().enumerate() {
305 tmp64 = tmp64.wrapping_add((*part as u64) * power);
306 *part = tmp64 as u32;
307 tmp64 >>= 32;
308 if index + 1 > upper_word {
309 break;
310 }
311 }
312
313 if tmp64 & U32_MASK > 0 {
314 // Extend the result
315 upper_word += 1;
316 buffer.data[upper_word] = tmp64 as u32;
317 }
318
319 rescale_factor -= MAX_I32_SCALE;
320 }
321
322 // Do the add
323 tmp64 = buffer.low64();
324 low64 = rhs.low64;
325 let tmp_hi = buffer.data[2];
326 high = rhs.hi;
327
328 if subtract {
329 low64 = tmp64.wrapping_sub(low64);
330 high = tmp_hi.wrapping_sub(high);
331
332 // Check for carry
333 let carry = if low64 > tmp64 {
334 high = high.wrapping_sub(1);
335 high >= tmp_hi
336 } else {
337 high > tmp_hi
338 };
339
340 if carry {
341 for part in buffer.data.iter_mut().skip(3) {
342 *part = part.wrapping_sub(1);
343 if *part > 0 {
344 break;
345 }
346 }
347
348 if buffer.data[upper_word] == 0 && upper_word < 3 {
349 return CalculationResult::Ok(Decimal::from_parts(
350 low64 as u32,
351 (low64 >> 32) as u32,
352 high,
353 negative,
354 scale,
355 ));
356 }
357 }
358 } else {
359 low64 = low64.wrapping_add(tmp64);
360 high = high.wrapping_add(tmp_hi);
361
362 // Check for carry
363 let carry = if low64 < tmp64 {
364 high = high.wrapping_add(1);
365 high <= tmp_hi
366 } else {
367 high < tmp_hi
368 };
369
370 if carry {
371 for (index, part) in buffer.data.iter_mut().enumerate().skip(3) {
372 if upper_word < index {
373 *part = 1;
374 upper_word = index;
375 break;
376 }
377 *part = part.wrapping_add(1);
378 if *part > 0 {
379 break;
380 }
381 }
382 }
383 }
384
385 buffer.set_low64(low64);
386 buffer.data[2] = high;
387 if let Some(scale) = buffer.rescale(upper_word, scale) {
388 CalculationResult::Ok(Decimal::from_parts(
389 buffer.data[0],
390 buffer.data[1],
391 buffer.data[2],
392 negative,
393 scale,
394 ))
395 } else {
396 CalculationResult::Overflow
397 }
398 }