opstr/ops/
base64_url_safe_encode.rs

1use crate::config::Configuration;
2use crate::errors::LibError;
3use crate::input::Args;
4use crate::ops::traits;
5use crate::output::Output;
6use crate::range;
7
8use base64;
9use base64::{Engine as _, engine::general_purpose as base64_engine};
10
11
12pub struct Base64UrlSafeEncode {}
13
14impl Base64UrlSafeEncode {
15    fn function_for_chars(arg: &str) -> String {
16        Self::function_for_bitstring(arg.as_bytes())
17    }
18
19    fn function_for_bitstring(arg: &[u8]) -> String {
20        base64_engine::URL_SAFE_NO_PAD.encode(arg)
21    }
22}
23
24impl traits::Op for Base64UrlSafeEncode {
25    fn name() -> &'static str { "base64-url-safe-encode" }
26    fn usage() -> &'static str { "<#1 string to-encode>" }
27    fn description() -> &'static str { "base64 encoding of provided string #1 with URL-appropriate representation (c.f. RFC 3548)" }
28    fn acceptable_number_of_arguments() -> range::Range { range::Range::IndexIndex(1, 1) }
29
30    fn priority(args: &Args, _conf: &Configuration) -> Result<f32, LibError> {
31        let base: &str = args.get(0)?.try_into()?;
32        let length = base.chars().count();
33
34        Ok(if 12 <= length && length <= 256 {
35            0.6
36        } else {
37            0.24
38        })
39    }
40
41    fn run(args: &Args, _conf: &Configuration) -> Result<Output, LibError> {
42        let base: &str = args.get(0)?.try_into()?;
43        Ok(Self::function_for_chars(base).into())
44    }
45}