base64/
base64.rs

1// Copyright 2023 The rust-ggstd authors. All rights reserved.
2// Copyright 2012 The Go Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file.
5
6use ggstd::encoding::base64;
7use std::io::Write;
8
9fn main() {
10    example();
11    example_encoding_encode_to_string();
12    example_encoding_encode();
13    example_encoding_decode_string();
14    example_encoding_decode();
15    example_new_encoder();
16}
17
18fn example() {
19    let msg = "Hello, 世界";
20    let encoded = base64::get_std_encoding().encode_to_string(msg.as_bytes());
21    println!("{}", encoded);
22    let (decoded, err) = base64::get_std_encoding().decode_string(&encoded);
23    if err.is_some() {
24        println!("decode error: {:?}", err);
25        return;
26    }
27    println!("{}", String::from_utf8_lossy(&decoded));
28    // Output:
29    // SGVsbG8sIOS4lueVjA==
30    // Hello, 世界
31}
32
33fn example_encoding_encode_to_string() {
34    let data = "any + old & data".as_bytes();
35    let str = base64::get_std_encoding().encode_to_string(data);
36    println!("{}", str)
37    // Output:
38    // YW55ICsgb2xkICYgZGF0YQ==
39}
40
41fn example_encoding_encode() {
42    let data = "Hello, world!".as_bytes();
43    let mut dst = vec![0; base64::get_std_encoding().encoded_len(data.len())];
44    base64::get_std_encoding().encode(&mut dst, data);
45    println!("{}", String::from_utf8_lossy(&dst));
46    // Output:
47    // SGVsbG8sIHdvcmxkIQ==
48}
49
50fn example_encoding_decode_string() {
51    let str = "c29tZSBkYXRhIHdpdGggACBhbmQg77u/";
52    let (data, err) = base64::get_std_encoding().decode_string(str);
53    if err.is_some() {
54        println!("error: {:?}", err);
55        return;
56    }
57    println!("{}", ggstd::strconv::quote_bytes_string(&data));
58    // Output:
59    // "some data with \x00 and \ufeff"
60}
61
62fn example_encoding_decode() {
63    let str = "SGVsbG8sIHdvcmxkIQ==";
64    let mut dst = vec![0; base64::get_std_encoding().decoded_len(str.len())];
65    let (n, err) = base64::get_std_encoding().decode(&mut dst, str.as_bytes());
66    if err.is_some() {
67        println!("decode error: {:?}", err);
68        return;
69    }
70    let dst = &dst[..n];
71    println!("\"{}\"", String::from_utf8(dst.to_vec()).unwrap());
72    // Output:
73    // "Hello, world!"
74}
75
76fn example_new_encoder() {
77    let input = b"foo\x00bar";
78    let stdout = std::io::stdout();
79    let mut stdout_writer = stdout.lock();
80    let mut encoder = base64::Encoder::new(base64::get_std_encoding(), &mut stdout_writer);
81    encoder.write_all(input).unwrap();
82    // Must close the encoder when finished to flush any partial blocks.
83    // If you comment out the following line, the last partial block "r"
84    // won't be encoded.
85    encoder.close().unwrap();
86    // Output:
87    // Zm9vAGJhcg==
88}