Commit bc1c0dbca0d6154fbe31c3e39407fe49f28f676b

muji 2023-09-07T12:39:51

Expose QR code generation functions.

diff --git a/src/lib.rs b/src/lib.rs
index ebae025..26b1d7e 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -48,6 +48,8 @@
 //! ```
 
 mod custom_providers;
+#[cfg(feature = "qr")]
+mod qr;
 mod rfc;
 mod secret;
 mod url_error;
@@ -56,6 +58,9 @@ pub use rfc::{Rfc6238, Rfc6238Error};
 pub use secret::{Secret, SecretParseError};
 pub use url_error::TotpUrlError;
 
+#[cfg(feature = "qr")]
+pub use qr::{qr_base64, qr_png};
+
 use constant_time_eq::constant_time_eq;
 
 #[cfg(feature = "serde_support")]
@@ -63,9 +68,6 @@ use serde::{Deserialize, Serialize};
 
 use core::fmt;
 
-#[cfg(feature = "qr")]
-use image::Luma;
-
 #[cfg(feature = "otpauth")]
 use url::{Host, Url};
 
@@ -642,98 +644,6 @@ impl TOTP {
 
         format!("otpauth://{}/{}?{}", host, label, params.join("&"))
     }
-
-    #[cfg(feature = "qr")]
-    fn get_qr_draw_canvas(&self, qr: qrcodegen::QrCode) -> image::ImageBuffer<Luma<u8>, Vec<u8>> {
-        let size = qr.size() as u32;
-        // "+ 8 * 8" is here to add padding (the white border around the QRCode)
-        // As some QRCode readers don't work without padding
-        let image_size = size * 8 + 8 * 8;
-        let mut canvas = image::GrayImage::new(image_size, image_size);
-
-        // Draw the border
-        for x in 0..image_size {
-            for y in 0..image_size {
-                if (y < 8 * 4 || y >= image_size - 8 * 4) || (x < 8 * 4 || x >= image_size - 8 * 4)
-                {
-                    canvas.put_pixel(x, y, Luma([255]));
-                }
-            }
-        }
-
-        // The QR inside the white border
-        for x_qr in 0..size {
-            for y_qr in 0..size {
-                // The canvas is a grayscale image without alpha. Hence it's only one 8-bits byte longs
-                // This clever trick to one-line the value was achieved with advanced mathematics
-                // And deep understanding of Boolean algebra.
-                let val = !qr.get_module(x_qr as i32, y_qr as i32) as u8 * 255;
-
-                // Multiply coordinates by width of pixels
-                // And take into account the 8*4 padding on top and left side
-                let x_start = x_qr * 8 + 8 * 4;
-                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]));
-                    }
-                }
-            }
-        }
-        canvas
-    }
-
-    /// Will return a qrcode to automatically add a TOTP as a base64 string. Needs feature `qr` to be enabled!
-    /// Result will be in the form of a string containing a base64-encoded png, which you can embed in HTML without needing
-    /// To store the png as a file.
-    ///
-    /// # Errors
-    ///
-    /// This will return an error in case the URL gets too long to encode into a QR code.
-    /// This would require the get_url method to generate an url bigger than 2000 characters,
-    /// Which would be too long for some browsers anyway.
-    ///
-    /// It will also return an error in case it can't encode the qr into a png. This shouldn't happen unless either the qrcode library returns malformed data, or the image library doesn't encode the data correctly
-    #[cfg(feature = "qr")]
-    pub fn get_qr(&self) -> Result<String, String> {
-        use base64::{engine::general_purpose, Engine as _};
-        use image::ImageEncoder;
-
-        let url = self.get_url();
-        let mut vec = Vec::new();
-
-        let qr: Result<qrcodegen::QrCode, String> =
-            match qrcodegen::QrCode::encode_text(&url, qrcodegen::QrCodeEcc::Medium) {
-                Ok(qr) => Ok(qr),
-                Err(err) => Err(err.to_string()),
-            };
-
-        if qr.is_err() {
-            return Err(qr.err().unwrap());
-        }
-
-        let code = qr?;
-
-        // "+ 8 * 8" is here to add padding (the white border around the QRCode)
-        // As some QRCode readers don't work without padding
-        let image_size = (code.size() as u32) * 8 + 8 * 8;
-
-        let canvas = self.get_qr_draw_canvas(code);
-
-        // Encode the canvas into a PNG
-        let encoder = image::codecs::png::PngEncoder::new(&mut vec);
-        match encoder.write_image(
-            &canvas.into_raw(),
-            image_size,
-            image_size,
-            image::ColorType::L8,
-        ) {
-            Ok(_) => Ok(general_purpose::STANDARD.encode(vec)),
-            Err(err) => Err(err.to_string()),
-        }
-    }
 }
 
 #[cfg(test)]
@@ -1285,7 +1195,7 @@ mod tests {
         let url = totp.get_url();
         let qr = qrcodegen::QrCode::encode_text(&url, qrcodegen::QrCodeEcc::Medium)
             .expect("could not generate qr");
-        let data = totp.get_qr_draw_canvas(qr).into_raw();
+        let data = qr::get_qr_draw_canvas(qr).into_raw();
 
         // Create hash from image
         let hash_digest = Sha512::digest(data);
diff --git a/src/qr.rs b/src/qr.rs
new file mode 100644
index 0000000..bdd4746
--- /dev/null
+++ b/src/qr.rs
@@ -0,0 +1,103 @@
+use crate::TOTP;
+use image::Luma;
+
+pub(crate) fn get_qr_draw_canvas(qr: qrcodegen::QrCode) -> image::ImageBuffer<Luma<u8>, Vec<u8>> {
+    let size = qr.size() as u32;
+    // "+ 8 * 8" is here to add padding (the white border around the QRCode)
+    // As some QRCode readers don't work without padding
+    let image_size = size * 8 + 8 * 8;
+    let mut canvas = image::GrayImage::new(image_size, image_size);
+
+    // Draw the border
+    for x in 0..image_size {
+        for y in 0..image_size {
+            if (y < 8 * 4 || y >= image_size - 8 * 4) || (x < 8 * 4 || x >= image_size - 8 * 4) {
+                canvas.put_pixel(x, y, Luma([255]));
+            }
+        }
+    }
+
+    // The QR inside the white border
+    for x_qr in 0..size {
+        for y_qr in 0..size {
+            // The canvas is a grayscale image without alpha. Hence it's only one 8-bits byte longs
+            // This clever trick to one-line the value was achieved with advanced mathematics
+            // And deep understanding of Boolean algebra.
+            let val = !qr.get_module(x_qr as i32, y_qr as i32) as u8 * 255;
+
+            // Multiply coordinates by width of pixels
+            // And take into account the 8*4 padding on top and left side
+            let x_start = x_qr * 8 + 8 * 4;
+            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]));
+                }
+            }
+        }
+    }
+    canvas
+}
+
+/// Convert text to a PNG QR code.
+pub fn qr_png(text: &str) -> Result<Vec<u8>, String> {
+    use image::ImageEncoder;
+
+    let mut vec = Vec::new();
+
+    let qr: Result<qrcodegen::QrCode, String> =
+        match qrcodegen::QrCode::encode_text(text, qrcodegen::QrCodeEcc::Medium) {
+            Ok(qr) => Ok(qr),
+            Err(err) => Err(err.to_string()),
+        };
+
+    if qr.is_err() {
+        return Err(qr.err().unwrap());
+    }
+
+    let code = qr?;
+
+    // "+ 8 * 8" is here to add padding (the white border around the QRCode)
+    // As some QRCode readers don't work without padding
+    let image_size = (code.size() as u32) * 8 + 8 * 8;
+
+    let canvas = get_qr_draw_canvas(code);
+
+    // Encode the canvas into a PNG
+    let encoder = image::codecs::png::PngEncoder::new(&mut vec);
+    match encoder.write_image(
+        &canvas.into_raw(),
+        image_size,
+        image_size,
+        image::ColorType::L8,
+    ) {
+        Ok(_) => Ok(vec),
+        Err(err) => Err(err.to_string()),
+    }
+}
+
+/// Convert text to a base64 encoded PNG QR code.
+pub fn qr_base64(text: &str) -> Result<String, String> {
+    use base64::{engine::general_purpose, Engine as _};
+    Ok(qr_png(text).map(|vec| general_purpose::STANDARD.encode(vec))?)
+}
+
+/// Will return a qrcode to automatically add a TOTP as a base64 string. Needs feature `qr` to be enabled!
+/// Result will be in the form of a string containing a base64-encoded png, which you can embed in HTML without needing
+/// To store the png as a file.
+///
+/// # Errors
+///
+/// This will return an error in case the URL gets too long to encode into a QR code.
+/// This would require the get_url method to generate an url bigger than 2000 characters,
+/// Which would be too long for some browsers anyway.
+///
+/// It will also return an error in case it can't encode the qr into a png. This shouldn't happen unless either the qrcode library returns malformed data, or the image library doesn't encode the data correctly
+impl TOTP {
+    pub fn get_qr(&self) -> Result<String, String> {
+        let url = self.get_url();
+        qr_base64(&url)
+    }
+}