common_multipart_rfc7578/
boundary.rs

1// Copyright 2021 rust-multipart-rfc7578 Developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7//
8
9use rand::{distributions::Alphanumeric, rngs::SmallRng, Rng, SeedableRng};
10use std::iter::FromIterator;
11
12/// A `BoundaryGenerator` is a policy to generate a random string to use
13/// as a part boundary.
14///
15/// The default generator will build a random string of 6 ascii characters.
16/// If you need more complexity, you can implement this, and use it with
17/// [`Form::new`].
18///
19/// # Examples
20///
21/// ```
22/// use common_multipart_rfc7578::client::multipart::BoundaryGenerator;
23///
24/// struct TestGenerator;
25///
26/// impl BoundaryGenerator for TestGenerator {
27///     fn generate_boundary() -> String {
28///         "test".to_string()
29///     }
30/// }
31/// ```
32pub trait BoundaryGenerator {
33    /// Generates a String to use as a boundary.
34    fn generate_boundary() -> String;
35}
36
37pub(crate) struct RandomAsciiGenerator;
38
39impl BoundaryGenerator for RandomAsciiGenerator {
40    /// Creates a boundary of 6 ascii characters.
41    fn generate_boundary() -> String {
42        let rng = SmallRng::from_entropy();
43        let ascii = rng.sample_iter(&Alphanumeric);
44
45        String::from_iter(ascii.map(|b| b as char).take(6))
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::{BoundaryGenerator, RandomAsciiGenerator};
52
53    #[test]
54    fn generate_random_boundary_not_empty() {
55        assert!(!RandomAsciiGenerator::generate_boundary().is_empty());
56    }
57
58    #[test]
59    fn generate_random_boundary_different_each_time() {
60        assert!(
61            RandomAsciiGenerator::generate_boundary() != RandomAsciiGenerator::generate_boundary()
62        );
63    }
64}