concentric_circles 0.1.0

Efficient generation and iteration of concentric circle perimeters using Bresenham's algorithm.
Documentation
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
#![no_std]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![forbid(clippy::float_arithmetic)]
#![cfg(target_pointer_width = "64")]
#![deny(clippy::all)]
/*!
# concentric_circles

A Rust library for efficient generation and iteration of concentric circle perimeters using Bresenham's algorithm.

- **No floating-point types are used:** all calculations are performed with integer types for maximum performance and precision.
- Provides iterator adapters for coloring, sector extraction, coordinate mapping, and more.
- Suitable for image processing, procedural graphics, and scientific visualization.
- No heap allocations; works in `no_std` environments.

## Type Limits

**Note:**
The maximum allowed radius depends on the types used for the coordinates and the radius.
For example, if you use `i8` for points and `u8` for the radius, the maximum safe radius is `i8::MAX - 1` (i.e., 126).
If you specify a larger radius, an empty iterator is returned—no panic or overflow will occur.

## Visual Examples

Below are images demonstrating how `ConcentricCircles` renders. These were generated by example programs in the `examples` folder.

Run them with `cargo run --example example_name`.

<div class="subContainer">
    <a href="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/basic_iter.png">
        <img src="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/basic_iter.png" class="border"></img>
    </a>
    <div class="imageDesc border">
        <div>The iterator</div>
        <div>basic_iterator</div>
    </div>
</div>

<div class="subContainer">
    <a target="_blank" href="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/add_color_radial.png">
        <img src="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/add_color_radial.png" class="border"></img>
    </a>
    <div class="imageDesc border">
        <div>The adapter</div>
        <div>add_color_radial</div>
    </div>
</div>

<div class="subContainer">
    <a target="_blank" href="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/circle_sector.png">
        <img src="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/circle_sector.png" class="border"></img>
    </a>
    <div class="imageDesc border">
        <div>The adapter</div>
        <div>circle_sector</div>
    </div>
</div>

<div class="subContainer">
    <a target="_blank" href="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/map_circle_sector.png">
        <img src="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/map_circle_sector.png" class="border"></img>
    </a>
    <div class="imageDesc border">
        <div>The adapter</div>
        <div>map_circle_sector</div>
    </div>
</div>

<div class="subContainer">
    <a target="_blank" href="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/map_color_radial.png">
        <img src="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/map_color_radial.png" class="border"></img>
    </a>
    <div class="imageDesc border">
        <div>The adapter</div>
        <div>map_color_radial</div>
    </div>
</div>

<div class="subContainer">
    <a target="_blank" href="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/crown_adapter.png">
        <img src="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/crown_adapter.png" class="border"></img>
    </a>
    <div class="imageDesc border">
        <div>The adapter</div>
        <div>crown</div>
    </div>
</div>

<div class="subContainer">
    <a target="_blank" href="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/step_rings.png">
        <img src="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/step_rings.png" class="border"></img>
    </a>
    <div class="imageDesc border">
        <div>The adapter</div>
        <div>step_rings</div>
    </div>
</div>
<div class="subContainer">
    <a target="_blank" href="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/to_image_coordinates.png">
        <img src="https://raw.githubusercontent.com/pic16f877ccs/image/refs/heads/pixelization/to_image_coordinates.png" class="border"></img>
    </a>
    <div class="imageDesc border">
        <div>The adapter</div>
        <div>to_image_coordinates</div>
    </div>
</div>

<style>
    .subContainer {
        margin: auto;
        padding: 5px;
        float: left;
        width: 180px;
    }

    .border {
        border: 1px solid #f0f0f0;
        border-radius: 5px;
    }

    img {
        padding: 5px;
    }

    .subContainer:hover img {
        border: 1px solid #777;
    }

    .imageDesc.border {
        background-color: Rgb(252, 252, 252);
        text-align: center;
        font-family: Arial, Helvetica, sans-serif;
        text-shadow: 5px 5px 5px Rgb(200, 200, 200);
    }
</style>
*/

use core::fmt::Debug;
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::ops::{Add, AddAssign, RangeInclusive, Shr, Sub, SubAssign};
use iterextd::{Scaler, Scaling};
use num_convert::FromAs;
use num_traits::{CheckedAdd, Signed, Unsigned, Zero};

mod concentric_circles_adapters;
mod point_with_color;
mod radii;
mod scaling;

pub use concentric_circles_adapters::{
    AddColor, AddColorRadial, CircleSectorSkip, CircleSectorTake, ConcentricCirclesAdapters, Crown,
    PointWithRadius, StepRings, ToImageCoordinates,
};
pub use point_with_color::{
    CrownWithColor, MapCircleSector, MapColorRadial, PointWithColor, ToImageCoordinatesWithColor,
};
pub use radii::Radii;
pub use scaling::ScalingU32;

/**
An iterator over concentric circle perimeters using Bresenham's algorithm.

`ConcentricCircles` yields pixel coordinates `(x, y)` that trace the perimeter
of circles with integer radii, starting from `inner_radius` and continuing to
`outer_radius`, inclusive.

Each circle is generated using Bresenham’s circle algorithm centered at `(0, 0)`.
Coordinates are yielded one at a time, with overlapping perimeters to avoid visual gaps.

To position the circles within an image or apply other coordinate transformations,
use an appropriate iterator adapter from this crate.
*/
#[derive(Clone, Debug, PartialEq)]
pub struct ConcentricCircles<T, U> {
    x: T,
    y: T,
    d: T,
    outer_radius: U,
    inner_radius: U,
    current_quadrant: u8,
    radius_pending: bool,
}

impl<T, U> ConcentricCircles<T, U>
where
    T: Signed + FromAs<U> + TryFrom<U> + Shr<Output = T> + CheckedAdd + Copy,
    U: Unsigned + PartialOrd + Copy,
{
    /// Creates a new `ConcentricCircles` iterator over radii.
    ///
    /// Starts from `inner_radius` and goes up to `outer_radius`, inclusive.
    ///
    /// # Arguments
    ///
    /// * `inner_radius`: The starting radius of the first circle (inclusive).
    ///   Must not be zero and must not be greater than `outer_radius`.
    /// * `outer_radius`: The ending radius of the last circle (inclusive).
    ///
    /// # Returns
    ///
    /// Returns an iterator that yields `(x, y)` coordinates for each point on the circle's perimeter.
    /// If `inner_radius` is zero or greater than `outer_radius`, an empty iterator is returned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use concentric_circles::ConcentricCircles;
    ///
    /// let iter = ConcentricCircles::<i32, u32>::new(5, 10);
    /// assert!(iter.count() > 0);
    ///
    /// let empty = ConcentricCircles::<i32, u32>::new(0, 10);
    /// assert_eq!(empty.count(), 0);
    ///
    /// let empty2 = ConcentricCircles::<i32, u32>::new(11, 10);
    /// assert_eq!(empty2.count(), 0);
    /// ```
    #[inline]
    pub fn new(inner_radius: U, outer_radius: U) -> Self {
        let current_quadrant = if (inner_radius == U::zero()) || (inner_radius > outer_radius) {
            5
        } else if let Ok(value) = T::try_from(outer_radius) {
            if value.checked_add(&T::one()).is_some() {
                0
            } else {
                5
            }
        } else {
            5
        };

        Self {
            x: T::one(),
            y: T::from_as(inner_radius),
            d: -(T::from_as(inner_radius) >> T::one()),
            outer_radius,
            inner_radius,
            current_quadrant,
            radius_pending: false,
        }
    }
}

impl<T, U> Iterator for ConcentricCircles<T, U>
where
    T: Signed + AddAssign + FromAs<U> + PartialOrd + SubAssign + Shr<Output = T> + Copy,
    U: Unsigned + AddAssign + PartialOrd + SubAssign + Copy,
    usize: FromAs<U>,
{
    type Item = (T, T);

    #[allow(clippy::precedence)]
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.current_quadrant == 0 {
            let xy = (self.x - T::one(), -self.y);

            if self.radius_pending {
                self.inner_radius += U::one();
                self.radius_pending = false;
            }

            if self.d < T::zero() {
                self.x += T::one();
                self.d += self.x;
            } else {
                self.y -= T::one();
                self.d -= self.y;

                if self.y <= T::zero() {
                    self.x = T::one();
                    self.y = T::from_as(self.inner_radius);
                    self.d = -(T::from_as(self.inner_radius) >> T::one());
                    self.current_quadrant = 1;
                }
            }

            Some((xy.0, xy.1))
        } else if self.current_quadrant == 1 {
            let xy = (self.y - T::one(), self.x - T::one());

            if self.d < T::zero() {
                self.x += T::one();
                self.d += self.x;
            } else {
                self.y -= T::one();
                self.d -= self.y;

                if self.y <= T::zero() {
                    self.x = T::one();
                    self.y = T::from_as(self.inner_radius);
                    self.d = -(T::from_as(self.inner_radius) >> T::one());
                    self.current_quadrant = 2;
                }
            }

            Some((xy.0, xy.1))
        } else if self.current_quadrant == 2 {
            let xy = (-self.x, self.y - T::one());

            if self.d < T::zero() {
                self.x += T::one();
                self.d += self.x;
            } else {
                self.y -= T::one();
                self.d -= self.y;

                if self.y <= T::zero() {
                    self.x = T::one();
                    self.y = T::from_as(self.inner_radius);
                    self.d = -(T::from_as(self.inner_radius) >> T::one());
                    self.current_quadrant = 3;
                }
            }

            Some((xy.0, xy.1))
        } else if self.current_quadrant == 3 {
            let xy = (-self.y, -self.x);

            if self.d < T::zero() {
                self.x += T::one();
                self.d += self.x;
            } else {
                self.y -= T::one();
                self.d -= self.y;

                if self.y <= T::zero() {
                    if self.inner_radius == self.outer_radius {
                        self.current_quadrant = 4;
                    } else {
                        self.current_quadrant = 0;
                        self.radius_pending = true;
                    }

                    self.y = T::from_as(self.inner_radius) + T::one();
                    self.d = -(T::from_as(self.inner_radius) + T::one() >> T::one());
                    self.x = T::one();

                    return Some(xy);
                }
            }

            Some(xy)
        } else {
            None
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (
            0,
            sum_circles_points(
                usize::from_as(self.inner_radius),
                usize::from_as(self.outer_radius),
            ),
        )
    }
}

impl<T, U> FusedIterator for ConcentricCircles<T, U>
where
    T: Signed + FromAs<U> + PartialOrd + AddAssign + SubAssign + Shr<Output = T> + Copy,
    U: Unsigned + PartialOrd + SubAssign + AddAssign + Copy,
    usize: FromAs<U>,
{
}

/// Returns the number of points on the perimeter of a circle for a given radius, or `None` if the radius is zero.
///
/// # Arguments
///
/// * `radius` - The radius of the circle.
///
/// # Returns
///
/// Returns `Some(points)` — the number of points (pixels) on the circle's perimeter,
/// or `None` if the radius is zero or if an overflow occurs.
///
/// # Examples
///
/// ```rust
/// use concentric_circles::points_in_circle;
///
/// assert_eq!(points_in_circle(5), Some(36));
/// assert_eq!(points_in_circle(0), None);
/// ```
#[inline]
pub fn points_in_circle(radius: usize) -> Option<usize> {
    if radius == 0 {
        None
    } else {
        Some(8_usize.checked_mul(radius)? - 4)
    }
}

#[inline]
pub(crate) fn points_in_circle_unchecked(radius: usize) -> usize {
    if radius == 0 {
        0
    } else {
        8 * radius - 4
    }
}

/// Returns the radius of a circle for a given number of points on its perimeter, if possible.
///
/// # Arguments
///
/// * `points` - The number of points on the circle's perimeter.
///
/// # Returns
///
/// Returns `Some(radius)` if the number of points corresponds exactly to a valid circle perimeter,
/// otherwise returns `None`.
///
/// # Examples
///
/// ```rust
/// use concentric_circles::radius_from_circle_points;
///
/// assert_eq!(radius_from_circle_points(0), None);
/// assert_eq!(radius_from_circle_points(1), None);
/// assert_eq!(radius_from_circle_points(4), Some(1));
/// assert_eq!(radius_from_circle_points(5), None);
/// ```
#[inline]
pub fn radius_from_circle_points(points: usize) -> Option<usize> {
    let r = points.checked_add(4)?;
    if r % 8 == 0 {
        Some(r >> 3)
    } else {
        None
    }
}

/// Returns the total number of points on the perimeters of circles with radii from `from` to `to` (inclusive).
///
/// Uses the formula for the number of points on a circle's perimeter.
///
/// # Arguments
///
/// * `from` - The starting radius (inclusive).
/// * `to` - The ending radius (inclusive).
///
/// # Returns
///
/// The total number of points on all circles from `from` to `to`.
/// Returns `None` if:
/// * `from` is zero (invalid radius),
/// * `from > to` (invalid range),
/// * or an overflow occurs during the internal arithmetic.
///
/// # Examples
///
/// ```rust
/// use concentric_circles::sum_circles_points;
///
/// let sum_points = sum_circles_points(1, 5);
/// assert_eq!(sum_points, Some(100)); // 4 + 12 + 20 + 28 + 36 = 100
/// ```
#[inline]
pub fn sum_circles_points(from: usize, to: usize) -> Option<usize> {
    if from == 0 || from > to {
        None
    } else {
        let n = to - from + 1;
        let sum_r = from.checked_add(to)?.checked_mul(n)? / 2;

        Some(8_usize.checked_mul(sum_r)? - 4_usize.checked_mul(n)?)
    }
}

#[inline]
pub(crate) fn sum_circles_points_unchecked(from: usize, to: usize) -> usize {
    let n = to - from + 1;
    let sum_r = (from + to) * n / 2;

    8 * sum_r - 4 * n
}

#[cfg(test)]
mod tests {
    use super::sum_circles_points_unchecked;

    #[test]
    fn test_sum_points_in_circle_uncheckeds() {
        assert_eq!(sum_circles_points_unchecked(1, 1), 4);
        assert_eq!(sum_circles_points_unchecked(1, 2), 4 + 12);
        assert_eq!(sum_circles_points_unchecked(2, 2), 12);
        assert_eq!(sum_circles_points_unchecked(1, 3), 4 + 12 + 20);
        assert_eq!(sum_circles_points_unchecked(2, 3), 12 + 20);
        assert_eq!(sum_circles_points_unchecked(3, 3), 20);
        assert_eq!(sum_circles_points_unchecked(1, 4), 4 + 12 + 20 + 28);
        assert_eq!(sum_circles_points_unchecked(2, 4), 12 + 20 + 28);
        assert_eq!(sum_circles_points_unchecked(3, 4), 20 + 28);
        assert_eq!(sum_circles_points_unchecked(4, 4), 28);
        assert_eq!(sum_circles_points_unchecked(1, 5), 4 + 12 + 20 + 28 + 36);
        assert_eq!(sum_circles_points_unchecked(2, 5), 12 + 20 + 28 + 36);
        assert_eq!(sum_circles_points_unchecked(3, 5), 20 + 28 + 36);
        assert_eq!(sum_circles_points_unchecked(4, 5), 28 + 36);
        assert_eq!(sum_circles_points_unchecked(5, 5), 36);
    }

    #[should_panic(expected = "attempt to add with overflow")]
    #[test]
    fn test_sum_points_in_circle_uncheckeds_max_values() {
        let _ = sum_circles_points_unchecked(usize::MAX, usize::MAX);
    }

    #[should_panic(expected = "attempt to add with overflow")]
    #[test]
    fn test_sum_points_in_circle_uncheckeds_max_end_value() {
        let _ = sum_circles_points_unchecked(1, usize::MAX);
    }
}