service_authenticator/
helper.rs

1//! Helper functions allowing you to avoid writing boilerplate code for common operations, such as
2//! parsing JSON or reading files.
3
4// Copyright (c) 2016 Google Inc (lewinb@google.com).
5//
6// Refer to the project root for licensing information.
7use crate::service_account::ServiceAccountKey;
8
9use std::io;
10use std::path::Path;
11
12/// Parse service account key from a [u8].
13pub fn parse_service_key(secret: &[u8]) -> io::Result<ServiceAccountKey> {
14  serde_json::from_slice(secret).map_err(|e| {
15    io::Error::new(
16      io::ErrorKind::InvalidData,
17      format!("Bad service account key: {}", e),
18    )
19  })
20}
21/// Read a service account key from a JSON file. You can download the JSON keys from the Google
22/// Cloud Console or the respective console of your service provider.
23pub async fn read_service_account_key<P: AsRef<Path>>(path: P) -> io::Result<ServiceAccountKey> {
24  let key = tokio::fs::read(path).await?;
25  serde_json::from_slice(&key).map_err(|e| {
26    io::Error::new(
27      io::ErrorKind::InvalidData,
28      format!("Bad service account key: {}", e),
29    )
30  })
31}
32pub(crate) fn join<T>(
33  pieces: &[T],
34  separator: &str,
35) -> String
36where
37  T: AsRef<str>,
38{
39  let mut iter = pieces.iter();
40  let first = match iter.next() {
41    Some(p) => p,
42    None => return String::new(),
43  };
44  let num_separators = pieces.len() - 1;
45  let pieces_size: usize = pieces.iter().map(|p| p.as_ref().len()).sum();
46  let size = pieces_size + separator.len() * num_separators;
47  let mut result = String::with_capacity(size);
48  result.push_str(first.as_ref());
49  for p in iter {
50    result.push_str(separator);
51    result.push_str(p.as_ref());
52  }
53  debug_assert_eq!(size, result.len());
54  result
55}