Refactor Params into external struct

Reduces file size of generated library:

```
cargo build --release
   Compiling google-compute1 v5.0.1+20220224 (/home/philippe/PycharmProjects/google-apis-rs/gen/compute1)
    Finished release [optimized] target(s) in 35.15s
```
164 MB resulting lib (4MB reduction)
This commit is contained in:
philippeitis
2022-10-19 17:05:26 -07:00
parent 9fa31bd034
commit 0ad3b1258f
4 changed files with 87 additions and 37 deletions

View File

@@ -23,6 +23,7 @@ serde_json = "^ 1.0"
base64 = "0.13.0"
chrono = { version = "0.4.22", features = ["serde"] }
url = "= 1.7"
yup-oauth2 = { version = "^ 7.0", optional = true }
itertools = "^ 0.10"

View File

@@ -1,6 +1,7 @@
pub mod auth;
pub mod field_mask;
pub mod serde;
pub mod url;
use std::error;
use std::error::Error as StdError;

View File

@@ -0,0 +1,71 @@
use std::borrow::Cow;
use ::url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use ::url::Url;
pub struct Params<'a> {
params: Vec<(&'a str, Cow<'a, str>)>,
}
impl<'a> Params<'a> {
pub fn with_capacity(capacity: usize) -> Self {
Self {
params: Vec::with_capacity(capacity),
}
}
pub fn push<I: Into<Cow<'a, str>>>(&mut self, param: &'a str, value: I) {
self.params.push((param, value.into()))
}
pub fn extend<I: Iterator<Item = (&'a String, IC)>, IC: Into<Cow<'a, str>>>(
&mut self,
params: I,
) {
self.params
.extend(params.map(|(k, v)| (k.as_str(), v.into())))
}
pub fn get(&self, param_name: &str) -> Option<&str> {
self.params
.iter()
.find(|(name, _)| name == &param_name)
.map(|(_, param)| param.as_ref())
}
pub fn uri_replacement(
&self,
url: String,
param: &str,
from: &str,
url_encode: bool,
) -> String {
if url_encode {
let mut replace_with: Cow<str> = self.get(param).unwrap_or("").into();
if from.as_bytes()[1] == '+' as u8 {
replace_with = percent_encode(replace_with.as_bytes(), DEFAULT_ENCODE_SET)
.to_string()
.into();
}
url.replace(from, &replace_with)
} else {
let replace_with = self
.get(param)
.expect("to find substitution value in params");
url.replace(from, replace_with)
}
}
pub fn remove_params(&mut self, to_remove: &[&str]) {
self.params.retain(|(n, _)| !to_remove.contains(n))
}
pub fn inner_mut(&mut self) -> &mut Vec<(&'a str, Cow<'a, str>)> {
self.params.as_mut()
}
pub fn parse_with_url(&self, url: &str) -> Url {
Url::parse_with_params(&url, &self.params).unwrap()
}
}