b64 coverage - 22.18% (branches 16.67%)

R/config.R 51 11 0 11 0.0 0.00%
R/engine.R 63 17 3 14 0.9 0.00% 17.65%
src/rust/src/lib.rs 377 195 36 159 1.0 18.46%
R/encode.R 94 19 6 13 1.3 16.67% 31.58%
R/extendr-wrappers.R 78 17 6 11 2.5 35.29%
R/alphabet.R 67 14 8 6 4.3 50.00% 57.14%
src/entrypoint.c 8 2 2 0 3.0 100.00%
Total 738 275 61 214 1.2 16.67% 22.18%
1
# Generated by extendr: Do not edit by hand
2
3
# nolint start
4
5
#
6
# This file was created with the following call:
7
#   .Call("wrap__make_b64_wrappers", use_symbols = TRUE, package_name = "b64")
8
9
#' @usage NULL
10
#' @useDynLib b64, .registration = TRUE
11
NULL
12
134x
encode_ <- function(what, engine) .Call(wrap__encode_, what, engine)
14
15!
encode_file_ <- function(path, engine) .Call(wrap__encode_file_, path, engine)
16
17!
encode_vectorized_ <- function(what, engine) .Call(wrap__encode_vectorized_, what, engine)
18
194x
decode_ <- function(input, engine) .Call(wrap__decode_, input, engine)
20
21!
decode_file_ <- function(path, engine) .Call(wrap__decode_file_, path, engine)
22
23!
decode_vectorized_ <- function(what, engine) .Call(wrap__decode_vectorized_, what, engine)
24
25!
decode_as_string_ <- function(what, split, engine) .Call(wrap__decode_as_string_, what, split, engine)
26
276x
alphabet_ <- function(which) .Call(wrap__alphabet_, which)
28
296x
new_alphabet_ <- function(chars) .Call(wrap__new_alphabet_, chars)
30
3118x
get_alphabet_ <- function(alphabet) .Call(wrap__get_alphabet_, alphabet)
32
33!
new_engine_ <- function(alphabet, config) .Call(wrap__new_engine_, alphabet, config)
34
355x
engine_ <- function(which) .Call(wrap__engine_, which)
36
37!
print_engine_ <- function(engine) .Call(wrap__print_engine_, engine)
38
39!
new_config_ <- function(encode_padding, decode_padding_trailing_bits, decode_padding_mode) .Call(wrap__new_config_, encode_padding, decode_padding_trailing_bits, decode_padding_mode)
40
41!
print_config_ <- function(config) .Call(wrap__print_config_, config)
42
43
#' Utility Functions
44
#'
45
#' Functions to perform common tasks when working with base64 encoded strings.
46
#'
47
#' @details
48
#'
49
#' `b64_chunk()` splits a character vector of base64 encoded strings into chunks of a
50
#' specified width.
51
#'
52
#' `b64_wrap()` wraps a character vector of base64 encoded strings with a newline character.
53
#'
54
#' @returns
55
#'
56
#' - `b64_chunk()` returns a list of character vectors.
57
#' - `b64_wrap()` returns a scalar character vector.
58
#'
59
#' @examples
60
#' encoded <- encode("Hello, world!")
61
#' chunked <- b64_chunk(encoded, 4)
62
#' chunked
63
#'
64
#' b64_wrap(chunked, "\n")
65
#' @param width a numeric scalar defining the width of the chunks. Must be divisible by 4.
66
#' @param encoded a character vector of base64 encoded strings.
67
#' @export
68
#' @rdname utils
69!
b64_chunk <- function(encoded, width) .Call(wrap__b64_chunk, encoded, width)
70
71
#' @param chunks a character vector of base64 encoded strings.
72
#' @param newline a character scalar defining the newline character.
73
#' @export
74
#' @rdname utils
75!
b64_wrap <- function(chunks, newline) .Call(wrap__b64_wrap, chunks, newline)
76
77
78
# nolint end
1
#' Create an encoding engine
2
#'
3
#' @param which default `"standard"`. The base64 encoding engine to be used.
4
#'  See details for more.
5
#' @param .alphabet an object of class `alphabet` as created with
6
#'  [`alphabet()`] or [`new_alphabet()`]
7
#' @param .config an object of class `engine_config` as created with
8
#'  [new_config()]
9
#' @details
10
#'
11
#' ## Engines
12
#'
13
#' By default, the "standard" base64 engine is used which is specified in
14
#'  [RFC 4648](https://datatracker.ietf.org/doc/html/rfc4648#section-4).
15
#'
16
#'  Additional pre-configured base64 engines are provided these are:
17
#'
18
#'  - `"standard_no_pad"`: uses the standard engine without padding
19
#'  - `"url_safe"`: uses a url-safe alphabet with padding
20
#'  - `"url_safe_no_pad"`: uses a url-safe alphabet without padding
21
#'
22
#'  See [base64 crate](https://docs.rs/base64/latest/base64/engine/general_purpose/index.html#constants) for more.
23
#'
24
#' @return an object of class `engine`.
25
#' @export
26
#' @examples
27
#' engine()
28
#' new_engine(alphabet("bcrypt"), new_config())
29
engine <- function(which = "standard") {
305x
  provided <- c("standard", "standard_no_pad", "url_safe", "url_safe_no_pad")
315x
  match.arg(which, choices = provided)
325x
  structure(engine_(which), class = "engine")
33
}
34
35
#' @export
36
#' @rdname engine
37
new_engine <- function(.alphabet = alphabet(), .config = new_config()) {
38
39!0/2TRUE: 0FALSE: 0
  if (!inherits(.alphabet, "alphabet")) {
40!
    stop(
41!
      paste(
42!
        "`.alphabet` is not an object of class 'alphabet'.\n" ,
43!
        "Use `alphabet()` for a standard base64 alphabet."
44
      )
45
    )
46!0/2TRUE: 0FALSE: 0
  } else if (!inherits(.config, "engine_config")) {
47!
    stop(
48!
      paste(
49!
        "`.config` is not an object of class 'engine_config'.\n" ,
50!
        "Create one with `new_config()`."
51
      )
52
    )
53
  }
54
55!
  res <- new_engine_(.alphabet, .config)
56!
  structure(res, class = "engine")
57
}
58
59
#' @export
60
print.engine <- function(x, ...) {
61!
  cat("<engine>")
62!
  invisible(x)
63
}
1
#' Encode and decode using base64
2
#'
3
#' @details
4
#'
5
#' ## Encoding
6
#'
7
#' - `encode()` takes a character vector, list of raw vectors (or blob class), or a raw vector and encodes them into base64 strings.
8
#' - `encode_file()` takes a path to a file and encodes it as a base64 string.
9
#'
10
#' ## Decoding
11
#'
12
#' - `decode()` will decode either a base64 encoded character scalar, a raw vector, or a list of raw vectors (see blob package).
13
#' - `decode_file()` will decode a base64 encoded file into a raw vector.
14
#' - `decode_as_string()` is designed to decode a base64 encoded string to a utf-8 string. By default, it will decode a chunked base64 encoded strings using `\n` as the separator. Use the `newline` argument to determine how to split the input string prior to decoding.
15
#'
16
#'
17
#' @param what a character, raw, or blob vector
18
#' @param eng a base64 engine. See [engine()] for details.
19
#' @param path a path to a base64 encoded file.
20
#' @param newline a character sequence to split in the input base64 encoded string on before decoding.
21
#'
22
#' @return
23
#' Both `encode()` and `decode()` are vectorized. They will return a character
24
#' and blob vector the same length as `what`, respectively.
25
#'
26
#' `decode_as_string()` returns a character scalar.
27
#' @export
28
#' @name encode
29
#' @examples
30
#' # encode hello world
31
#' encoded <- encode("Hello world")
32
#' encoded
33
#'
34
#' # decode to a blob
35
#' decoded <- decode(encoded)
36
#' decoded
37
#'
38
#' # convert back to a character
39
#' rawToChar(decoded[[1]])
40
encode <- function(what, eng = engine()) {
414x
  n <- length(what)
424x1/2TRUE: 4FALSE: 0
  if (inherits(what, "raw") || (n == 1 & inherits(what, "character"))) {
434x
    encode_(what, eng)
44
  } else {
45!
    encode_vectorized_(what, eng)
46
  }
47
}
48
49
#' @export
50
#' @rdname encode
51
decode <- function(what, eng = engine()) {
524x
  n <- length(what)
534x1/2TRUE: 4FALSE: 0
  if (inherits(what, "raw") || (n == 1 & inherits(what, "character"))) {
544x
    decode_(what, eng)
55
  } else {
56!
    decode_vectorized_(what, eng)
57
  }
58
}
59
60
#' @export
61
#' @rdname encode
62
decode_as_string <- function(what, newline = "\n", eng = engine()) {
63!0/2TRUE: 0FALSE: 0
  if (!inherits(what, "character") || length(what) != 1) {
64!
    stop("`what` must be a scalar character vector")
65
  }
66
67!0/2TRUE: 0FALSE: 0
  if (!inherits(newline, "character") || length(newline) != 1) {
68!
    stop("`newline` must be a scalar character vector")
69
  }
70
71!
  decode_as_string_(what, newline, eng)
72
}
73
74
75
#' @export
76
#' @name encode
77
encode_file <- function(path, eng = engine()) {
78!0/2TRUE: 0FALSE: 0
  if (!file.exists(path)) {
79!
    stop(paste0("`", path, "` does not exist"))
80
  }
81
82!
  encode_file_(path, eng)
83
}
84
85
86
#' @export
87
#' @rdname encode
88
decode_file <- function(path, eng = engine()) {
89!0/2TRUE: 0FALSE: 0
  if (!file.exists(path)) {
90!
    stop(paste0("`", path, "` does not exist"))
91
  }
92
93!
  decode_file_(path, eng)
94
}
1
#' Standard base64 alphabets
2
#'
3
#' Create an alphabet from a set of standard base64 alphabets, or use your own.
4
#'
5
#' @param which default `"standard"`. Which base64 alphabet to use.
6
#'  See details for other values.
7
#' @param chars a character scalar contains 64 unique characters.
8
#'
9
#' @details
10
#'
11
#' - `"bcrypt"`: bcrypt alphabet
12
#' - `"bin_hex"`: alphabet used in BinHex 4.0 files
13
#' - `"crypt"`: crypt(3) alphabet (with . and / as the first two characters)
14
#' - `"imap_mutf7"`: alphabet used in IMAP-modified UTF-7 (with + and ,)
15
#' - `"standard"`: standard alphabet (with + and /) specified in RFC 4648
16
#' - `"url_safe"`: URL-safe alphabet (with - and _) specified in RFC 4648
17
#'
18
#' See [base64 crate](https://docs.rs/base64/latest/base64/alphabet/index.html#constants)
19
#' from where these definitions come.
20
#'
21
#' @export
22
#' @examples
23
#' alphabet("standard")
24
#' alphabet("bcrypt")
25
#' alphabet("bin_hex")
26
#' alphabet("crypt")
27
#' alphabet("imap_mutf7")
28
#' alphabet("url_safe")
29
#'
30
#' new_alphabet("qwertyuiop[]asdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890")
31
#' @returns an object of class `alphabet`
32
alphabet <- function(which = "standard") {
336x
  match.arg(
346x
    which,
356x
    choices = c("standard", "bcrypt", "bin_hex", "crypt", "imap_mutf7", "url_safe")
36
  )
376x
  structure(alphabet_(which), class = "alphabet")
38
}
39
40
#' @export
41
#' @rdname alphabet
42
new_alphabet <- function(chars) {
436x
  n <- nchar(chars)
446x1/2TRUE: 0FALSE: 6
  if (nchar(chars) != 64) {
45!
    stop(
46!
      paste(
47!
        "`chars` must contain 64 unique characters. Only", n, "characters were provided."
48
      )
49
    )
50
  }
51
526x
  structure(new_alphabet_(chars), class = "alphabet")
53
}
54
55
56
#' @export
57
print.alphabet <- function(x, ...) {
58!
  cat("<alphabet>\n")
59!
  cat(get_alphabet_(x))
60!
  invisible(x)
61
}
62
63
64
#' @export
65
as.character.alphabet <- function(x, ...) {
6618x
  get_alphabet_(x)
67
}
1
#' Create a custom encoding engine
2
#'
3
#' @details
4
#'
5
#' See [base64 crate](https://docs.rs/base64/latest/base64/engine/general_purpose/struct.GeneralPurposeConfig.html#method.with_encode_padding) for more details.
6
#'
7
#' ## Decode Padding Modes
8
#'
9
#' There are three modes that can be used for `decode_padding_mode` argument.
10
#'
11
#' - `"canonical"`: padding must consist of 0, 1, or 2 `=` characters
12
#' - `"none"`: there must be no padding characters present
13
#' - `"indifferent"`: canonical padding is used, but omitted padding
14
#'  characters are also permitted
15
#'
16
#' @param encode_padding default `TRUE` add 1-2 trailing `=` to pad results
17
#' @param decode_padding_trailing_bits default `FALSE`. "If invalid trailing bits are present and this is true, those bits will be silently ignored." (See details for reference).
18
#' @param decode_padding_mode default `"canonical"`. Other values are `"indifferent"` and `"none"`. See details for more.
19
#' @export
20
#' @return an object of class `engine_config`
21
#' @examples
22
#' # create a new nonsensicle config
23
#' new_config(FALSE, TRUE, "none")
24
new_config <- function(
25
    encode_padding = TRUE,
26
    decode_padding_trailing_bits = FALSE,
27
    decode_padding_mode = c("canonical", "indifferent", "none")
28
) {
29
30!
  padding_mode <- match.arg(
31!
    decode_padding_mode,
32!
    choices = c("canonical", "indifferent", "none")
33
  )
34
35!
  res <- new_config_(
36!
    encode_padding,
37!
    decode_padding_trailing_bits,
38!
    padding_mode
39
  )
40
41!
  structure(res, class = "engine_config")
42
}
43
44
#' @export
45
print.engine_config <- function(x, ...) {
46!
  y <- print_config_(x)
47!
  cat("<engine_config>\n")
48!
  invisible(x)
49
}
50
51
1
// We need to forward routine registration from C to Rust
2
// to avoid the linker removing the static library.
3
4
void R_init_b64_extendr(void *dll);
5
63x
void R_init_b64(void *dll) {
73x
    R_init_b64_extendr(dll);
8
}
1
use base64::{
2
    alphabet,
3
    engine::{general_purpose, DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig},
4
    prelude::*,
5
    read::DecoderReader,
6
    write::EncoderStringWriter,
7
};
8
use extendr_api::prelude::*;
9
use itertools::{Either, Itertools};
10
use std::io::Read;
11
12
#[extendr]
134x
fn encode_(what: Either<String, Raw>, engine: Robj) -> String {
144x
    let eng: ExternalPtr<GeneralPurpose> = engine.try_into().unwrap();
154x
    match what {
164x
        Either::Left(s) => eng.encode(s),
17!
        Either::Right(r) => eng.encode(r.as_slice()),
18
    }
19
}
20
21
#[extendr]
22!
fn encode_vectorized_(what: Either<Strings, List>, engine: Robj) -> Strings {
23!
    let eng: ExternalPtr<GeneralPurpose> = engine.try_into().unwrap();
24!
    match what {
25!
        Either::Left(s) => s
26!
            .into_iter()
27!
            .map(|s| {
28!
                if s.is_na() {
29!
                    Rstr::na()
30
                } else {
31!
                    let to_encode = s.as_bytes();
32!
                    Rstr::from(eng.encode(to_encode))
33
                }
34
            })
35!
            .collect::<Strings>(),
36!
        Either::Right(r) => r
37!
            .into_iter()
38!
            .map(|(_, b)| {
39!
                if b.is_null() {
40!
                    Rstr::na()
41
                } else {
42!
                    let raw: Raw = b.try_into().unwrap();
43!
                    Rstr::from(eng.encode(raw.as_slice()))
44
                }
45
            })
46!
            .collect::<Strings>(),
47
    }
48
}
49
50
#[extendr]
51!
fn encode_file_(path: &str, engine: Robj) -> String {
52!
    let eng: ExternalPtr<GeneralPurpose> = engine.try_into().unwrap();
53!
    let eng = eng.addr();
54!
    let file = std::fs::File::open(path).unwrap();
55!
    let mut reader = std::io::BufReader::new(file);
56!
    let mut encoder = EncoderStringWriter::new(eng);
57!
    std::io::copy(&mut reader, &mut encoder).unwrap();
58!
    encoder.into_inner()
59
}
60
61
/// Utility Functions
62
///
63
/// Functions to perform common tasks when working with base64 encoded strings.
64
///
65
/// @details
66
///
67
/// `b64_chunk()` splits a character vector of base64 encoded strings into chunks of a
68
/// specified width.
69
///
70
/// `b64_wrap()` wraps a character vector of base64 encoded strings with a newline character.
71
///
72
/// @returns
73
///
74
/// - `b64_chunk()` returns a list of character vectors.
75
/// - `b64_wrap()` returns a scalar character vector.
76
///
77
/// @examples
78
/// encoded <- encode("Hello, world!")
79
/// chunked <- b64_chunk(encoded, 4)
80
/// chunked
81
///
82
/// b64_wrap(chunked, "\n")
83
/// @param width a numeric scalar defining the width of the chunks. Must be divisible by 4.
84
/// @param encoded a character vector of base64 encoded strings.
85
/// @export
86
/// @rdname utils
87
#[extendr]
88!
fn b64_chunk(encoded: Strings, width: Either<i32, f64>) -> List {
89!
    let width = match width {
90!
        Left(l) => l,
91!
        Right(r) => r as i32,
92
    };
93
94!
    if width % 4 != 0 {
95!
        extendr_api::throw_r_error("Chunk size must be a multiple of 4.");
96
    }
97!
    encoded
98!
        .into_iter()
99!
        .map(|s| {
100!
            if s.is_na() {
101!
                Strings::new(0)
102
            } else {
103!
                s.chars()
104!
                    .chunks(width as usize)
105!
                    .into_iter()
106!
                    .map(|chunk| chunk.collect::<String>())
107!
                    .collect::<Strings>()
108
            }
109
        })
110!
        .collect::<List>()
111
}
112
113
/// @param chunks a character vector of base64 encoded strings.
114
/// @param newline a character scalar defining the newline character.
115
/// @export
116
/// @rdname utils
117
#[extendr]
118!
fn b64_wrap(chunks: Either<List, Strings>, newline: &str) -> Strings {
119!
    match chunks {
120!
        Left(l) => l
121!
            .into_iter()
122!
            .map(|(_, s)| {
123!
                if s.is_na() {
124!
                    Rstr::na()
125
                } else {
126!
                    let s = Strings::try_from(s).unwrap();
127!
                    Rstr::from(b64_wrap_(s, newline))
128
                }
129
            })
130!
            .collect::<Strings>(),
131!
        Right(r) => b64_wrap_(r, newline).into(),
132
    }
133
}
134
135!
fn b64_wrap_(chunks: Strings, newline: &str) -> String {
136!
    chunks.into_iter().join(newline)
137
}
138
139
#[extendr]
1404x
fn decode_(input: Either<String, Raw>, engine: Robj) -> List {
1414x
    let eng: ExternalPtr<GeneralPurpose> = engine.try_into().unwrap();
1424x
    let res = match input {
1434x
        Either::Left(s) => {
1444x
            let res = eng.decode(s);
1454x
            match res {
1464x
                Ok(d) => d,
147!
                Err(e) => throw_r_error(e.to_string().as_str()),
148
            }
149
        }
150!
        Either::Right(r) => match eng.decode(r.as_slice()) {
151!
            Ok(d) => d,
152!
            Err(e) => throw_r_error(e.to_string().as_str()),
153
        },
154
    };
155
1564x
    list!(Raw::from_bytes(&res))
1574x
        .set_class(&["blob", "vctrs_list_of", "vctrs_vctr", "list"])
1584x
        .unwrap()
1594x
        .clone()
160
}
161
162
#[extendr]
163!
fn decode_vectorized_(what: Either<Strings, List>, engine: Robj) -> List {
164!
    let eng: ExternalPtr<GeneralPurpose> = engine.try_into().unwrap();
165!
    match what {
166!
        Either::Left(s) => s
167!
            .into_iter()
168!
            .map(|s| {
169!
                if s.is_na() {
170!
                    ().into_robj()
171
                } else {
172!
                    let to_encode = s.as_str();
173!
                    let decoded = eng.decode(to_encode);
174!
                    match decoded {
175!
                        Ok(d) => {
176!
                            let r = Raw::from_bytes(&d);
177!
                            r.into_robj()
178
                        }
179!
                        Err(_) => ().into_robj(),
180
                    }
181
                }
182
            })
183!
            .collect::<List>()
184!
            .set_class(&["blob", "vctrs_list_of", "vctrs_vctr", "list"])
185!
            .unwrap()
186!
            .clone(),
187!
        Either::Right(r) => r
188!
            .into_iter()
189!
            .map(|(_, b)| {
190!
                let raw = Raw::try_from(b);
191!
                match raw {
192!
                    Ok(r) => {
193!
                        let decoded = eng.decode(r.as_slice());
194!
                        match decoded {
195!
                            Ok(d) => Raw::from_bytes(&d).into_robj(),
196!
                            Err(_) => ().into_robj(),
197
                        }
198
                    }
199!
                    Err(_) => ().into_robj(),
200
                }
201
            })
202!
            .collect::<List>()
203!
            .set_class(&["blob", "vctrs_list_of", "vctrs_vctr", "list"])
204!
            .unwrap()
205!
            .clone(),
206
    }
207
}
208
209
#[extendr]
210!
fn decode_as_string_(what: String, split: Option<String>, engine: Robj) -> Result<String> {
211!
    let eng: ExternalPtr<GeneralPurpose> = engine.try_into().unwrap();
212!
    match split {
213!
        Some(sp) => {
214!
            let res = what
215!
                .split(&sp)
216!
                .map(|split| {
217!
                    let bytes = eng
218!
                        .decode(split)
219!
                        .map_err(|_| throw_r_error("Failed to decode split"))
220!
                        .unwrap();
221
222!
                    String::from_utf8(bytes)
223!
                        .map_err(|_| throw_r_error("Failed to parse decoded bytes as a string"))
224!
                        .unwrap()
225
                })
226!
                .collect::<String>();
227!
            Ok(res)
228
        }
229
        None => {
230!
            let res = eng
231!
                .decode(what)
232!
                .map_err(|_| throw_r_error("Failed to decode input string"))
233!
                .unwrap();
234!
            let res = String::from_utf8(res)
235!
                .map_err(|_| throw_r_error("Failed to parse decoded bytes to a string"))
236!
                .unwrap();
237!
            Ok(res)
238
        }
239
    }
240
}
241
242
#[extendr]
243!
fn decode_file_(path: &str, engine: Robj) -> Vec<u8> {
244!
    let eng: ExternalPtr<GeneralPurpose> = engine.try_into().unwrap();
245!
    let eng = eng.addr();
246!
    let file = std::fs::File::open(path).unwrap();
247!
    let mut reader = std::io::BufReader::new(file);
248!
    let mut decoder = DecoderReader::new(&mut reader, eng);
249!
    let mut result = Vec::new();
250!
    decoder.read_to_end(&mut result).unwrap();
251!
    result
252
}
253
254
// use a built-in alphabet
255
#[extendr]
2566x
fn alphabet_(which: &str) -> ExternalPtr<alphabet::Alphabet> {
2576x
    match which {
2586x
        "bcrypt" => ExternalPtr::new(alphabet::BCRYPT),
2595x
        "bin_hex" => ExternalPtr::new(alphabet::BIN_HEX),
2604x
        "crypt" => ExternalPtr::new(alphabet::CRYPT),
2613x
        "imap_mutf7" => ExternalPtr::new(alphabet::IMAP_MUTF7),
2622x
        "standard" => ExternalPtr::new(alphabet::STANDARD),
2631x
        "url_safe" => ExternalPtr::new(alphabet::URL_SAFE),
264!
        _ => extendr_api::throw_r_error(format!("Unknown alphabet: {}", which)),
265
    }
266
}
267
268
// Create new alphabet
269
#[extendr]
2706x
fn new_alphabet_(chars: &str) -> ExternalPtr<alphabet::Alphabet> {
2716x
    let res = alphabet::Alphabet::new(chars);
272
2736x
    match res {
2746x
        Ok(r) => ExternalPtr::new(r),
275!
        Err(e) => extendr_api::throw_r_error(format!("Error creating alphabet: {}", e)),
276
    }
277
}
278
279
// get alphabet as a string for printing
280
#[extendr]
28118x
fn get_alphabet_(alphabet: Robj) -> String {
28218x
    let alph: ExternalPtr<alphabet::Alphabet> = alphabet.try_into().unwrap();
28318x
    alph.as_str().to_string()
284
}
285
286
// default configs
287
// padding = true,
288
// decode_allow_trailing_bits = false,
289
// and decode_padding_mode = DecodePaddingMode::RequireCanonicalPadding
290
#[extendr]
291!
fn new_config_(
292!
    encode_padding: bool,
293!
    decode_padding_trailing_bits: bool,
294!
    decode_padding_mode: &str,
295!
) -> ExternalPtr<GeneralPurposeConfig> {
296!
    let pad_mode = match decode_padding_mode {
297!
        "indifferent" => DecodePaddingMode::Indifferent,
298!
        "canonical" => DecodePaddingMode::RequireCanonical,
299!
        "none" => DecodePaddingMode::RequireNone,
300!
        _ => extendr_api::throw_r_error(format!("Unknown padding mode: {}", decode_padding_mode)),
301
    };
302
303!
    let config = GeneralPurposeConfig::new()
304!
        .with_encode_padding(encode_padding)
305!
        .with_decode_allow_trailing_bits(decode_padding_trailing_bits)
306!
        .with_decode_padding_mode(pad_mode);
307
308!
    ExternalPtr::new(config)
309
}
310
311
#[extendr]
312!
fn print_config_(config: Robj) -> String {
313!
    let conf: ExternalPtr<GeneralPurposeConfig> = config.try_into().unwrap();
314!
    format!("{:#?}", conf)
315
}
316
317
#[extendr]
3185x
fn engine_(which: &str) -> ExternalPtr<GeneralPurpose> {
3195x
    match which {
3205x
        "standard" => ExternalPtr::new(general_purpose::STANDARD),
3213x
        "standard_no_pad" => ExternalPtr::new(general_purpose::STANDARD_NO_PAD),
3222x
        "url_safe" => ExternalPtr::new(general_purpose::URL_SAFE),
3231x
        "url_safe_no_pad" => ExternalPtr::new(general_purpose::URL_SAFE_NO_PAD),
324!
        _ => extendr_api::throw_r_error(format!("Unknown engine: {}", which)),
325
    }
326
}
327
328
// need to figure out a nice print pattern here
329
#[extendr]
330!
fn print_engine_(engine: Robj) -> String {
331!
    let eng: ExternalPtr<GeneralPurpose> = engine.try_into().unwrap();
332!
    format!("{:#?}", eng)
333
}
334
335
#[extendr]
336!
fn new_engine_(alphabet: Robj, config: Robj) -> ExternalPtr<GeneralPurpose> {
337!
    let alph: ExternalPtr<alphabet::Alphabet> = alphabet.try_into().unwrap();
338!
    let conf: ExternalPtr<GeneralPurposeConfig> = config.try_into().unwrap();
339!
    let inner = conf.addr();
340!
    let engine = general_purpose::GeneralPurpose::new(&alph, *inner);
341!
    ExternalPtr::new(engine)
342
}
343
344
// Macro to generate exports.
345
// This ensures exported functions are registered with R.
346
// See corresponding C code in `entrypoint.c`.
347
extendr_module! {
348
    mod b64;
349
    // encoding
350
    fn encode_;
351
    fn encode_file_;
352
    fn encode_vectorized_;
353
354
    // decoding
355
    fn decode_;
356
    fn decode_file_;
357
    fn decode_vectorized_;
358
    fn decode_as_string_;
359
360
    // alphabets
361
    fn alphabet_;
362
    fn new_alphabet_;
363
    fn get_alphabet_;
364
365
    // engines
366
    fn new_engine_;
367
    fn engine_;
368
    fn print_engine_;
369
370
    // config
371
    fn new_config_;
372
    fn print_config_;
373
374
    // helpers
375
    fn b64_chunk;
376
    fn b64_wrap;
377
}