Skip to content

Commit

Permalink
Optimize drawing loop
Browse files Browse the repository at this point in the history
Signed-off-by: Cléo Rebert <cleo.rebert@gmail.com>
  • Loading branch information
constantoine committed Jan 19, 2024
1 parent 17844d6 commit e68b083
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
6 changes: 6 additions & 0 deletions qrcodegen-image/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## [1.3.0](https://github.com/constantoine/totp-rs/releases/tag/qrcodegen-image%2Fv1.3.0) (19/01/2024)

### What's new

- `draw_canvas` is now 70%(!) faster on my machine after optimizing the "drawing_square" loop.

## [1.2.0](https://github.com/constantoine/totp-rs/releases/tag/qrcodegen-image%2Fv1.2.0) (14/09/2023)

### What's new
Expand Down
2 changes: 1 addition & 1 deletion qrcodegen-image/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "qrcodegen-image"
version = "1.2.0"
version = "1.3.0"
edition = "2021"
authors = ["Cleo Rebert <cleo.rebert@gmail.com>"]
rust-version = "1.61"
Expand Down
11 changes: 6 additions & 5 deletions qrcodegen-image/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ pub fn draw_canvas(qr: qrcodegen::QrCode) -> image::ImageBuffer<Luma<u8>, Vec<u8
*pixel = Luma([255]);
}

let raw = canvas.as_mut();

// The QR inside the white border
for x_qr in 0..size {
for y_qr in 0..size {
Expand All @@ -32,10 +34,9 @@ pub fn draw_canvas(qr: qrcodegen::QrCode) -> image::ImageBuffer<Luma<u8>, Vec<u8
let y_start = y_qr * 8 + 8 * 4;

// Draw a 8-pixels-wide square
for x_img in x_start..x_start + 8 {
for y_img in y_start..y_start + 8 {
canvas.put_pixel(x_img, y_img, Luma([val]));
}
for y_img in y_start..y_start + 8 {
let start = (x_start + y_img * image_size) as usize;
raw[start..start + 8].copy_from_slice(&[val; 8]);
}
}
}
Expand Down Expand Up @@ -99,5 +100,5 @@ pub fn draw_png(text: &str) -> Result<Vec<u8>, String> {
#[cfg(feature = "base64")]
pub fn draw_base64(text: &str) -> Result<String, String> {
use base64::{engine::general_purpose, Engine as _};
Ok(draw_png(text).map(|vec| general_purpose::STANDARD.encode(vec))?)
draw_png(text).map(|vec| general_purpose::STANDARD.encode(vec))
}

0 comments on commit e68b083

Please sign in to comment.