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
// This file is part of ICU4X.
//
// The contents of this file implement algorithms from Calendrical Calculations
// by Reingold & Dershowitz, Cambridge University Press, 4th edition (2018),
// which have been released as Lisp code at <https://github.com/EdReingold/calendar-code2/>
// under the Apache-2.0 license. Accordingly, this file is released under
// the Apache License, Version 2.0 which can be found at the calendrical_calculations
// package root or at http://www.apache.org/licenses/LICENSE-2.0.

use crate::astronomy::Location;
use crate::rata_die::{Moment, RataDie};
#[allow(unused_imports)]
use core_maths::*;

pub(crate) trait IntegerRoundings {
    fn div_ceil(self, rhs: Self) -> Self;
}

impl IntegerRoundings for i64 {
    // copied from std
    fn div_ceil(self, rhs: Self) -> Self {
        let d = self / rhs;
        let r = self % rhs;
        if (r > 0 && rhs > 0) || (r < 0 && rhs < 0) {
            d + 1
        } else {
            d
        }
    }
}

#[test]
fn test_div_ceil() {
    assert_eq!(IntegerRoundings::div_ceil(i64::MIN, 1), i64::MIN);
    assert_eq!(
        IntegerRoundings::div_ceil(i64::MIN, 2),
        -4611686018427387904
    );
    assert_eq!(
        IntegerRoundings::div_ceil(i64::MIN, 3),
        -3074457345618258602
    );

    assert_eq!(IntegerRoundings::div_ceil(-10, 1), -10);
    assert_eq!(IntegerRoundings::div_ceil(-10, 2), -5);
    assert_eq!(IntegerRoundings::div_ceil(-10, 3), -3);

    assert_eq!(IntegerRoundings::div_ceil(-9, 1), -9);
    assert_eq!(IntegerRoundings::div_ceil(-9, 2), -4);
    assert_eq!(IntegerRoundings::div_ceil(-9, 3), -3);

    assert_eq!(IntegerRoundings::div_ceil(-8, 1), -8);
    assert_eq!(IntegerRoundings::div_ceil(-8, 2), -4);
    assert_eq!(IntegerRoundings::div_ceil(-8, 3), -2);

    assert_eq!(IntegerRoundings::div_ceil(-2, 1), -2);
    assert_eq!(IntegerRoundings::div_ceil(-2, 2), -1);
    assert_eq!(IntegerRoundings::div_ceil(-2, 3), 0);

    assert_eq!(IntegerRoundings::div_ceil(-1, 1), -1);
    assert_eq!(IntegerRoundings::div_ceil(-1, 2), 0);
    assert_eq!(IntegerRoundings::div_ceil(-1, 3), 0);

    assert_eq!(IntegerRoundings::div_ceil(0, 1), 0);
    assert_eq!(IntegerRoundings::div_ceil(0, 2), 0);
    assert_eq!(IntegerRoundings::div_ceil(0, 3), 0);

    assert_eq!(IntegerRoundings::div_ceil(1, 1), 1);
    assert_eq!(IntegerRoundings::div_ceil(1, 2), 1);
    assert_eq!(IntegerRoundings::div_ceil(1, 3), 1);

    assert_eq!(IntegerRoundings::div_ceil(2, 1), 2);
    assert_eq!(IntegerRoundings::div_ceil(2, 2), 1);
    assert_eq!(IntegerRoundings::div_ceil(2, 3), 1);

    assert_eq!(IntegerRoundings::div_ceil(8, 1), 8);
    assert_eq!(IntegerRoundings::div_ceil(8, 2), 4);
    assert_eq!(IntegerRoundings::div_ceil(8, 3), 3);

    assert_eq!(IntegerRoundings::div_ceil(9, 1), 9);
    assert_eq!(IntegerRoundings::div_ceil(9, 2), 5);
    assert_eq!(IntegerRoundings::div_ceil(9, 3), 3);

    assert_eq!(IntegerRoundings::div_ceil(10, 1), 10);
    assert_eq!(IntegerRoundings::div_ceil(10, 2), 5);
    assert_eq!(IntegerRoundings::div_ceil(10, 3), 4);

    assert_eq!(IntegerRoundings::div_ceil(i64::MAX, 1), 9223372036854775807);
    assert_eq!(IntegerRoundings::div_ceil(i64::MAX, 2), 4611686018427387904);
    assert_eq!(IntegerRoundings::div_ceil(i64::MAX, 3), 3074457345618258603);

    for n in -100..100 {
        for d in 1..5 {
            let x1 = IntegerRoundings::div_ceil(n, d);
            let x2 = (n as f64 / d as f64).ceil();
            assert_eq!(x1, x2 as i64);
        }
    }
}

// Highest power is *last*
pub(crate) fn poly(x: f64, coeffs: &[f64]) -> f64 {
    coeffs.iter().rev().fold(0.0, |a, c| a * x + c)
}

// A generic function that finds a value within an interval
// where a certain condition is satisfied.
pub(crate) fn binary_search(
    mut l: f64,
    mut h: f64,
    test: impl Fn(f64) -> bool,
    epsilon: f64,
) -> f64 {
    debug_assert!(l < h);

    loop {
        let mid = l + (h - l) / 2.0;

        // Determine which direction to go. `test` returns true if we need to go left.
        (l, h) = if test(mid) { (l, mid) } else { (mid, h) };

        // When the interval width reaches `epsilon`, return the current midpoint.
        if (h - l) < epsilon {
            return mid;
        }
    }
}

pub(crate) fn next_moment<F>(mut index: Moment, location: Location, condition: F) -> RataDie
where
    F: Fn(Moment, Location) -> bool,
{
    loop {
        if condition(index, location) {
            return index.as_rata_die();
        }
        index += 1.0;
    }
}

pub(crate) fn next<F>(mut index: RataDie, condition: F) -> RataDie
where
    F: Fn(RataDie) -> bool,
{
    loop {
        if condition(index) {
            return index;
        }
        index += 1;
    }
}

pub(crate) fn next_u8<F>(mut index: u8, condition: F) -> u8
where
    F: Fn(u8) -> bool,
{
    loop {
        if condition(index) {
            return index;
        }
        index += 1;
    }
}

// "Final" is a reserved keyword in rust, which explains the naming convention here.
pub(crate) fn final_func<F>(mut index: i32, condition: F) -> i32
where
    F: Fn(i32) -> bool,
{
    while condition(index) {
        index += 1;
    }
    index - 1
}

#[test]
fn test_binary_search() {
    struct TestCase {
        test_fn: fn(f64) -> bool,
        range: (f64, f64),
        expected: f64,
    }

    let test_cases = [
        TestCase {
            test_fn: |x: f64| x >= 4.0,
            range: (0.0, 10.0),
            expected: 4.0,
        },
        TestCase {
            test_fn: |x: f64| x * x >= 2.0,
            range: (0.0, 2.0),
            expected: 2.0f64.sqrt(),
        },
        TestCase {
            test_fn: |x: f64| x >= -4.0,
            range: (-10.0, 0.0),
            expected: -4.0,
        },
        TestCase {
            test_fn: |x: f64| x >= 0.0,
            range: (0.0, 10.0),
            expected: 0.0,
        },
        TestCase {
            test_fn: |x: f64| x > 10.0,
            range: (0.0, 10.0),
            expected: 10.0,
        },
    ];

    for case in test_cases {
        let result = binary_search(case.range.0, case.range.1, case.test_fn, 1e-4);
        assert!((result - case.expected).abs() < 0.0001);
    }
}

pub(crate) fn invert_angular<F: Fn(f64) -> f64>(f: F, y: f64, r: (f64, f64)) -> f64 {
    binary_search(r.0, r.1, |x| (f(x) - y).rem_euclid(360.0) < 180.0, 1e-5)
}

#[test]
fn test_invert_angular() {
    struct TestCase {
        f: fn(f64) -> f64,
        y: f64,
        r: (f64, f64),
        expected: f64,
    }

    fn f1(x: f64) -> f64 {
        (2.0 * x).rem_euclid(360.0)
    }

    fn f2(x: f64) -> f64 {
        (3.0 * x).rem_euclid(360.0)
    }

    fn f3(x: f64) -> f64 {
        (x).rem_euclid(360.0)
    }
    // tolerance for comparing floating points.
    let tolerance = 1e-5;

    let test_cases = [
        TestCase {
            f: f1,
            y: 4.0,
            r: (0.0, 10.0),
            expected: 4.0,
        },
        TestCase {
            f: f2,
            y: 6.0,
            r: (0.0, 20.0),
            expected: 6.0,
        },
        TestCase {
            f: f3,
            y: 400.0,
            r: (0.0, 10.0),
            expected: 10.0,
        },
        TestCase {
            f: f3,
            y: 0.0,
            r: (0.0, 10.0),
            expected: 0.0,
        },
        TestCase {
            f: f3,
            y: 10.0,
            r: (0.0, 10.0),
            expected: 10.0,
        },
    ];

    for case in test_cases {
        let x = invert_angular(case.f, case.y, case.r);
        assert!((((case.f)(x)).rem_euclid(360.0) - case.expected).abs() < tolerance);
    }
}

/// Error returned when casting from an i32
#[derive(Copy, Clone, Debug)]
#[allow(clippy::exhaustive_enums)] // enum is specific to function and has a closed set of possible values
pub enum I32CastError {
    /// Less than i32::MIN
    BelowMin,
    /// Greater than i32::MAX
    AboveMax,
}

impl I32CastError {
    pub(crate) const fn saturate(self) -> i32 {
        match self {
            I32CastError::BelowMin => i32::MIN,
            I32CastError::AboveMax => i32::MAX,
        }
    }
}

/// Convert an i64 to i32 and with information on which way it was out of bounds if so
#[inline]
pub const fn i64_to_i32(input: i64) -> Result<i32, I32CastError> {
    if input < i32::MIN as i64 {
        Err(I32CastError::BelowMin)
    } else if input > i32::MAX as i64 {
        Err(I32CastError::AboveMax)
    } else {
        Ok(input as i32)
    }
}

/// Convert an i64 to i32 but saturate at th ebounds
#[inline]
pub fn i64_to_saturated_i32(input: i64) -> i32 {
    i64_to_i32(input).unwrap_or_else(|i| i.saturate())
}

#[test]
fn test_i64_to_saturated_i32() {
    assert_eq!(i64_to_saturated_i32(i64::MIN), i32::MIN);
    assert_eq!(i64_to_saturated_i32(-2147483649), -2147483648);
    assert_eq!(i64_to_saturated_i32(-2147483648), -2147483648);
    assert_eq!(i64_to_saturated_i32(-2147483647), -2147483647);
    assert_eq!(i64_to_saturated_i32(-2147483646), -2147483646);
    assert_eq!(i64_to_saturated_i32(-100), -100);
    assert_eq!(i64_to_saturated_i32(0), 0);
    assert_eq!(i64_to_saturated_i32(100), 100);
    assert_eq!(i64_to_saturated_i32(2147483646), 2147483646);
    assert_eq!(i64_to_saturated_i32(2147483647), 2147483647);
    assert_eq!(i64_to_saturated_i32(2147483648), 2147483647);
    assert_eq!(i64_to_saturated_i32(2147483649), 2147483647);
    assert_eq!(i64_to_saturated_i32(i64::MAX), i32::MAX);
}