Skip to main content

functora_core/
encoding.rs

1use 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}
77
78#[must_use]
79pub fn download_script(filename: &str) -> String {
80    let escaped = filename
81        .replace('\\', "\\\\")
82        .replace('"', "\\\"")
83        .replace('\n', "\\n")
84        .replace('\r', "\\r")
85        .replace('\t', "\\t")
86        .replace('\'', "\\u0027")
87        .replace('<', "\\u003c")
88        .replace('>', "\\u003e");
89    format!(
90        r#"const parts=[];for(;;){{const m=await dioxus.recv();if(m&&m.t==='done')break;if(m&&m.t==='abort')return;const bin=atob(m.data);const bytes=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)bytes[i]=bin.charCodeAt(i);parts.push(bytes)}}const url=URL.createObjectURL(new Blob(parts,{{type:'application/octet-stream'}}));const a=document.createElement('a');a.href=url;a.download="{escaped}";a.style.display='none';document.body.appendChild(a);a.click();setTimeout(()=>{{document.body.removeChild(a);URL.revokeObjectURL(url)}},1000)"#,
91    )
92}