rasterrocket-render 1.0.0

Software rasterizer — path fill, compositing, and AVX-512/AVX2/NEON SIMD for the rasterrocket PDF renderer
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
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
//! Glyph bitmap blitting — replaces `Splash::fillGlyph2`.
//!
//! A glyph bitmap is either:
//! - **AA** (`aa = true`): one byte per pixel, containing a coverage value 0–255.
//! - **Mono** (`aa = false`): 1-bit-per-pixel, MSB-first packed, `ceil(w/8)` bytes per row.
//!
//! The blit clips to the destination bitmap bounds and optionally to the `Clip` region.
//!
//! # C++ equivalent
//! `Splash::fillGlyph2`.

use crate::bitmap::Bitmap;
use crate::clip::{Clip, ClipResult};
use crate::pipe::{self, PipeSrc, PipeState};
use crate::simd;
use color::Pixel;

/// A rasterized glyph bitmap as produced by a font renderer.
///
/// The origin `(x, y)` is the pen-position offset in device pixels:
/// the top-left of the bitmap maps to `(pen_x - x, pen_y - y)`.
pub struct GlyphBitmap<'a> {
    /// Raw bitmap data. For AA glyphs: `w` bytes per row. For mono: `ceil(w/8)` bytes per row.
    pub data: &'a [u8],
    /// Horizontal offset from the pen position to the left edge of the bitmap.
    pub x: i32,
    /// Vertical offset from the pen position to the top edge of the bitmap.
    pub y: i32,
    /// Width in pixels.
    pub w: i32,
    /// Height in pixels.
    pub h: i32,
    /// `true` for anti-aliased (one u8 coverage byte per pixel);
    /// `false` for 1-bit MSB-first packed mono.
    pub aa: bool,
}

impl GlyphBitmap<'_> {
    /// Number of bytes per row in `data`.
    #[must_use]
    pub fn row_bytes(&self) -> usize {
        let w = self.w.max(0);
        if self.aa {
            #[expect(clippy::cast_sign_loss, reason = "w = self.w.max(0) is non-negative")]
            {
                w as usize
            }
        } else {
            // Use saturating_add so a pathological w near i32::MAX doesn't wrap.
            // In practice FreeType glyphs are always < 2^16 px wide.
            #[expect(clippy::cast_sign_loss, reason = "w = self.w.max(0) is non-negative")]
            {
                (w.saturating_add(7) / 8) as usize
            }
        }
    }
}

/// Blit a glyph at pen position `(pen_x, pen_y)` (device pixel coordinates).
///
/// `clip_all_inside` — if `true`, skip per-pixel clip tests (the caller has
/// already determined the entire glyph bbox is inside the clip region).
/// When `false`, the `clip` is tested per pixel.
///
/// The `pipe` and `src` describe the fill colour and compositing parameters.
///
/// # C++ equivalent
///
/// Matches `Splash::fillGlyph2` with `noClip = clip_all_inside`.
#[expect(
    clippy::too_many_arguments,
    reason = "mirrors Splash::fillGlyph2 API; all params necessary"
)]
pub fn blit_glyph<P: Pixel>(
    bitmap: &mut Bitmap<P>,
    clip: &Clip,
    clip_all_inside: bool,
    pipe: &PipeState<'_>,
    src: &PipeSrc<'_>,
    pen_x: i32,
    pen_y: i32,
    glyph: &GlyphBitmap<'_>,
) {
    // Compute the top-left destination pixel.
    let x_start_raw = pen_x - glyph.x;
    let y_start_raw = pen_y - glyph.y;

    // Clamp to bitmap bounds.
    #[expect(
        clippy::cast_possible_wrap,
        reason = "bitmap dims ≤ i32::MAX in practice"
    )]
    let bmp_w = bitmap.width as i32;
    #[expect(
        clippy::cast_possible_wrap,
        reason = "bitmap dims ≤ i32::MAX in practice"
    )]
    let bmp_h = bitmap.height as i32;

    let x_clip = x_start_raw.max(0);
    let y_clip = y_start_raw.max(0);
    let x_end = (x_start_raw + glyph.w).min(bmp_w);
    let y_end = (y_start_raw + glyph.h).min(bmp_h);

    if x_clip >= x_end || y_clip >= y_end {
        return;
    }

    // All four differences are non-negative because of the checks above.
    #[expect(
        clippy::cast_sign_loss,
        reason = "x_clip ≥ x_start_raw.max(0) so difference ≥ 0"
    )]
    let x_data_skip = (x_clip - x_start_raw) as usize;
    #[expect(
        clippy::cast_sign_loss,
        reason = "y_clip ≥ y_start_raw.max(0) so difference ≥ 0"
    )]
    let y_data_skip = (y_clip - y_start_raw) as usize;
    #[expect(clippy::cast_sign_loss, reason = "x_end > x_clip by guard above")]
    let xx_limit = (x_end - x_clip) as usize;
    #[expect(clippy::cast_sign_loss, reason = "y_end > y_clip by guard above")]
    let yy_limit = (y_end - y_clip) as usize;
    let row_bytes = glyph.row_bytes();

    if glyph.aa {
        blit_aa::<P>(
            bitmap,
            clip,
            clip_all_inside,
            pipe,
            src,
            glyph,
            x_clip,
            y_clip,
            x_data_skip,
            y_data_skip,
            xx_limit,
            yy_limit,
            row_bytes,
        );
    } else {
        blit_mono::<P>(
            bitmap,
            clip,
            clip_all_inside,
            pipe,
            src,
            glyph,
            x_clip,
            y_clip,
            x_data_skip,
            y_data_skip,
            xx_limit,
            yy_limit,
            row_bytes,
        );
    }
}

/// Blit an AA (per-byte coverage) glyph.
#[expect(
    clippy::too_many_arguments,
    reason = "internal helper; all params necessary for this blit path"
)]
fn blit_aa<P: Pixel>(
    bitmap: &mut Bitmap<P>,
    clip: &Clip,
    clip_all_inside: bool,
    pipe: &PipeState<'_>,
    src: &PipeSrc<'_>,
    glyph: &GlyphBitmap<'_>,
    x_start: i32,
    y_start: i32,
    x_data_skip: usize,
    y_data_skip: usize,
    xx_limit: usize,
    yy_limit: usize,
    row_bytes: usize,
) {
    let data = glyph.data;
    // Verify the glyph data buffer covers the visible region.  A mismatch
    // indicates a malformed GlyphBitmap (wrong w/h/row_bytes); we clamp via
    // get() in the inner loop, but the assert catches it in debug builds.
    debug_assert!(
        data.len() >= (y_data_skip + yy_limit) * row_bytes,
        "blit_aa: glyph data too short: len={} < (y_data_skip={y_data_skip} + yy_limit={yy_limit}) * row_bytes={row_bytes}",
        data.len(),
    );
    // Hoisted above the row loop to avoid per-row heap allocation.
    let mut run_shape: Vec<u8> = Vec::new();

    for yy in 0..yy_limit {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "yy < yy_limit ≤ bitmap.height ≤ i32::MAX"
        )]
        #[expect(clippy::cast_possible_wrap, reason = "yy < bitmap.height ≤ i32::MAX")]
        let y = y_start + yy as i32;
        let row_off = (y_data_skip + yy) * row_bytes + x_data_skip;

        let mut run_start: Option<i32> = None;
        run_shape.clear();

        for xx in 0..xx_limit {
            #[expect(
                clippy::cast_possible_truncation,
                reason = "xx < xx_limit ≤ bitmap.width ≤ i32::MAX"
            )]
            #[expect(clippy::cast_possible_wrap, reason = "xx < bitmap.width ≤ i32::MAX")]
            let x = x_start + xx as i32;
            let data_idx = row_off + xx;
            let alpha = data.get(data_idx).copied().unwrap_or(0);
            let inside_clip = clip_all_inside || clip.test(x, y);

            if inside_clip && alpha != 0 {
                if run_start.is_none() {
                    run_start = Some(x);
                    run_shape.clear();
                }
                run_shape.push(alpha);
            } else if let Some(rs) = run_start.take() {
                emit_aa_run::<P>(bitmap, pipe, src, rs, y, &run_shape);
            }
        }
        if let Some(rs) = run_start.take() {
            emit_aa_run::<P>(bitmap, pipe, src, rs, y, &run_shape);
        }
    }
}

/// Blit a mono (1-bit packed) glyph.
#[expect(
    clippy::too_many_arguments,
    reason = "internal helper; all params necessary"
)]
#[expect(
    clippy::too_many_lines,
    reason = "function handles both SIMD and scalar mono-unpack paths; splitting further would obscure the logic"
)]
fn blit_mono<P: Pixel>(
    bitmap: &mut Bitmap<P>,
    clip: &Clip,
    clip_all_inside: bool,
    pipe: &PipeState<'_>,
    src: &PipeSrc<'_>,
    glyph: &GlyphBitmap<'_>,
    x_start: i32,
    y_start: i32,
    x_data_skip: usize,
    y_data_skip: usize,
    xx_limit: usize,
    yy_limit: usize,
    row_bytes: usize,
) {
    let x_shift = x_data_skip % 8;
    let data = glyph.data;

    // Verify the glyph data buffer covers the visible region (debug builds only).
    debug_assert!(
        data.len() >= (y_data_skip + yy_limit) * row_bytes,
        "blit_mono: glyph data too short: len={} < (y_data_skip={y_data_skip} + yy_limit={yy_limit}) * row_bytes={row_bytes}",
        data.len(),
    );

    // Scratch buffer for SIMD-expanded bits: one byte per pixel, 0x00 or 0xFF.
    // Sized to the maximum row width; reused across rows.
    let mut expanded: Vec<u8> = vec![0u8; xx_limit];

    for yy in 0..yy_limit {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "yy < yy_limit ≤ bitmap.height ≤ i32::MAX"
        )]
        #[expect(clippy::cast_possible_wrap, reason = "yy < bitmap.height ≤ i32::MAX")]
        let y = y_start + yy as i32;
        let row_off = (y_data_skip + yy) * row_bytes + x_data_skip / 8;

        // Use SIMD unpack when x_shift == 0 (bits are byte-aligned).
        // When x_shift > 0 the pixels straddle byte boundaries, so we fall
        // back to the scalar bit-extraction path which handles that case.
        #[cfg(target_arch = "x86_64")]
        let use_simd_unpack = x_shift == 0;
        #[cfg(not(target_arch = "x86_64"))]
        let use_simd_unpack = false;

        if use_simd_unpack {
            let packed_row = &data[row_off..];
            simd::unpack_mono_row(packed_row, xx_limit, &mut expanded);

            let mut run_start: Option<i32> = None;
            for (xx, &cov) in expanded[..xx_limit].iter().enumerate() {
                #[expect(
                    clippy::cast_possible_truncation,
                    reason = "xx < xx_limit ≤ bitmap.width ≤ i32::MAX"
                )]
                #[expect(clippy::cast_possible_wrap, reason = "xx < bitmap.width ≤ i32::MAX")]
                let x = x_start + xx as i32;
                let set = cov != 0;
                let inside_clip = clip_all_inside || clip.test(x, y);

                if set && inside_clip {
                    if run_start.is_none() {
                        run_start = Some(x);
                    }
                } else if let Some(rs) = run_start.take() {
                    let rx1 = x - 1;
                    emit_solid_run::<P>(bitmap, pipe, src, rs, rx1, y);
                }
            }
            if let Some(rs) = run_start.take() {
                #[expect(
                    clippy::cast_possible_truncation,
                    reason = "xx_limit ≤ bitmap.width ≤ i32::MAX"
                )]
                #[expect(
                    clippy::cast_possible_wrap,
                    reason = "xx_limit < bitmap.width ≤ i32::MAX"
                )]
                let rx1 = x_start + xx_limit as i32 - 1;
                emit_solid_run::<P>(bitmap, pipe, src, rs, rx1, y);
            }
            continue;
        }

        let mut run_start: Option<i32> = None;
        let mut xx = 0usize;

        while xx < xx_limit {
            let byte_idx = row_off + xx / 8;

            // When x_shift > 0, straddle two source bytes to align the read window.
            let alpha0 = if x_shift > 0 && xx + 8 < xx_limit {
                let lo = data.get(byte_idx).copied().unwrap_or(0);
                let hi = data.get(byte_idx + 1).copied().unwrap_or(0);
                #[expect(clippy::cast_possible_truncation, reason = "shift result fits in u8")]
                {
                    (u16::from(lo) << x_shift | u16::from(hi) >> (8 - x_shift)) as u8
                }
            } else {
                data.get(byte_idx).copied().unwrap_or(0)
            };

            let bits_this_byte = (xx_limit - xx).min(8);
            for bit in 0..bits_this_byte {
                #[expect(
                    clippy::cast_possible_truncation,
                    reason = "xx + bit < xx_limit ≤ bitmap.width ≤ i32::MAX"
                )]
                #[expect(
                    clippy::cast_possible_wrap,
                    reason = "xx + bit < bitmap.width ≤ i32::MAX"
                )]
                let x = x_start + (xx + bit) as i32;
                let set = (alpha0 >> (7 - bit)) & 1 != 0;
                let inside_clip = clip_all_inside || clip.test(x, y);

                if set && inside_clip {
                    if run_start.is_none() {
                        run_start = Some(x);
                    }
                } else if let Some(rs) = run_start.take() {
                    let rx1 = x - 1;
                    emit_solid_run::<P>(bitmap, pipe, src, rs, rx1, y);
                }
            }
            xx += bits_this_byte;
        }
        if let Some(rs) = run_start.take() {
            #[expect(
                clippy::cast_possible_truncation,
                reason = "xx_limit ≤ bitmap.width ≤ i32::MAX"
            )]
            #[expect(
                clippy::cast_possible_wrap,
                reason = "xx_limit < bitmap.width ≤ i32::MAX"
            )]
            let rx1 = x_start + xx_limit as i32 - 1;
            emit_solid_run::<P>(bitmap, pipe, src, rs, rx1, y);
        }
    }
}

/// Emit one AA-shaped span via `render_span`.
fn emit_aa_run<P: Pixel>(
    bitmap: &mut Bitmap<P>,
    pipe: &PipeState<'_>,
    src: &PipeSrc<'_>,
    x0: i32,
    y: i32,
    shape: &[u8],
) {
    debug_assert!(!shape.is_empty());
    // shape.len() ≤ bitmap.width ≤ i32::MAX in practice.
    #[expect(
        clippy::cast_possible_truncation,
        reason = "shape.len() ≤ bitmap.width ≤ i32::MAX"
    )]
    #[expect(
        clippy::cast_possible_wrap,
        reason = "shape.len() ≤ bitmap.width ≤ i32::MAX"
    )]
    let x1 = x0 + shape.len() as i32 - 1;
    #[expect(clippy::cast_sign_loss, reason = "y ≥ 0 by construction")]
    let y_u = y as u32;
    #[expect(clippy::cast_sign_loss, reason = "x0 ≥ 0")]
    let byte_off = x0 as usize * P::BYTES;
    #[expect(clippy::cast_sign_loss, reason = "x1 ≥ x0 ≥ 0")]
    let byte_end = (x1 as usize + 1) * P::BYTES;
    #[expect(clippy::cast_sign_loss, reason = "x0 ≥ 0, x1 ≥ x0")]
    let alpha_range = x0 as usize..=x1 as usize;

    let (row, alpha) = bitmap.row_and_alpha_mut(y_u);
    let dst_pixels = &mut row[byte_off..byte_end];
    let dst_alpha = alpha.map(|a| &mut a[alpha_range]);

    pipe::render_span::<P>(pipe, src, dst_pixels, dst_alpha, Some(shape), x0, x1, y);
}

/// Emit a fully opaque span (mono glyph pixels) via `render_span`.
fn emit_solid_run<P: Pixel>(
    bitmap: &mut Bitmap<P>,
    pipe: &PipeState<'_>,
    src: &PipeSrc<'_>,
    x0: i32,
    x1: i32,
    y: i32,
) {
    debug_assert!(x0 <= x1);
    #[expect(clippy::cast_sign_loss, reason = "y ≥ 0 by construction")]
    let y_u = y as u32;
    #[expect(clippy::cast_sign_loss, reason = "x0 ≥ 0")]
    let byte_off = x0 as usize * P::BYTES;
    #[expect(clippy::cast_sign_loss, reason = "x1 ≥ x0 ≥ 0")]
    let byte_end = (x1 as usize + 1) * P::BYTES;
    #[expect(clippy::cast_sign_loss, reason = "x0 ≥ 0, x1 ≥ x0")]
    let alpha_range = x0 as usize..=x1 as usize;

    let (row, alpha) = bitmap.row_and_alpha_mut(y_u);
    let dst_pixels = &mut row[byte_off..byte_end];
    let dst_alpha = alpha.map(|a| &mut a[alpha_range]);

    pipe::render_span::<P>(pipe, src, dst_pixels, dst_alpha, None, x0, x1, y);
}

/// Clip-test a glyph bbox and blit it.
///
/// Convenience wrapper that performs the `testRect` + `fillGlyph2` pattern from
/// `Splash::fillGlyph`. Returns the `ClipResult` for the caller to record as `opClipRes`.
pub fn fill_glyph<P: Pixel>(
    bitmap: &mut Bitmap<P>,
    clip: &Clip,
    pipe: &PipeState<'_>,
    src: &PipeSrc<'_>,
    pen_x: i32,
    pen_y: i32,
    glyph: &GlyphBitmap<'_>,
) -> ClipResult {
    let x0 = pen_x - glyph.x;
    let y0 = pen_y - glyph.y;
    let x1 = x0 + glyph.w - 1;
    let y1 = y0 + glyph.h - 1;

    let clip_res = clip.test_rect(x0, y0, x1, y1);
    if clip_res != ClipResult::AllOutside {
        blit_glyph::<P>(
            bitmap,
            clip,
            clip_res == ClipResult::AllInside,
            pipe,
            src,
            pen_x,
            pen_y,
            glyph,
        );
    }
    clip_res
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bitmap::Bitmap;
    use crate::pipe::PipeSrc;
    use crate::testutil::{make_clip, simple_pipe};
    use color::Rgb8;

    #[test]
    fn blit_aa_glyph_paints_pixels() {
        let mut bmp: Bitmap<Rgb8> = Bitmap::new(8, 8, 4, false);
        let clip = make_clip(8, 8);
        let pipe = simple_pipe();
        let color = [255u8, 0, 0];
        let src = PipeSrc::Solid(&color);

        // 4×4 AA glyph with full coverage (255) everywhere.
        let data = vec![255u8; 16];
        let glyph = GlyphBitmap {
            data: &data,
            x: 0,
            y: 0,
            w: 4,
            h: 4,
            aa: true,
        };

        blit_glyph::<Rgb8>(&mut bmp, &clip, true, &pipe, &src, 2, 2, &glyph);

        // Rows 2..5, cols 2..5 should be red.
        for y in 2..6u32 {
            let row = bmp.row(y);
            for (x, px) in row.iter().enumerate().skip(2).take(4) {
                assert_eq!(px.r, 255, "y={y} x={x} R");
            }
        }
        assert_eq!(bmp.row(1)[1].r, 0);
    }

    #[test]
    fn blit_aa_glyph_zero_coverage_skips() {
        let mut bmp: Bitmap<Rgb8> = Bitmap::new(4, 4, 4, false);
        let clip = make_clip(4, 4);
        let pipe = simple_pipe();
        let color = [255u8, 0, 0];
        let src = PipeSrc::Solid(&color);

        let data = vec![0u8; 4];
        let glyph = GlyphBitmap {
            data: &data,
            x: 0,
            y: 0,
            w: 2,
            h: 2,
            aa: true,
        };

        blit_glyph::<Rgb8>(&mut bmp, &clip, true, &pipe, &src, 0, 0, &glyph);

        for y in 0..4u32 {
            let row = bmp.row(y);
            for px in row.iter().take(4) {
                assert_eq!(px.r, 0, "should be unpainted");
            }
        }
    }

    #[test]
    fn blit_mono_glyph_paints_set_bits() {
        let mut bmp: Bitmap<Rgb8> = Bitmap::new(8, 4, 4, false);
        let clip = make_clip(8, 4);
        let pipe = simple_pipe();
        let color = [0u8, 255, 0];
        let src = PipeSrc::Solid(&color);

        // 8×2 mono glyph: row 0 all-set (0xFF), row 1 all-clear (0x00).
        let data = [0xFFu8, 0x00u8];
        let glyph = GlyphBitmap {
            data: &data,
            x: 0,
            y: 0,
            w: 8,
            h: 2,
            aa: false,
        };

        blit_glyph::<Rgb8>(&mut bmp, &clip, true, &pipe, &src, 0, 0, &glyph);

        let row0 = bmp.row(0);
        for (x, px) in row0.iter().enumerate().take(8) {
            assert_eq!(px.g, 255, "row 0 x={x} should be painted");
        }
        let row1 = bmp.row(1);
        for (x, px) in row1.iter().enumerate().take(8) {
            assert_eq!(px.g, 0, "row 1 x={x} should be clear");
        }
    }

    #[test]
    fn blit_glyph_clip_excludes_outside() {
        let mut bmp: Bitmap<Rgb8> = Bitmap::new(8, 8, 4, false);
        let clip = Clip::new(2.0, 2.0, 5.0, 5.0, false);
        let pipe = simple_pipe();
        let color = [255u8, 0, 0];
        let src = PipeSrc::Solid(&color);

        let data = vec![255u8; 16];
        let glyph = GlyphBitmap {
            data: &data,
            x: 0,
            y: 0,
            w: 4,
            h: 4,
            aa: true,
        };

        blit_glyph::<Rgb8>(&mut bmp, &clip, false, &pipe, &src, 0, 0, &glyph);

        assert_eq!(bmp.row(0)[0].r, 0, "row 0 should be clipped");
        assert_eq!(bmp.row(1)[0].r, 0, "row 1 should be clipped");
        assert_eq!(bmp.row(2)[2].r, 255, "(2,2) should be painted");
    }

    #[test]
    fn fill_glyph_returns_clip_result() {
        let mut bmp: Bitmap<Rgb8> = Bitmap::new(8, 8, 4, false);
        let clip = make_clip(8, 8);
        let pipe = simple_pipe();
        let color = [128u8, 128, 128];
        let src = PipeSrc::Solid(&color);

        let data = vec![128u8; 4];
        let glyph = GlyphBitmap {
            data: &data,
            x: 0,
            y: 0,
            w: 2,
            h: 2,
            aa: true,
        };

        let res = fill_glyph::<Rgb8>(&mut bmp, &clip, &pipe, &src, 1, 1, &glyph);
        assert_eq!(res, ClipResult::AllInside);
    }

    #[test]
    fn glyph_row_bytes_aa() {
        let data = [];
        let g = GlyphBitmap {
            data: &data,
            x: 0,
            y: 0,
            w: 7,
            h: 1,
            aa: true,
        };
        assert_eq!(g.row_bytes(), 7);
    }

    #[test]
    fn glyph_row_bytes_mono() {
        let data = [];
        let g = GlyphBitmap {
            data: &data,
            x: 0,
            y: 0,
            w: 7,
            h: 1,
            aa: false,
        };
        assert_eq!(g.row_bytes(), 1); // ceil(7/8) = 1
        let g9 = GlyphBitmap {
            data: &data,
            x: 0,
            y: 0,
            w: 9,
            h: 1,
            aa: false,
        };
        assert_eq!(g9.row_bytes(), 2); // ceil(9/8) = 2
    }
}