juniper/
util.rs

1use std::borrow::Cow;
2
3use derive_more::with_trait::Display;
4
5/// Convert string to camel case.
6///
7/// Note: needs to be public because several macros use it.
8#[doc(hidden)]
9pub fn to_camel_case(s: &'_ str) -> Cow<'_, str> {
10    let mut dest = Cow::Borrowed(s);
11
12    // handle '_' to be more friendly with the
13    // _var convention for unused variables
14    let s_iter = if let Some(stripped) = s.strip_prefix('_') {
15        stripped
16    } else {
17        s
18    }
19    .split('_')
20    .enumerate();
21
22    for (i, part) in s_iter {
23        if i > 0 && part.len() == 1 {
24            dest += Cow::Owned(part.to_uppercase());
25        } else if i > 0 && part.len() > 1 {
26            let first = part
27                .chars()
28                .next()
29                .unwrap()
30                .to_uppercase()
31                .collect::<String>();
32            let second = &part[1..];
33
34            dest += Cow::Owned(first);
35            dest += second;
36        } else if i == 0 {
37            dest = Cow::Borrowed(part);
38        }
39    }
40
41    dest
42}
43
44#[test]
45fn test_to_camel_case() {
46    assert_eq!(&to_camel_case("test")[..], "test");
47    assert_eq!(&to_camel_case("_test")[..], "test");
48    assert_eq!(&to_camel_case("first_second")[..], "firstSecond");
49    assert_eq!(&to_camel_case("first_")[..], "first");
50    assert_eq!(&to_camel_case("a_b_c")[..], "aBC");
51    assert_eq!(&to_camel_case("a_bc")[..], "aBc");
52    assert_eq!(&to_camel_case("a_b")[..], "aB");
53    assert_eq!(&to_camel_case("a")[..], "a");
54    assert_eq!(&to_camel_case("")[..], "");
55}
56
57/// Combination of two [`Display`]able types into a single one.
58#[derive(Display)]
59pub(crate) enum Either<L, R> {
60    /// Left value of the first type.
61    Left(L),
62
63    /// Right value of the second type.
64    Right(R),
65}