-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathbase32_ffi_tests.rs
More file actions
63 lines (54 loc) · 2.36 KB
/
base32_ffi_tests.rs
File metadata and controls
63 lines (54 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2017 Trust Wallet.
use std::ffi::CString;
use tw_encoding::ffi::{decode_base32, encode_base32};
/// Checks if the encoded `input` with the given `alphabet` and `padding` parameters
/// equals to `expected`.
#[track_caller]
fn test_base32_encode_helper(input: &[u8], expected: &str, alphabet: Option<&str>, padding: bool) {
let alphabet_cstring = alphabet.map(|alphabet| CString::new(alphabet).unwrap());
let alphabet_ptr = alphabet_cstring
.as_ref()
.map(|s| s.as_ptr())
.unwrap_or_else(std::ptr::null);
let result_ptr =
unsafe { encode_base32(input.as_ptr(), input.len(), alphabet_ptr, padding) }.unwrap();
let result = unsafe { CString::from_raw(result_ptr) };
assert_eq!(result.to_str().unwrap(), expected);
}
/// Checks if the decoded `input` with the given `alphabet` and `padding` parameters
/// equals to `expected`.
#[track_caller]
fn test_base32_decode_helper(input: &str, expected: &[u8], alphabet: Option<&str>, padding: bool) {
let input = CString::new(input).unwrap();
let alphabet_cstring = alphabet.map(|alphabet| CString::new(alphabet).unwrap());
let alphabet_ptr = alphabet_cstring
.as_ref()
.map(|s| s.as_ptr())
.unwrap_or_else(std::ptr::null);
let decoded = unsafe {
decode_base32(input.as_ptr(), alphabet_ptr, padding)
.unwrap()
.into_vec()
};
assert_eq!(decoded, expected);
}
#[test]
fn test_base32_encode() {
let input = b"Hello, world!";
let alphabet = "abcdefghijklmnopqrstuvwxyz234567";
test_base32_encode_helper(input, "JBSWY3DPFQQHO33SNRSCC", None, false);
test_base32_encode_helper(input, "jbswy3dpfqqho33snrscc===", Some(alphabet), true);
test_base32_encode_helper(input, "JBSWY3DPFQQHO33SNRSCC===", None, true);
test_base32_encode_helper(input, "jbswy3dpfqqho33snrscc", Some(alphabet), false);
}
#[test]
fn test_base32_decode() {
let expected = b"Hello, world!";
let alphabet = "abcdefghijklmnopqrstuvwxyz234567";
test_base32_decode_helper("JBSWY3DPFQQHO33SNRSCC===", expected, None, true);
test_base32_decode_helper("JBSWY3DPFQQHO33SNRSCC", expected, None, false);
test_base32_decode_helper("jbswy3dpfqqho33snrscc===", expected, Some(alphabet), true);
test_base32_decode_helper("jbswy3dpfqqho33snrscc", expected, Some(alphabet), false);
}