|
| 1 | +// Copyright 2024 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include "ink/geometry/internal/modulo.h" |
| 16 | + |
| 17 | +#include <cmath> |
| 18 | + |
| 19 | +#include "absl/log/absl_check.h" |
| 20 | + |
| 21 | +namespace ink::geometry_internal { |
| 22 | + |
| 23 | +float FloatModulo(float a, float b) { |
| 24 | + ABSL_DCHECK(std::isfinite(b) && b > 0.f); |
| 25 | + float result = std::fmodf(a, b); |
| 26 | + // `fmodf` always matches the sign of the first argument, so `fmodf(a, b)` |
| 27 | + // returns a value in the range (-b, b). We want [0, b), so wrap negative |
| 28 | + // values back to positive. |
| 29 | + if (result < 0.f) { |
| 30 | + result += b; |
| 31 | + // If `fmodf` returned a sufficiently small negative number, then adding `b` |
| 32 | + // will give us a result exactly equal to `b`, due to float rounding. |
| 33 | + // However, `FloatModulo` promises to return a value strictly less than `b`, |
| 34 | + // so we should return zero in this case. |
| 35 | + if (result == b) { |
| 36 | + result = 0.f; |
| 37 | + } |
| 38 | + } |
| 39 | + return result; |
| 40 | +} |
| 41 | + |
| 42 | +} // namespace ink::geometry_internal |
0 commit comments