functora_core/
encoding.rs1use crate::Error;
2use base64::Engine;
3use base64::engine::general_purpose::URL_SAFE_NO_PAD;
4use serde::Serialize;
5use serde::de::DeserializeOwned;
6use std::borrow::Cow;
7use tap::prelude::*;
8
9pub fn encode_payload<T: Serialize>(value: &T) -> Result<String, Error> {
10 serde_json::to_vec(value)
11 .map(|bytes| URL_SAFE_NO_PAD.encode(bytes))?
12 .pipe(Ok)
13}
14
15pub fn decode_payload<T: DeserializeOwned>(encoded: &str) -> Result<T, Error> {
16 let bytes = URL_SAFE_NO_PAD.decode(encoded)?;
17 serde_json::from_slice::<T>(&bytes)?.pipe(Ok)
18}
19
20#[must_use]
21pub fn append_query_param(base_url: &str, name: &str, value: &str) -> String {
22 let separator = if base_url.contains('?') { "&" } else { "?" };
23 format!("{base_url}{separator}{name}={}", urlencoding::encode(value))
24}
25
26#[must_use]
27pub fn extract_query_param(url: &str, name: &str) -> Option<String> {
28 url.split('?')
29 .nth(1)?
30 .split('&')
31 .find_map(|param| {
32 param
33 .split_once('=')
34 .filter(|(actual, _)| *actual == name)
35 .map(|(_, value)| value)
36 })
37 .map(|value| urlencoding::decode(value).map_or_else(|_| value.to_string(), Cow::into_owned))
38}
39
40#[cfg(feature = "qr")]
41pub fn generate_qr_code(url: &str) -> Result<String, Error> {
42 use rxing::qrcode::QRCodeWriter;
43 use rxing::{BarcodeFormat, EncodeHints, Writer};
44 const QR_SVG_SIZE: i32 = 200;
45 const QR_SVG_QUIET_ZONE: i32 = 2;
46 let hints = EncodeHints {
47 Margin: Some(QR_SVG_QUIET_ZONE.to_string()),
48 ..Default::default()
49 };
50 QRCodeWriter
51 .encode_with_hints(
52 url,
53 &BarcodeFormat::QR_CODE,
54 QR_SVG_SIZE,
55 QR_SVG_SIZE,
56 &hints,
57 )
58 .map(|matrix| bitmatrix_to_svg(&matrix))?
59 .pipe(Ok)
60}
61
62#[cfg(feature = "qr")]
63fn bitmatrix_to_svg(matrix: &rxing::common::BitMatrix) -> String {
64 let w = matrix.getWidth();
65 let h = matrix.getHeight();
66 let paths = (0..h)
67 .flat_map(|y| {
68 (0..w)
69 .filter(move |&x| matrix.get(x, y))
70 .map(move |x| format!("M{x} {y} h1 v1 h-1 z "))
71 })
72 .collect::<String>();
73 format!(
74 r##"<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 {w} {h}" shape-rendering="crispEdges"><rect width="{w}" height="{h}" fill="#ffffff"/><path d="{paths}" fill="#000000"/></svg>"##,
75 )
76}