diff --git a/benches/elastic/src/main.rs b/benches/elastic/src/main.rs index 7a15832bd8..8a910d2db9 100644 --- a/benches/elastic/src/main.rs +++ b/benches/elastic/src/main.rs @@ -1,13 +1,13 @@ #![feature(plugin)] #![plugin(json_str)] -#[macro_use] -extern crate serde_derive; #[macro_use] extern crate elastic_derive; +#[macro_use] +extern crate serde_derive; -extern crate serde; extern crate elastic; +extern crate serde; extern crate measure; @@ -48,13 +48,14 @@ fn main() { .params(|p| p.header(http::header::Connection::keep_alive())) .build() .unwrap(); - + let results = measure::run(runs, || { - client.search::() - .index("bench_index") - .body(BODY) - .send() - .unwrap() + client + .search::() + .index("bench_index") + .body(BODY) + .send() + .unwrap() }); println!("{}", results); diff --git a/benches/elastic_async/src/main.rs b/benches/elastic_async/src/main.rs index c8d07f5e9a..2b168053a1 100644 --- a/benches/elastic_async/src/main.rs +++ b/benches/elastic_async/src/main.rs @@ -1,15 +1,15 @@ #![feature(plugin)] #![plugin(json_str)] -#[macro_use] -extern crate serde_derive; #[macro_use] extern crate elastic_derive; extern crate futures; +#[macro_use] +extern crate serde_derive; extern crate tokio_core; -extern crate serde; extern crate elastic; +extern crate serde; extern crate measure; @@ -50,12 +50,13 @@ fn main() { .params(|p| p.header(http::header::Connection::keep_alive())) .build(&core.handle()) .unwrap(); - + let results_future = measure::run_future(runs, || { - client.search::() - .index("bench_index") - .body(BODY) - .send() + client + .search::() + .index("bench_index") + .body(BODY) + .send() }); results = core.run(results_future).unwrap(); diff --git a/benches/elastic_bulk/src/main.rs b/benches/elastic_bulk/src/main.rs index 5ab3520961..2e8dfe639e 100644 --- a/benches/elastic_bulk/src/main.rs +++ b/benches/elastic_bulk/src/main.rs @@ -1,23 +1,23 @@ //! Elasticsearch Reqwest Client Samples //! //! This sample assumes you have a node running on `localhost`. -//! +//! //! This sample demonstrates a request with a large body. -//! -//! If you compile with `--features profile_memory` then it uses the system allocator +//! +//! If you compile with `--features profile_memory` then it uses the system allocator //! to play nicely with valgrind for profile_memory. -#![cfg_attr(feature="profile_memory", feature(alloc_system))] -#[cfg(feature="profile_memory")] +#![cfg_attr(feature = "profile_memory", feature(alloc_system))] +#[cfg(feature = "profile_memory")] extern crate alloc_system; +extern crate elastic; +#[cfg(feature = "inlinable_string")] +extern crate inlinable_string; #[macro_use] extern crate lazy_static; -#[cfg(feature="string_cache")] +#[cfg(feature = "string_cache")] extern crate string_cache; -#[cfg(feature="inlinable_string")] -extern crate inlinable_string; -extern crate elastic; extern crate reqwest; @@ -26,19 +26,19 @@ extern crate measure; use elastic::http; use elastic::prelude::*; -#[cfg(not(any(feature="string_cache", feature="inlinable_string")))] +#[cfg(not(any(feature = "string_cache", feature = "inlinable_string")))] type AllocatedField = String; -#[cfg(feature="string_cache")] +#[cfg(feature = "string_cache")] type AllocatedField = string_cache::DefaultAtom; -#[cfg(feature="inlinable_string")] +#[cfg(feature = "inlinable_string")] type AllocatedField = inlinable_string::InlinableString; -#[cfg(not(feature="errors_only"))] +#[cfg(not(feature = "errors_only"))] type BulkResponseType = elastic::prelude::BulkResponse; -#[cfg(feature="errors_only")] +#[cfg(feature = "errors_only")] type BulkResponseType = elastic::prelude::BulkErrorsResponse; // Create a bulk request to index a bunch of docs. @@ -67,12 +67,12 @@ fn get_req() -> &'static str { &REQUEST } -#[cfg(feature="gzip")] +#[cfg(feature = "gzip")] fn http_client() -> reqwest::Client { reqwest::Client::new() } -#[cfg(not(feature="gzip"))] +#[cfg(not(feature = "gzip"))] fn http_client() -> reqwest::Client { let mut http = reqwest::Client::new(); http.gzip(false); @@ -88,12 +88,13 @@ fn main() { .params(|p| p.header(http::header::Connection::keep_alive())) .build() .unwrap(); - + let results = measure::run(runs, || { - client.request(BulkRequest::new(get_req())) - .send() - .and_then(|res| res.into_response::()) - .unwrap() + client + .request(BulkRequest::new(get_req())) + .send() + .and_then(|res| res.into_response::()) + .unwrap() }); println!("{}", results); diff --git a/benches/elastic_raw/src/main.rs b/benches/elastic_raw/src/main.rs index 04ec1d2892..a66928346a 100644 --- a/benches/elastic_raw/src/main.rs +++ b/benches/elastic_raw/src/main.rs @@ -28,7 +28,7 @@ fn main() { .params(|p| p.header(http::header::Connection::keep_alive())) .build() .unwrap(); - + let results = measure::run(runs, || { let req = SearchRequest::for_index_ty("bench_index", "bench_doc", BODY); let mut res = client.request(req).send().unwrap().into_raw(); diff --git a/benches/measure/src/lib.rs b/benches/measure/src/lib.rs index cc74c9c19a..7b19f03fa8 100644 --- a/benches/measure/src/lib.rs +++ b/benches/measure/src/lib.rs @@ -1,8 +1,8 @@ #![feature(test)] extern crate stopwatch; -extern crate time; extern crate test; +extern crate time; use std::env; use std::fmt; @@ -12,7 +12,7 @@ use stopwatch::Stopwatch; pub struct Measure { runs: usize, mean: i64, - percentiles: Vec<(f32, i64)> + percentiles: Vec<(f32, i64)>, } impl fmt::Display for Measure { @@ -34,17 +34,21 @@ pub fn parse_runs_from_env() -> usize { // Get the command name let _ = args.next().unwrap(); - + // Get the first argument as a usize if args.len() >= 1 { - args.next().unwrap().parse::().unwrap_or(default_runs) + args.next() + .unwrap() + .parse::() + .unwrap_or(default_runs) } else { default_runs } } pub fn run(runs: usize, mut f: F) -> Measure - where F: FnMut() -> FOut +where + F: FnMut() -> FOut, { let mut results = Vec::::with_capacity(runs as usize); for _ in 0..runs { @@ -66,22 +70,12 @@ pub fn run(runs: usize, mut f: F) -> Measure Measure { runs: runs, mean: mean, - percentiles: pv + percentiles: pv, } } fn percentiles(data: &Vec, runs: f32) -> Vec<(f32, i64)> { - vec![ - 0.50, - 0.66, - 0.75, - 0.80, - 0.90, - 0.95, - 0.98, - 0.99, - 1.00 - ] + vec![0.50, 0.66, 0.75, 0.80, 0.90, 0.95, 0.98, 0.99, 1.00] .iter() .map(|p| { let p: f32 = *p; diff --git a/benches/prepare/src/main.rs b/benches/prepare/src/main.rs index 76028779a9..1baae049a9 100644 --- a/benches/prepare/src/main.rs +++ b/benches/prepare/src/main.rs @@ -1,10 +1,10 @@ +extern crate serde; #[macro_use] extern crate serde_derive; -extern crate serde; +extern crate elastic; #[macro_use] extern crate elastic_derive; -extern crate elastic; use elastic::prelude::*; @@ -33,7 +33,10 @@ fn main() { client.index_create(index()).send().unwrap(); - client.document_put_mapping::(index()).send().unwrap(); + client + .document_put_mapping::(index()) + .send() + .unwrap(); for i in 0..10 { let doc = BenchDoc { diff --git a/benches/rs-es/src/main.rs b/benches/rs-es/src/main.rs index 341e29bb1a..2f09ee420e 100644 --- a/benches/rs-es/src/main.rs +++ b/benches/rs-es/src/main.rs @@ -21,9 +21,10 @@ fn main() { let mut client = Client::new("http://localhost:9200").unwrap(); let qry = Query::build_query_string("*").build(); - + let results = measure::run(runs, || { - let res: SearchResult = client.search_query() + let res: SearchResult = client + .search_query() .with_indexes(&["bench_index"]) .with_types(&["bench_doc"]) .with_query(&qry) diff --git a/examples/account_sample/src/main.rs b/examples/account_sample/src/main.rs index 73d499a9b5..7e177d348b 100644 --- a/examples/account_sample/src/main.rs +++ b/examples/account_sample/src/main.rs @@ -2,16 +2,16 @@ //! //! It expects you have an Elasticsearch node running on `localhost:9200`. -#[macro_use] -extern crate serde_derive; #[macro_use] extern crate elastic_derive; #[macro_use] extern crate quick_error; +#[macro_use] +extern crate serde_derive; +extern crate elastic; #[macro_use] extern crate serde_json; -extern crate elastic; pub mod model; pub mod ops; @@ -40,7 +40,7 @@ fn run() -> Result<(), Box> { } Ok(()) -} +} fn main() { run().unwrap() diff --git a/examples/account_sample/src/model/account.rs b/examples/account_sample/src/model/account.rs index 101a8eca46..e4de377b8f 100644 --- a/examples/account_sample/src/model/account.rs +++ b/examples/account_sample/src/model/account.rs @@ -5,8 +5,7 @@ //! Field serialisation and mapping is all handled in the same place //! so it's always in sync. -use elastic::types::prelude::{KeywordFieldType, Text, DefaultTextMapping, TextMapping, - Keyword, DefaultKeywordMapping, DocumentType}; +use elastic::types::prelude::{DefaultKeywordMapping, DefaultTextMapping, DocumentType, Keyword, KeywordFieldType, Text, TextMapping}; /// Our main model; an account in the bank. #[derive(Debug, Serialize, Deserialize, ElasticType)] @@ -46,10 +45,8 @@ pub type State = Keyword; #[derive(Debug, Serialize, Deserialize)] pub enum Gender { - #[serde(rename = "F")] - Female, - #[serde(rename = "M")] - Male, + #[serde(rename = "F")] Female, + #[serde(rename = "M")] Male, } impl KeywordFieldType for Gender {} diff --git a/examples/account_sample/src/ops/commands/put_bulk_accounts.rs b/examples/account_sample/src/ops/commands/put_bulk_accounts.rs index 06318c7c10..5e37781eae 100644 --- a/examples/account_sample/src/ops/commands/put_bulk_accounts.rs +++ b/examples/account_sample/src/ops/commands/put_bulk_accounts.rs @@ -1,20 +1,23 @@ -use std::io::{Result as IoResult, Error as IoError}; +use std::io::{Error as IoError, Result as IoResult}; use std::fs::File; use std::path::Path; use ops::Client; -use elastic::client::requests::{SyncBody, BulkRequest}; +use elastic::client::requests::{BulkRequest, SyncBody}; use elastic::client::responses::bulk::{BulkErrorsResponse, ErrorItem}; use elastic::Error as ResponseError; use model; pub trait PutBulkAccounts { - fn put_bulk_accounts

(&self, path: P) -> Result<(), PutBulkAccountsError> where P: AsRef; + fn put_bulk_accounts

(&self, path: P) -> Result<(), PutBulkAccountsError> + where + P: AsRef; } impl PutBulkAccounts for Client { fn put_bulk_accounts

(&self, path: P) -> Result<(), PutBulkAccountsError> - where P: AsRef + where + P: AsRef, { let body = bulk_body(path)?; let req = put(body); @@ -34,13 +37,15 @@ impl PutBulkAccounts for Client { } fn put(body: B) -> BulkRequest<'static, B> - where B: Into +where + B: Into, { BulkRequest::for_index_ty(model::index::name(), model::account::name(), body) } fn bulk_body

(path: P) -> IoResult - where P: AsRef +where + P: AsRef, { File::open(path) } diff --git a/examples/async_raw_sample/src/body/mod.rs b/examples/async_raw_sample/src/body/mod.rs index 4015ff8f07..e0062185c4 100644 --- a/examples/async_raw_sample/src/body/mod.rs +++ b/examples/async_raw_sample/src/body/mod.rs @@ -1,2 +1,2 @@ pub mod request; -pub mod response; \ No newline at end of file +pub mod response; diff --git a/examples/async_raw_sample/src/body/request.rs b/examples/async_raw_sample/src/body/request.rs index 8ebeff2d41..757b8777c6 100644 --- a/examples/async_raw_sample/src/body/request.rs +++ b/examples/async_raw_sample/src/body/request.rs @@ -2,7 +2,7 @@ use std::collections::VecDeque; use std::path::Path; use tokio_proto::streaming::Body as BodyStream; -use futures::{IntoFuture, Future, Stream, Sink, Poll, Async}; +use futures::{Async, Future, IntoFuture, Poll, Sink, Stream}; use futures::future::lazy; use futures::sync::mpsc::SendError; use memmap::{Mmap, MmapViewSync, Protection}; @@ -47,10 +47,9 @@ impl Stream for FileChunkStream { /// /// The first item is a future that will stream chunks from the mapped file. /// The second item is the async body to use in the request. -pub fn mapped_file

- (path: P) - -> (impl Future + Send, FileBody) - where P: AsRef + Send + 'static +pub fn mapped_file

(path: P) -> (impl Future + Send, FileBody) +where + P: AsRef + Send + 'static, { let (tx, rx) = FileBody::pair(); @@ -71,7 +70,8 @@ pub fn mapped_file

// mmap a file and push its chunks into a queue fn map_file_to_chunks

(path: P) -> Result, Error> - where P: AsRef +where + P: AsRef, { let file = Mmap::open_path(path, Protection::Read)?.into_view_sync(); diff --git a/examples/async_raw_sample/src/body/response.rs b/examples/async_raw_sample/src/body/response.rs index 2f7fbaa282..cd8b1c897d 100644 --- a/examples/async_raw_sample/src/body/response.rs +++ b/examples/async_raw_sample/src/body/response.rs @@ -1,6 +1,6 @@ use std::cmp; use std::collections::VecDeque; -use std::io::{Read, Error as IoError}; +use std::io::{Error as IoError, Read}; use hyper::Chunk as HyperChunk; @@ -50,7 +50,8 @@ impl ChunkBodyBuilder { } pub fn append(&mut self, chunk: I) - where I: Into + where + I: Into, { self.0.push_back(chunk.into()); } diff --git a/examples/async_raw_sample/src/hyper_req.rs b/examples/async_raw_sample/src/hyper_req.rs index f1cac80354..b7aa91d088 100644 --- a/examples/async_raw_sample/src/hyper_req.rs +++ b/examples/async_raw_sample/src/hyper_req.rs @@ -2,17 +2,18 @@ use std::str::FromStr; use std::fmt::Debug; use futures::Stream; -use hyper::{Method, Uri, Error as HyperError}; +use hyper::{Error as HyperError, Method, Uri}; use hyper::header::ContentType; use hyper::client::Request; -use elastic_requests::{HttpRequest, HttpMethod}; +use elastic_requests::{HttpMethod, HttpRequest}; /// Build a `hyper` request from an `elastic` request. pub fn build(base_url: &str, req: I) -> Request - where I: Into>, - B: Stream + 'static + Debug, - B::Item: AsRef<[u8]> +where + I: Into>, + B: Stream + 'static + Debug, + B::Item: AsRef<[u8]>, { let req = req.into(); diff --git a/examples/async_raw_sample/src/main.rs b/examples/async_raw_sample/src/main.rs index d4ecfe0f7b..1e87530954 100644 --- a/examples/async_raw_sample/src/main.rs +++ b/examples/async_raw_sample/src/main.rs @@ -5,12 +5,12 @@ extern crate elastic_responses; extern crate string_cache; extern crate futures; -extern crate tokio_proto; extern crate tokio_core; +extern crate tokio_proto; -extern crate memmap; -extern crate hyper; extern crate futures_cpupool; +extern crate hyper; +extern crate memmap; #[macro_use] extern crate quick_error; @@ -26,7 +26,7 @@ use elastic_responses::parse; use tokio_core::reactor::Core; use futures::{Future, Stream}; -use futures_cpupool::{CpuPool, Builder as CpuPoolBuilder}; +use futures_cpupool::{Builder as CpuPoolBuilder, CpuPool}; use hyper::Client; use hyper::client::HttpConnector; @@ -59,10 +59,7 @@ fn main() { core.run(response_future).unwrap(); } -fn send_request(url: &'static str, - client: &Client, - pool: CpuPool) - -> impl Future { +fn send_request(url: &'static str, client: &Client, pool: CpuPool) -> impl Future { // Get a future to buffer a bulk file let (buffer_request_body, request_body) = body::request::mapped_file("./data/accounts.json"); let buffer_request_body = pool.spawn(buffer_request_body); @@ -80,7 +77,8 @@ fn send_request(url: &'static str, let status: u16 = response.status().into(); let chunks = body::response::ChunkBodyBuilder::new(); - response.body() + response + .body() .fold(chunks, concat_chunks) .map(move |chunks| (status, chunks.build())) .map_err(Into::into) @@ -101,9 +99,7 @@ fn send_request(url: &'static str, .map(move |(_, response)| response) } -fn concat_chunks(mut chunks: body::response::ChunkBodyBuilder, - chunk: hyper::Chunk) - -> Result { +fn concat_chunks(mut chunks: body::response::ChunkBodyBuilder, chunk: hyper::Chunk) -> Result { chunks.append(chunk); Ok(chunks) } diff --git a/src/elastic/src/client/async.rs b/src/elastic/src/client/async.rs index 451575b0e4..09dea5663b 100644 --- a/src/elastic/src/client/async.rs +++ b/src/elastic/src/client/async.rs @@ -8,7 +8,7 @@ use reqwest::unstable::async::{Client as AsyncHttpClient, ClientBuilder as Async use error::{self, Error, Result}; use client::requests::HttpRequest; use client::responses::{async_response, AsyncResponseBuilder}; -use client::{private, Client, Sender, RequestParams}; +use client::{private, Client, RequestParams, Sender}; /** An asynchronous Elasticsearch client. @@ -47,8 +47,8 @@ pub type AsyncClient = Client; /** An asynchronous request sender. */ #[derive(Clone)] pub struct AsyncSender { - pub (in client) http: AsyncHttpClient, - pub (in client) serde_pool: Option + pub(in client) http: AsyncHttpClient, + pub(in client) serde_pool: Option, } impl private::Sealed for AsyncSender {} @@ -58,26 +58,39 @@ impl Sender for AsyncSender { type Response = Pending; fn send(&self, req: TRequest, params: &RequestParams) -> Self::Response - where TRequest: Into>, - TBody: Into + where + TRequest: Into>, + TBody: Into, { let serde_pool = self.serde_pool.clone(); let correlation_id = Uuid::new_v4(); let req = req.into(); - info!("Elasticsearch Request: correlation_id: '{}', path: '{}'", correlation_id, req.url.as_ref()); + info!( + "Elasticsearch Request: correlation_id: '{}', path: '{}'", + correlation_id, + req.url.as_ref() + ); let req_future = self.http .elastic_req(params, req) .map_err(move |e| { - error!("Elasticsearch Response: correlation_id: '{}', error: '{}'", correlation_id, e); + error!( + "Elasticsearch Response: correlation_id: '{}', error: '{}'", + correlation_id, + e + ); error::request(e) }) .map(move |res| { - info!("Elasticsearch Response: correlation_id: '{}', status: '{}'", correlation_id, res.status()); + info!( + "Elasticsearch Response: correlation_id: '{}', status: '{}'", + correlation_id, + res.status() + ); async_response(res, serde_pool) }); - + Pending::new(req_future) } } @@ -88,7 +101,10 @@ pub struct Pending { } impl Pending { - fn new(fut: F) -> Self where F: Future + 'static { + fn new(fut: F) -> Self + where + F: Future + 'static, + { Pending { inner: Box::new(fut), } @@ -108,7 +124,7 @@ impl Future for Pending { pub struct AsyncClientBuilder { http: Option, serde_pool: Option, - params: RequestParams + params: RequestParams, } impl Default for AsyncClientBuilder { @@ -132,7 +148,7 @@ impl AsyncClientBuilder { AsyncClientBuilder { http: None, serde_pool: None, - params: RequestParams::default() + params: RequestParams::default(), } } @@ -143,7 +159,7 @@ impl AsyncClientBuilder { AsyncClientBuilder { http: None, serde_pool: None, - params: params + params: params, } } @@ -164,8 +180,9 @@ impl AsyncClientBuilder { .base_url("https://my_es_cluster/some_path"); ``` */ - pub fn base_url(mut self, base_url: I) -> Self - where I: Into + pub fn base_url(mut self, base_url: I) -> Self + where + I: Into, { self.params = self.params.base_url(base_url); @@ -206,7 +223,8 @@ impl AsyncClientBuilder { [SyncClientBuilder.base_url]: #method.base_url */ pub fn params(mut self, builder: F) -> Self - where F: Fn(RequestParams) -> RequestParams + where + F: Fn(RequestParams) -> RequestParams, { self.params = builder(self.params); @@ -237,8 +255,9 @@ impl AsyncClientBuilder { # } ``` */ - pub fn serde_pool

(mut self, serde_pool: P) -> Self - where P: Into> + pub fn serde_pool

(mut self, serde_pool: P) -> Self + where + P: Into>, { self.serde_pool = serde_pool.into(); @@ -258,9 +277,10 @@ impl AsyncClientBuilder { [Client]: struct.Client.html */ pub fn build(self, handle: &Handle) -> Result { - let http = self.http.map(Ok) - .unwrap_or_else(|| AsyncHttpClientBuilder::new().build(handle)) - .map_err(error::build)?; + let http = self.http + .map(Ok) + .unwrap_or_else(|| AsyncHttpClientBuilder::new().build(handle)) + .map_err(error::build)?; Ok(AsyncClient { sender: AsyncSender { diff --git a/src/elastic/src/client/mod.rs b/src/elastic/src/client/mod.rs index 49b459b637..ebfd613298 100644 --- a/src/elastic/src/client/mod.rs +++ b/src/elastic/src/client/mod.rs @@ -508,8 +508,9 @@ pub trait Sender: private::Sealed + Clone { /// Send a request. fn send(&self, req: TRequest, params: &RequestParams) -> Self::Response - where TRequest: Into>, - TBody: Into; + where + TRequest: Into>, + TBody: Into; } /** @@ -574,7 +575,7 @@ pub struct Client { pub mod prelude { /*! A glob import for convenience. */ - pub use super::{SyncClientBuilder, AsyncClientBuilder, SyncClient, AsyncClient, RequestParams}; + pub use super::{AsyncClient, AsyncClientBuilder, RequestParams, SyncClient, SyncClientBuilder}; pub use super::requests::prelude::*; pub use super::responses::prelude::*; } @@ -582,7 +583,7 @@ pub mod prelude { #[cfg(test)] mod tests { use super::*; - use ::tests::*; + use tests::*; #[test] fn client_is_send_sync() { diff --git a/src/elastic/src/client/requests/document_get.rs b/src/elastic/src/client/requests/document_get.rs index 2f463f0af6..6399e993ba 100644 --- a/src/elastic/src/client/requests/document_get.rs +++ b/src/elastic/src/client/requests/document_get.rs @@ -8,10 +8,10 @@ use std::marker::PhantomData; use futures::{Future, Poll}; use serde::de::DeserializeOwned; -use error::{Result, Error}; -use client::{Client, Sender, SyncSender, AsyncSender}; +use error::{Error, Result}; +use client::{AsyncSender, Client, Sender, SyncSender}; use client::requests::RequestBuilder; -use client::requests::params::{Index, Type, Id}; +use client::requests::params::{Id, Index, Type}; use client::requests::endpoints::GetRequest; use client::requests::raw::RawRequestInner; use client::responses::GetResponse; @@ -41,8 +41,9 @@ pub struct GetRequestInner { /** # Get document */ -impl Client - where TSender: Sender +impl Client +where + TSender: Sender, { /** Create a [`GetRequestBuilder`][GetRequestBuilder] with this `Client` that can be configured before sending. @@ -113,22 +114,22 @@ impl Client [types-mod]: ../../types/index.html [documents-mod]: ../../types/document/index.html */ - pub fn document_get(&self, - index: Index<'static>, - id: Id<'static>) - -> GetRequestBuilder - where TDocument: DeserializeOwned + DocumentType + pub fn document_get(&self, index: Index<'static>, id: Id<'static>) -> GetRequestBuilder + where + TDocument: DeserializeOwned + DocumentType, { let ty = TDocument::name().into(); - RequestBuilder::new(self.clone(), - None, - GetRequestInner { - index: index, - ty: ty, - id: id, - _marker: PhantomData, - }) + RequestBuilder::new( + self.clone(), + None, + GetRequestInner { + index: index, + ty: ty, + id: id, + _marker: PhantomData, + }, + ) } } @@ -144,11 +145,13 @@ impl GetRequestInner { Configure a `GetRequestBuilder` before sending it. */ impl GetRequestBuilder - where TSender: Sender +where + TSender: Sender, { /** Set the type for the get request. */ pub fn ty(mut self, ty: I) -> Self - where I: Into> + where + I: Into>, { self.inner.ty = ty.into(); self @@ -159,7 +162,8 @@ impl GetRequestBuilder # Send synchronously */ impl GetRequestBuilder - where TDocument: DeserializeOwned +where + TDocument: DeserializeOwned, { /** Send a `GetRequestBuilder` synchronously using a [`SyncClient`][SyncClient]. @@ -207,7 +211,8 @@ impl GetRequestBuilder # Send asynchronously */ impl GetRequestBuilder - where TDocument: DeserializeOwned + Send + 'static, +where + TDocument: DeserializeOwned + Send + 'static, { /** Send a `GetRequestBuilder` asynchronously using an [`AsyncClient`][AsyncClient]. @@ -267,15 +272,19 @@ pub struct Pending { } impl Pending { - fn new(fut: F) -> Self where F: Future, Error = Error> + 'static { + fn new(fut: F) -> Self + where + F: Future, Error = Error> + 'static, + { Pending { inner: Box::new(fut), } } } -impl Future for Pending - where TDocument: DeserializeOwned + Send + 'static, +impl Future for Pending +where + TDocument: DeserializeOwned + Send + 'static, { type Item = GetResponse; type Error = Error; @@ -296,7 +305,8 @@ mod tests { let req = client .document_get::(index("test-idx"), id("1")) - .inner.into_request(); + .inner + .into_request(); assert_eq!("/test-idx/value/1", req.url.as_ref()); } @@ -308,7 +318,8 @@ mod tests { let req = client .document_get::(index("test-idx"), id("1")) .ty("new-ty") - .inner.into_request(); + .inner + .into_request(); assert_eq!("/test-idx/new-ty/1", req.url.as_ref()); } diff --git a/src/elastic/src/client/requests/document_index.rs b/src/elastic/src/client/requests/document_index.rs index dd420c6a8d..293391e766 100644 --- a/src/elastic/src/client/requests/document_index.rs +++ b/src/elastic/src/client/requests/document_index.rs @@ -9,10 +9,10 @@ use futures::{Future, IntoFuture, Poll}; use futures_cpupool::CpuPool; use serde::Serialize; -use error::{self, Result, Error}; -use client::{Client, Sender, SyncSender, AsyncSender}; +use error::{self, Error, Result}; +use client::{AsyncSender, Client, Sender, SyncSender}; use client::requests::RequestBuilder; -use client::requests::params::{Index, Type, Id}; +use client::requests::params::{Id, Index, Type}; use client::requests::endpoints::IndexRequest; use client::requests::raw::RawRequestInner; use client::responses::IndexResponse; @@ -42,8 +42,9 @@ pub struct IndexRequestInner { /** # Index request */ -impl Client - where TSender: Sender +impl Client +where + TSender: Sender, { /** Create a [`IndexRequestBuilder`][IndexRequestBuilder] with this `Client` that can be configured before sending. @@ -96,38 +97,44 @@ impl Client [types-mod]: ../../types/index.html [documents-mod]: ../../types/document/index.html */ - pub fn document_index(&self, - index: Index<'static>, - id: Id<'static>, - doc: TDocument) - -> IndexRequestBuilder - where TDocument: Serialize + DocumentType + pub fn document_index(&self, index: Index<'static>, id: Id<'static>, doc: TDocument) -> IndexRequestBuilder + where + TDocument: Serialize + DocumentType, { let ty = TDocument::name().into(); - RequestBuilder::new(self.clone(), - None, - IndexRequestInner { - index: index, - ty: ty, - id: id, - doc: doc, - }) + RequestBuilder::new( + self.clone(), + None, + IndexRequestInner { + index: index, + ty: ty, + id: id, + doc: doc, + }, + ) } } impl IndexRequestInner - where TDocument: Serialize +where + TDocument: Serialize, { fn into_sync_request(self) -> Result>> { let body = serde_json::to_vec(&self.doc).map_err(error::request)?; - Ok(IndexRequest::for_index_ty_id(self.index, self.ty, self.id, body)) + Ok(IndexRequest::for_index_ty_id( + self.index, + self.ty, + self.id, + body, + )) } } impl IndexRequestInner - where TDocument: Serialize + Send + 'static +where + TDocument: Serialize + Send + 'static, { fn into_async_request(self, ser_pool: Option) -> Box>, Error = Error>> { if let Some(ser_pool) = ser_pool { @@ -145,12 +152,14 @@ impl IndexRequestInner Configure a `IndexRequestBuilder` before sending it. */ -impl IndexRequestBuilder - where TSender: Sender +impl IndexRequestBuilder +where + TSender: Sender, { /** Set the type for the index request. */ pub fn ty(mut self, ty: I) -> Self - where I: Into> + where + I: Into>, { self.inner.ty = ty.into(); self @@ -161,7 +170,8 @@ impl IndexRequestBuilder # Send synchronously */ impl IndexRequestBuilder - where TDocument: Serialize +where + TDocument: Serialize, { /** Send a `IndexRequestBuilder` synchronously using a [`SyncClient`][SyncClient]. @@ -216,7 +226,8 @@ impl IndexRequestBuilder # Send asynchronously */ impl IndexRequestBuilder - where TDocument: Serialize + Send + 'static +where + TDocument: Serialize + Send + 'static, { /** Send a `IndexRequestBuilder` asynchronously using an [`AsyncClient`][AsyncClient]. @@ -274,8 +285,8 @@ impl IndexRequestBuilder let res_future = req_future.and_then(move |req| { RequestBuilder::new(client, params, RawRequestInner::new(req)) - .send() - .and_then(|res| res.into_response()) + .send() + .and_then(|res| res.into_response()) }); Pending::new(res_future) @@ -288,7 +299,10 @@ pub struct Pending { } impl Pending { - fn new(fut: F) -> Self where F: Future + 'static { + fn new(fut: F) -> Self + where + F: Future + 'static, + { Pending { inner: Box::new(fut), } @@ -315,7 +329,8 @@ mod tests { let req = client .document_index(index("test-idx"), id("1"), Value::Null) - .inner.into_sync_request() + .inner + .into_sync_request() .unwrap(); assert_eq!("/test-idx/value/1", req.url.as_ref()); @@ -329,7 +344,8 @@ mod tests { let req = client .document_index(index("test-idx"), id("1"), Value::Null) .ty("new-ty") - .inner.into_sync_request() + .inner + .into_sync_request() .unwrap(); assert_eq!("/test-idx/new-ty/1", req.url.as_ref()); @@ -342,7 +358,8 @@ mod tests { let doc = Value::Null; let req = client .document_index(index("test-idx"), id("1"), &doc) - .inner.into_sync_request() + .inner + .into_sync_request() .unwrap(); assert_eq!("/test-idx/value/1", req.url.as_ref()); diff --git a/src/elastic/src/client/requests/document_put_mapping.rs b/src/elastic/src/client/requests/document_put_mapping.rs index 4bed39e917..bda9510842 100644 --- a/src/elastic/src/client/requests/document_put_mapping.rs +++ b/src/elastic/src/client/requests/document_put_mapping.rs @@ -10,8 +10,8 @@ use futures::{Future, IntoFuture, Poll}; use futures_cpupool::CpuPool; use serde::Serialize; -use error::{self, Result, Error}; -use client::{Client, Sender, SyncSender, AsyncSender}; +use error::{self, Error, Result}; +use client::{AsyncSender, Client, Sender, SyncSender}; use client::requests::RequestBuilder; use client::requests::params::{Index, Type}; use client::requests::endpoints::IndicesPutMappingRequest; @@ -42,8 +42,9 @@ pub struct PutMappingRequestInner { /** # Put mapping request */ -impl Client - where TSender: Sender +impl Client +where + TSender: Sender, { /** Create a [`PutMappingRequestBuilder`][PutMappingRequestBuilder] with this `Client` that can be configured before sending. @@ -86,35 +87,42 @@ impl Client [types-mod]: ../../types/index.html [documents-mod]: ../../types/document/index.html */ - pub fn document_put_mapping(&self, - index: Index<'static>) - -> PutMappingRequestBuilder - where TDocument: Serialize + DocumentType + pub fn document_put_mapping(&self, index: Index<'static>) -> PutMappingRequestBuilder + where + TDocument: Serialize + DocumentType, { let ty = TDocument::name().into(); - RequestBuilder::new(self.clone(), - None, - PutMappingRequestInner { - index: index, - ty: ty, - _marker: PhantomData, - }) + RequestBuilder::new( + self.clone(), + None, + PutMappingRequestInner { + index: index, + ty: ty, + _marker: PhantomData, + }, + ) } } impl PutMappingRequestInner - where TDocument: DocumentType +where + TDocument: DocumentType, { fn into_sync_request(self) -> Result>> { let body = serde_json::to_vec(&TDocument::index_mapping()).map_err(error::request)?; - Ok(IndicesPutMappingRequest::for_index_ty(self.index, self.ty, body)) + Ok(IndicesPutMappingRequest::for_index_ty( + self.index, + self.ty, + body, + )) } } impl PutMappingRequestInner - where TDocument: DocumentType + Send + 'static +where + TDocument: DocumentType + Send + 'static, { fn into_async_request(self, ser_pool: Option) -> Box>, Error = Error>> { if let Some(ser_pool) = ser_pool { @@ -133,11 +141,13 @@ impl PutMappingRequestInner Configure a `PutMappingRequestBuilder` before sending it. */ impl PutMappingRequestBuilder - where TSender: Sender +where + TSender: Sender, { /** Set the type for the put mapping request. */ pub fn ty(mut self, ty: I) -> Self - where I: Into> + where + I: Into>, { self.inner.ty = ty.into(); self @@ -148,7 +158,8 @@ impl PutMappingRequestBuilder # Send synchronously */ impl PutMappingRequestBuilder - where TDocument: DocumentType +where + TDocument: DocumentType, { /** Send a `PutMappingRequestBuilder` synchronously using a [`SyncClient`][SyncClient]. @@ -193,7 +204,8 @@ impl PutMappingRequestBuilder # Send asynchronously */ impl PutMappingRequestBuilder - where TDocument: DocumentType + Send + 'static +where + TDocument: DocumentType + Send + 'static, { /** Send a `PutMappingRequestBuilder` asynchronously using an [`AsyncClient`][AsyncClient]. @@ -241,8 +253,8 @@ impl PutMappingRequestBuilder let res_future = req_future.and_then(move |req| { RequestBuilder::new(client, params, RawRequestInner::new(req)) - .send() - .and_then(|res| res.into_response()) + .send() + .and_then(|res| res.into_response()) }); Pending::new(res_future) @@ -255,7 +267,10 @@ pub struct Pending { } impl Pending { - fn new(fut: F) -> Self where F: Future + 'static { + fn new(fut: F) -> Self + where + F: Future + 'static, + { Pending { inner: Box::new(fut), } @@ -282,7 +297,8 @@ mod tests { let req = client .document_put_mapping::(index("test-idx")) - .inner.into_sync_request() + .inner + .into_sync_request() .unwrap(); assert_eq!("/test-idx/_mappings/value", req.url.as_ref()); @@ -296,7 +312,8 @@ mod tests { let req = client .document_put_mapping::(index("test-idx")) .ty("new-ty") - .inner.into_sync_request() + .inner + .into_sync_request() .unwrap(); assert_eq!("/test-idx/_mappings/new-ty", req.url.as_ref()); diff --git a/src/elastic/src/client/requests/index_create.rs b/src/elastic/src/client/requests/index_create.rs index 645f9202a1..fa6cd2f1d7 100644 --- a/src/elastic/src/client/requests/index_create.rs +++ b/src/elastic/src/client/requests/index_create.rs @@ -7,7 +7,7 @@ Builders for [create index requests][docs-create-index]. use futures::{Future, Poll}; use error::*; -use client::{Client, Sender, SyncSender, AsyncSender}; +use client::{AsyncSender, Client, Sender, SyncSender}; use client::requests::{empty_body, DefaultBody, RequestBuilder}; use client::requests::params::Index; use client::requests::endpoints::IndicesCreateRequest; @@ -36,8 +36,9 @@ pub struct IndexCreateRequestInner { /** # Create index request */ -impl Client - where TSender: Sender +impl Client +where + TSender: Sender, { /** Create a [`IndexCreateRequestBuilder`][IndexCreateRequestBuilder] with this `Client` that can be configured before sending. @@ -114,12 +115,14 @@ impl Client [documents-mod]: ../../types/document/index.html */ pub fn index_create(&self, index: Index<'static>) -> IndexCreateRequestBuilder { - RequestBuilder::new(self.clone(), - None, - IndexCreateRequestInner { - index: index, - body: empty_body(), - }) + RequestBuilder::new( + self.clone(), + None, + IndexCreateRequestInner { + index: index, + body: empty_body(), + }, + ) } } @@ -135,25 +138,27 @@ impl IndexCreateRequestInner { Configure a `IndexCreateRequestBuilder` before sending it. */ impl IndexCreateRequestBuilder - where TSender: Sender, - TBody: Into +where + TSender: Sender, + TBody: Into, { /** Set the body for the create index request. If no body is specified then an empty query will be used. */ - pub fn body(self, - body: TNewBody) - -> IndexCreateRequestBuilder - where TNewBody: Into + pub fn body(self, body: TNewBody) -> IndexCreateRequestBuilder + where + TNewBody: Into, { - RequestBuilder::new(self.client, - self.params, - IndexCreateRequestInner { - index: self.inner.index, - body: body, - }) + RequestBuilder::new( + self.client, + self.params, + IndexCreateRequestInner { + index: self.inner.index, + body: body, + }, + ) } } @@ -161,7 +166,8 @@ impl IndexCreateRequestBuilder # Send synchronously */ impl IndexCreateRequestBuilder - where TBody: Into<::Body> +where + TBody: Into<::Body>, { /** Send a `IndexCreateRequestBuilder` synchronously using a [`SyncClient`][SyncClient]. @@ -202,7 +208,8 @@ impl IndexCreateRequestBuilder # Send asynchronously */ impl IndexCreateRequestBuilder - where TBody: Into<::Body> +where + TBody: Into<::Body>, { /** Send a `IndexCreateRequestBuilder` asynchronously using an [`AsyncClient`][AsyncClient]. @@ -255,7 +262,10 @@ pub struct Pending { } impl Pending { - fn new(fut: F) -> Self where F: Future + 'static { + fn new(fut: F) -> Self + where + F: Future + 'static, + { Pending { inner: Box::new(fut), } @@ -291,7 +301,8 @@ mod tests { let req = client .index_create(index("testindex")) .body("{}") - .inner.into_request(); + .inner + .into_request(); assert_eq!("{}", req.body); } diff --git a/src/elastic/src/client/requests/mod.rs b/src/elastic/src/client/requests/mod.rs index adad87f24d..70772d54c8 100644 --- a/src/elastic/src/client/requests/mod.rs +++ b/src/elastic/src/client/requests/mod.rs @@ -6,10 +6,10 @@ This module contains implementation details that are useful if you want to custo use futures_cpupool::CpuPool; -use client::{Client, Sender, AsyncSender, RequestParams}; +use client::{AsyncSender, Client, RequestParams, Sender}; -pub use elastic_reqwest::{SyncBody, AsyncBody}; -pub use elastic_reqwest::req::{HttpRequest, HttpMethod, empty_body, Url, DefaultBody}; +pub use elastic_reqwest::{AsyncBody, SyncBody}; +pub use elastic_reqwest::req::{empty_body, DefaultBody, HttpMethod, HttpRequest, Url}; pub use elastic_reqwest::req::params; pub use elastic_reqwest::req::endpoints; @@ -46,8 +46,9 @@ The `RequestBuilder` has two generic parameters: `RequestBuilder` contains methods that are common to all request builders. */ -pub struct RequestBuilder - where TSender: Sender +pub struct RequestBuilder +where + TSender: Sender, { client: Client, params: Option, @@ -59,8 +60,9 @@ pub struct RequestBuilder The following methods can be called on any request builder, whether it's synchronous or asynchronous. */ -impl RequestBuilder - where TSender: Sender +impl RequestBuilder +where + TSender: Sender, { fn new(client: Client, params: Option, req: TRequest) -> Self { RequestBuilder { @@ -94,14 +96,13 @@ impl RequestBuilder ``` */ pub fn params(mut self, builder: F) -> Self - where F: Fn(RequestParams) -> RequestParams + where + F: Fn(RequestParams) -> RequestParams, { let params = self.params; let client = self.client; - self.params = { - Some(builder(params.unwrap_or_else(|| client.params.clone()))) - }; + self.params = { Some(builder(params.unwrap_or_else(|| client.params.clone()))) }; self.client = client; @@ -160,7 +161,8 @@ impl RequestBuilder { ``` */ pub fn serde_pool

(mut self, pool: P) -> Self - where P: Into> + where + P: Into>, { self.client.sender.serde_pool = pool.into(); @@ -174,7 +176,7 @@ pub mod prelude { pub use super::params::*; pub use super::endpoints::*; - pub use super::{empty_body, DefaultBody, RawRequestBuilder, SearchRequestBuilder, GetRequestBuilder, IndexRequestBuilder, PutMappingRequestBuilder, IndexCreateRequestBuilder}; + pub use super::{empty_body, DefaultBody, GetRequestBuilder, IndexCreateRequestBuilder, IndexRequestBuilder, PutMappingRequestBuilder, RawRequestBuilder, SearchRequestBuilder}; } #[cfg(test)] @@ -184,7 +186,10 @@ mod tests { #[test] fn request_builder_params() { - let client = SyncClientBuilder::new().base_url("http://eshost:9200").build().unwrap(); + let client = SyncClientBuilder::new() + .base_url("http://eshost:9200") + .build() + .unwrap(); let req = RequestBuilder::new(client.clone(), None, PingRequest::new()) .params(|p| p.url_param("pretty", true)) diff --git a/src/elastic/src/client/requests/raw.rs b/src/elastic/src/client/requests/raw.rs index cd647c21fe..af80455129 100644 --- a/src/elastic/src/client/requests/raw.rs +++ b/src/elastic/src/client/requests/raw.rs @@ -20,7 +20,7 @@ pub type RawRequestBuilder = RequestBuilder { req: TRequest, - _marker: PhantomData + _marker: PhantomData, } impl RawRequestInner { @@ -35,8 +35,9 @@ impl RawRequestInner { /** # Raw request */ -impl Client - where TSender: Sender +impl Client +where + TSender: Sender, { /** Create a [`RawRequestBuilder`][RawRequestBuilder] with this `Client` that can be configured before sending. @@ -73,17 +74,19 @@ impl Client [endpoints-mod]: requests/endpoints/index.html */ pub fn request(&self, req: TRequest) -> RawRequestBuilder - where TRequest: Into>, - TBody: Into + where + TRequest: Into>, + TBody: Into, { RequestBuilder::new(self.clone(), None, RawRequestInner::new(req)) } } impl RawRequestBuilder - where TSender: Sender, - TRequest: Into>, - TBody: Into<::Body> +where + TSender: Sender, + TRequest: Into>, + TBody: Into<::Body>, { /** Send a `RawRequestBuilder`. diff --git a/src/elastic/src/client/requests/search.rs b/src/elastic/src/client/requests/search.rs index e474817e90..e10dd0a231 100644 --- a/src/elastic/src/client/requests/search.rs +++ b/src/elastic/src/client/requests/search.rs @@ -8,8 +8,8 @@ use std::marker::PhantomData; use futures::{Future, Poll}; use serde::de::DeserializeOwned; -use error::{Result, Error}; -use client::{Client, Sender, SyncSender, AsyncSender}; +use error::{Error, Result}; +use client::{AsyncSender, Client, Sender, SyncSender}; use client::requests::{empty_body, DefaultBody, RequestBuilder}; use client::requests::params::{Index, Type}; use client::requests::endpoints::SearchRequest; @@ -40,8 +40,9 @@ pub struct SearchRequestInner { /** # Search request */ -impl Client - where TSender: Sender +impl Client +where + TSender: Sender, { /** Create a [`SearchRequestBuilder`][SearchRequestBuilder] with this `Client` that can be configured before sending. @@ -117,17 +118,17 @@ impl Client [documents-mod]: ../../types/document/index.html [docs-querystring]: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html */ - pub fn search - (&self) - -> SearchRequestBuilder - where TDocument: DeserializeOwned + pub fn search(&self) -> SearchRequestBuilder + where + TDocument: DeserializeOwned, { RequestBuilder::new(self.clone(), None, SearchRequestInner::new(empty_body())) } } impl SearchRequestInner - where TDocument: DeserializeOwned +where + TDocument: DeserializeOwned, { fn new(body: TBody) -> Self { SearchRequestInner { @@ -154,7 +155,8 @@ impl SearchRequestInner Configure a `SearchRequestBuilder` before sending it. */ impl SearchRequestBuilder - where TSender: Sender +where + TSender: Sender, { /** Set the indices for the search request. @@ -162,7 +164,8 @@ impl SearchRequestBuilder If no index is specified then `_all` will be used. */ pub fn index(mut self, index: I) -> Self - where I: Into> + where + I: Into>, { self.inner.index = Some(index.into()); self @@ -170,7 +173,8 @@ impl SearchRequestBuilder /** Set the types for the search request. */ pub fn ty(mut self, ty: Option) -> Self - where I: Into> + where + I: Into>, { self.inner.ty = ty.map(Into::into); self @@ -181,19 +185,20 @@ impl SearchRequestBuilder If no body is specified then an empty query will be used. */ - pub fn body(self, - body: TNewBody) - -> SearchRequestBuilder - where TNewBody: Into + pub fn body(self, body: TNewBody) -> SearchRequestBuilder + where + TNewBody: Into, { - RequestBuilder::new(self.client, - self.params, - SearchRequestInner { - body: body, - index: self.inner.index, - ty: self.inner.ty, - _marker: PhantomData, - }) + RequestBuilder::new( + self.client, + self.params, + SearchRequestInner { + body: body, + index: self.inner.index, + ty: self.inner.ty, + _marker: PhantomData, + }, + ) } } @@ -201,8 +206,9 @@ impl SearchRequestBuilder # Send synchronously */ impl SearchRequestBuilder - where TDocument: DeserializeOwned, - TBody: Into<::Body> +where + TDocument: DeserializeOwned, + TBody: Into<::Body>, { /** Send a `SearchRequestBuilder` synchronously using a [`SyncClient`][SyncClient]. @@ -253,8 +259,9 @@ impl SearchRequestBuilder # Send asynchronously */ impl SearchRequestBuilder - where TDocument: DeserializeOwned + Send + 'static, - TBody: Into<::Body> +where + TDocument: DeserializeOwned + Send + 'static, + TBody: Into<::Body>, { /** Send a `SearchRequestBuilder` asynchronously using an [`AsyncClient`][AsyncClient]. @@ -317,15 +324,19 @@ pub struct Pending { } impl Pending { - fn new(fut: F) -> Self where F: Future, Error = Error> + 'static { + fn new(fut: F) -> Self + where + F: Future, Error = Error> + 'static, + { Pending { inner: Box::new(fut), } } } -impl Future for Pending - where TDocument: DeserializeOwned + Send + 'static, +impl Future for Pending +where + TDocument: DeserializeOwned + Send + 'static, { type Item = SearchResponse; type Error = Error; @@ -353,7 +364,11 @@ mod tests { fn specify_index() { let client = SyncClientBuilder::new().build().unwrap(); - let req = client.search::().index("new-idx").inner.into_request(); + let req = client + .search::() + .index("new-idx") + .inner + .into_request(); assert_eq!("/new-idx/_search", req.url.as_ref()); } @@ -365,7 +380,8 @@ mod tests { let req = client .search::() .ty(Some("new-ty")) - .inner.into_request(); + .inner + .into_request(); assert_eq!("/_all/new-ty/_search", req.url.as_ref()); } diff --git a/src/elastic/src/client/responses/async.rs b/src/elastic/src/client/responses/async.rs index b8adcfcb17..ce8878d869 100644 --- a/src/elastic/src/client/responses/async.rs +++ b/src/elastic/src/client/responses/async.rs @@ -1,5 +1,5 @@ use std::mem; -use futures::{Future, Stream, Poll}; +use futures::{Future, Poll, Stream}; use futures_cpupool::CpuPool; use serde::de::DeserializeOwned; use reqwest::unstable::async::{Decoder, Response as RawResponse}; @@ -16,13 +16,13 @@ You can also `Read` directly from the response body. */ pub struct AsyncResponseBuilder { inner: RawResponse, - de_pool: Option + de_pool: Option, } pub(crate) fn async_response(res: RawResponse, de_pool: Option) -> AsyncResponseBuilder { AsyncResponseBuilder { inner: res, - de_pool: de_pool + de_pool: de_pool, } } @@ -111,22 +111,25 @@ impl AsyncResponseBuilder { [response-types]: parse/trait.IsOk.html#implementors */ pub fn into_response(mut self) -> IntoResponse - where T: IsOk + DeserializeOwned + Send + 'static + where + T: IsOk + DeserializeOwned + Send + 'static, { let status = self.status(); let body = mem::replace(self.inner.body_mut(), Decoder::empty()); let de_fn = move |body: AsyncChunk| { - parse().from_slice(status, body.as_ref()) - .map_err(move |e| error::response(status, e)) + parse() + .from_slice(status, body.as_ref()) + .map_err(move |e| error::response(status, e)) }; let body_future = body.concat2().map_err(move |e| error::response(status, e)); if let Some(de_pool) = self.de_pool { - IntoResponse::new(body_future.and_then(move |body| de_pool.spawn_fn(move || de_fn(body)))) - } - else { + IntoResponse::new( + body_future.and_then(move |body| de_pool.spawn_fn(move || de_fn(body))), + ) + } else { IntoResponse::new(body_future.and_then(de_fn)) } } @@ -138,15 +141,19 @@ pub struct IntoResponse { } impl IntoResponse { - fn new(fut: F) -> Self where F: Future + 'static { + fn new(fut: F) -> Self + where + F: Future + 'static, + { IntoResponse { inner: Box::new(fut), } } } -impl Future for IntoResponse - where T: IsOk + DeserializeOwned + Send + 'static +impl Future for IntoResponse +where + T: IsOk + DeserializeOwned + Send + 'static, { type Item = T; type Error = Error; diff --git a/src/elastic/src/client/responses/mod.rs b/src/elastic/src/client/responses/mod.rs index 33d4613934..4c467c0a2b 100644 --- a/src/elastic/src/client/responses/mod.rs +++ b/src/elastic/src/client/responses/mod.rs @@ -16,8 +16,7 @@ pub mod parse; pub use self::sync::*; pub use self::async::*; -pub use elastic_reqwest::res::{SearchResponse, GetResponse, Shards, CommandResponse, IndexResponse, PingResponse, - BulkResponse, BulkErrorsResponse}; +pub use elastic_reqwest::res::{BulkErrorsResponse, BulkResponse, CommandResponse, GetResponse, IndexResponse, PingResponse, SearchResponse, Shards}; pub use elastic_reqwest::res::search; pub use elastic_reqwest::res::bulk; @@ -25,9 +24,8 @@ pub use elastic_reqwest::res::bulk; pub mod prelude { /*! A glob import for convenience. */ - pub use super::{SearchResponse, GetResponse, Shards, CommandResponse, IndexResponse, PingResponse, - BulkResponse, BulkErrorsResponse}; + pub use super::{BulkErrorsResponse, BulkResponse, CommandResponse, GetResponse, IndexResponse, PingResponse, SearchResponse, Shards}; pub use super::async::AsyncResponseBuilder; pub use super::sync::SyncResponseBuilder; -} \ No newline at end of file +} diff --git a/src/elastic/src/client/responses/parse.rs b/src/elastic/src/client/responses/parse.rs index 3ac19ccb55..fb46de2343 100644 --- a/src/elastic/src/client/responses/parse.rs +++ b/src/elastic/src/client/responses/parse.rs @@ -89,6 +89,5 @@ See the [`IsOk`][IsOk] trait for more details. pub(super) use elastic_reqwest::res::parse; -pub use elastic_reqwest::res::parsing::{HttpResponseHead, IsOk, ResponseBody, MaybeOkResponse, - MaybeBufferedResponse, Unbuffered, Buffered}; +pub use elastic_reqwest::res::parsing::{Buffered, HttpResponseHead, IsOk, MaybeBufferedResponse, MaybeOkResponse, ResponseBody, Unbuffered}; pub use elastic_reqwest::res::error::ParseResponseError; diff --git a/src/elastic/src/client/responses/sync.rs b/src/elastic/src/client/responses/sync.rs index 8e88af994e..6b21ac497d 100644 --- a/src/elastic/src/client/responses/sync.rs +++ b/src/elastic/src/client/responses/sync.rs @@ -90,10 +90,13 @@ impl SyncResponseBuilder { [response-types]: parse/trait.IsOk.html#implementors */ pub fn into_response(self) -> Result - where T: IsOk + DeserializeOwned + where + T: IsOk + DeserializeOwned, { let status = self.status(); - parse().from_response(self.0).map_err(|e| error::response(status, e)) + parse() + .from_response(self.0) + .map_err(|e| error::response(status, e)) } } diff --git a/src/elastic/src/client/sync.rs b/src/elastic/src/client/sync.rs index eb52f4c25c..f43faa2ade 100644 --- a/src/elastic/src/client/sync.rs +++ b/src/elastic/src/client/sync.rs @@ -5,7 +5,7 @@ use reqwest::{Client as SyncHttpClient, ClientBuilder as SyncHttpClientBuilder}; use error::{self, Result}; use client::requests::HttpRequest; use client::responses::{sync_response, SyncResponseBuilder}; -use client::{private, Client, Sender, RequestParams}; +use client::{private, Client, RequestParams, Sender}; /** A synchronous Elasticsearch client. @@ -37,7 +37,7 @@ pub type SyncClient = Client; /** A synchronous request sender. */ #[derive(Clone)] pub struct SyncSender { - pub (in client) http: SyncHttpClient + pub(in client) http: SyncHttpClient, } impl private::Sealed for SyncSender {} @@ -47,25 +47,38 @@ impl Sender for SyncSender { type Response = Result; fn send(&self, req: TRequest, params: &RequestParams) -> Self::Response - where TRequest: Into>, - TBody: Into + where + TRequest: Into>, + TBody: Into, { let correlation_id = Uuid::new_v4(); let req = req.into(); - info!("Elasticsearch Request: correlation_id: '{}', path: '{}'", correlation_id, req.url.as_ref()); + info!( + "Elasticsearch Request: correlation_id: '{}', path: '{}'", + correlation_id, + req.url.as_ref() + ); let res = match self.http.elastic_req(params, req).map_err(error::request) { Ok(res) => { - info!("Elasticsearch Response: correlation_id: '{}', status: '{}'", correlation_id, res.status()); + info!( + "Elasticsearch Response: correlation_id: '{}', status: '{}'", + correlation_id, + res.status() + ); res - }, + } Err(e) => { - error!("Elasticsearch Response: correlation_id: '{}', error: '{}'", correlation_id, e); + error!( + "Elasticsearch Response: correlation_id: '{}', error: '{}'", + correlation_id, + e + ); Err(e)? } }; - + Ok(sync_response(res)) } } @@ -73,7 +86,7 @@ impl Sender for SyncSender { /** A builder for a syncronous client. */ pub struct SyncClientBuilder { http: Option, - params: RequestParams + params: RequestParams, } impl Default for SyncClientBuilder { @@ -95,7 +108,7 @@ impl SyncClientBuilder { pub fn new() -> Self { SyncClientBuilder { http: None, - params: RequestParams::default() + params: RequestParams::default(), } } @@ -105,7 +118,7 @@ impl SyncClientBuilder { pub fn from_params(params: RequestParams) -> Self { SyncClientBuilder { http: None, - params: params + params: params, } } @@ -126,8 +139,9 @@ impl SyncClientBuilder { .base_url("https://my_es_cluster/some_path"); ``` */ - pub fn base_url(mut self, base_url: I) -> Self - where I: Into + pub fn base_url(mut self, base_url: I) -> Self + where + I: Into, { self.params = self.params.base_url(base_url); @@ -168,7 +182,8 @@ impl SyncClientBuilder { [SyncClientBuilder.base_url]: #method.base_url */ pub fn params(mut self, builder: F) -> Self - where F: Fn(RequestParams) -> RequestParams + where + F: Fn(RequestParams) -> RequestParams, { self.params = builder(self.params); @@ -188,15 +203,14 @@ impl SyncClientBuilder { [Client]: struct.Client.html */ pub fn build(self) -> Result { - let http = self.http.map(Ok) - .unwrap_or_else(|| SyncHttpClientBuilder::new().build()) - .map_err(error::build)?; + let http = self.http + .map(Ok) + .unwrap_or_else(|| SyncHttpClientBuilder::new().build()) + .map_err(error::build)?; Ok(SyncClient { - sender: SyncSender { - http: http - }, - params: self.params + sender: SyncSender { http: http }, + params: self.params, }) } } diff --git a/src/elastic/src/error.rs b/src/elastic/src/error.rs index 54b748a2b9..668c95d4c2 100644 --- a/src/elastic/src/error.rs +++ b/src/elastic/src/error.rs @@ -62,24 +62,22 @@ also contain a backtrace. */ #[derive(Debug)] pub enum Error { - /** An API error from Elasticsearch. */ - Api(ApiError), - /** Any other kind of error. */ - Client(ClientError) + /** An API error from Elasticsearch. */ Api(ApiError), + /** Any other kind of error. */ Client(ClientError), } impl StdError for Error { fn description(&self) -> &str { match *self { Error::Api(_) => "API error returned from Elasticsearch", - Error::Client(_) => "error sending a request or receiving a response" + Error::Client(_) => "error sending a request or receiving a response", } } fn cause(&self) -> Option<&StdError> { match *self { Error::Api(ref e) => Some(e), - Error::Client(ref e) => Some(e) + Error::Client(ref e) => Some(e), } } } @@ -88,7 +86,11 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Api(ref e) => write!(f, "API error returned from Elasticsearch. Caused by: {}", e), - Error::Client(ref e) => write!(f, "error sending a request or receiving a response. Caused by: {}", e) + Error::Client(ref e) => write!( + f, + "error sending a request or receiving a response. Caused by: {}", + e + ), } } } @@ -115,43 +117,46 @@ impl fmt::Display for ClientError { } } -pub(crate) fn build(err: E) -> Error - where E: StdError + Send + 'static +pub(crate) fn build(err: E) -> Error +where + E: StdError + Send + 'static, { Error::Client(ClientError { - inner: inner::Error::with_chain(err, inner::ErrorKind::Build) + inner: inner::Error::with_chain(err, inner::ErrorKind::Build), }) } -pub(crate) fn request(err: E) -> Error - where E: StdError + Send + 'static +pub(crate) fn request(err: E) -> Error +where + E: StdError + Send + 'static, { Error::Client(ClientError { - inner: inner::Error::with_chain(err, inner::ErrorKind::Request) + inner: inner::Error::with_chain(err, inner::ErrorKind::Request), }) } -pub(crate) fn response(status: u16, err: E) -> Error - where E: Into> + StdError + Send + 'static +pub(crate) fn response(status: u16, err: E) -> Error +where + E: Into> + StdError + Send + 'static, { match err.into() { MaybeApiError::Api(err) => Error::Api(err), MaybeApiError::Other(err) => Error::Client(ClientError { - inner: inner::Error::with_chain(err, inner::ErrorKind::Response(status)) - }) + inner: inner::Error::with_chain(err, inner::ErrorKind::Response(status)), + }), } } pub(crate) enum MaybeApiError { Api(ApiError), - Other(E) + Other(E), } impl Into> for ResponseError { fn into(self) -> MaybeApiError { match self { ResponseError::Api(err) => MaybeApiError::Api(err), - err => MaybeApiError::Other(err) + err => MaybeApiError::Other(err), } } } @@ -160,7 +165,7 @@ impl Into> for ResponseError { fn into(self) -> MaybeApiError { match self { ResponseError::Api(err) => MaybeApiError::Api(err), - err => MaybeApiError::Other(ElasticReqwestError::Response(err)) + err => MaybeApiError::Other(ElasticReqwestError::Response(err)), } } } @@ -169,7 +174,7 @@ impl Into> for ElasticReqwestError { fn into(self) -> MaybeApiError { match self { ElasticReqwestError::Response(err) => err.into(), - err => MaybeApiError::Other(err) + err => MaybeApiError::Other(err), } } } @@ -216,7 +221,7 @@ mod inner { #[cfg(test)] mod tests { use super::*; - use ::tests::*; + use tests::*; #[test] fn error_is_send_sync() { diff --git a/src/elastic/src/lib.rs b/src/elastic/src/lib.rs index ec61c19348..43bcf89eb5 100644 --- a/src/elastic/src/lib.rs +++ b/src/elastic/src/lib.rs @@ -275,19 +275,19 @@ This crate glues these libraries together with some simple assumptions about how #![deny(warnings, missing_docs)] #![allow(unknown_lints, doc_markdown)] -#[macro_use] -extern crate log; -extern crate uuid; +extern crate elastic_reqwest; +extern crate elastic_types; #[macro_use] extern crate error_chain; -extern crate serde; -extern crate serde_json; -extern crate reqwest; extern crate futures; extern crate futures_cpupool; +#[macro_use] +extern crate log; +extern crate reqwest; +extern crate serde; +extern crate serde_json; extern crate tokio_core; -extern crate elastic_reqwest; -extern crate elastic_types; +extern crate uuid; pub mod error; pub use error::Error; diff --git a/src/elastic/src/types.rs b/src/elastic/src/types.rs index d4de9039f2..7acec8f503 100644 --- a/src/elastic/src/types.rs +++ b/src/elastic/src/types.rs @@ -265,7 +265,7 @@ Serialising `MyType`s mapping will produce the following json: [geoshape-mod]: geo/shape/index.html */ -pub use elastic_types::{document, boolean, date, geo, ip, number, string, prelude}; +pub use elastic_types::{boolean, date, document, geo, ip, number, prelude, string}; #[doc(hidden)] pub use elastic_types::derive; diff --git a/src/elastic_derive/src/lib.rs b/src/elastic_derive/src/lib.rs index 80998c9ca8..193014a951 100644 --- a/src/elastic_derive/src/lib.rs +++ b/src/elastic_derive/src/lib.rs @@ -8,12 +8,12 @@ This crate provides custom `derive` attributes for data types in the [`elastic`] extern crate proc_macro; -extern crate syn; +extern crate elastic_types_derive_internals as internals; #[macro_use] extern crate quote; -extern crate elastic_types_derive_internals as internals; +extern crate syn; -use internals::{elastic_type, date_format}; +use internals::{date_format, elastic_type}; #[proc_macro_derive(ElasticType, attributes(elastic))] pub fn derive_elastic_type(input: proc_macro::TokenStream) -> proc_macro::TokenStream { @@ -25,8 +25,8 @@ pub fn derive_elastic_type(input: proc_macro::TokenStream) -> proc_macro::TokenS expanded.append_all(genned); expanded.to_string().parse().unwrap() - }, - Err(e) => panic!("{}", e) + } + Err(e) => panic!("{}", e), } } @@ -40,7 +40,7 @@ pub fn derive_date_format(input: proc_macro::TokenStream) -> proc_macro::TokenSt expanded.append_all(genned); expanded.to_string().parse().unwrap() - }, - Err(e) => panic!("{}", e) + } + Err(e) => panic!("{}", e), } } diff --git a/src/requests/benches/mod.rs b/src/requests/benches/mod.rs index 1627308e77..64323f49e0 100644 --- a/src/requests/benches/mod.rs +++ b/src/requests/benches/mod.rs @@ -1,27 +1,27 @@ #![feature(test)] -extern crate test; extern crate elastic_requests; +extern crate test; use test::Bencher; use elastic_requests::*; #[bench] fn new_req(b: &mut Bencher) { - b.iter(|| { - let req = SearchRequest::for_index_ty("test_index", "test_ty", "{'query': { 'match_all': {}}}"); + b.iter(|| { + let req = SearchRequest::for_index_ty("test_index", "test_ty", "{'query': { 'match_all': {}}}"); - test::black_box(req) - }); + test::black_box(req) + }); } #[bench] fn owned_req_into_http_req(b: &mut Bencher) { - b.iter(|| { - let req = SearchRequest::for_index_ty("test_index", "test_ty", "{'query': { 'match_all': {}}}"); + b.iter(|| { + let req = SearchRequest::for_index_ty("test_index", "test_ty", "{'query': { 'match_all': {}}}"); - let http_req: HttpRequest<_> = (req).into(); + let http_req: HttpRequest<_> = (req).into(); - test::black_box(http_req) - }); -} \ No newline at end of file + test::black_box(http_req) + }); +} diff --git a/src/requests/src/genned.rs b/src/requests/src/genned.rs index 3bafdb8e4b..984b1720d8 100644 --- a/src/requests/src/genned.rs +++ b/src/requests/src/genned.rs @@ -1,10 +1,10 @@ // This code is automatically generated // pub mod endpoints { - use super :: http :: * ; - use super :: params :: * ; + use super::http::*; + use super::params::*; - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesCloseUrlParams<'a> { Index(Index<'a>), } @@ -21,14 +21,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesCloseRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IndicesCloseRequest<'a, B> { pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesCloseRequest { url: IndicesCloseUrlParams::Index(index.into()).url(), @@ -45,7 +46,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum DeleteScriptUrlParams<'a> { LangId(Lang<'a>, Id<'a>), } @@ -63,16 +64,19 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct DeleteScriptRequest<'a> { pub url: Url<'a>, } impl<'a> DeleteScriptRequest<'a> { pub fn for_lang_id(lang: ILang, id: IId) -> Self - where ILang: Into>, - IId: Into> + where + ILang: Into>, + IId: Into>, { - DeleteScriptRequest { url: DeleteScriptUrlParams::LangId(lang.into(), id.into()).url() } + DeleteScriptRequest { + url: DeleteScriptUrlParams::LangId(lang.into(), id.into()).url(), + } } } impl<'a> Into> for DeleteScriptRequest<'a> { @@ -84,7 +88,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum TermvectorsUrlParams<'a> { IndexType(Index<'a>, Type<'a>), IndexTypeId(Index<'a>, Type<'a>, Id<'a>), @@ -102,8 +106,7 @@ pub mod endpoints { Url::from(url) } TermvectorsUrlParams::IndexTypeId(ref index, ref ty, ref id) => { - let mut url = String::with_capacity(16usize + index.len() + ty.len() + - id.len()); + let mut url = String::with_capacity(16usize + index.len() + ty.len() + id.len()); url.push_str("/"); url.push_str(index.as_ref()); url.push_str("/"); @@ -116,29 +119,27 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct TermvectorsRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> TermvectorsRequest<'a, B> { pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { TermvectorsRequest { url: TermvectorsUrlParams::IndexType(index.into(), ty.into()).url(), body: body, } } - pub fn for_index_ty_id(index: IIndex, - ty: IType, - id: IId, - body: B) - -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId, body: B) -> Self + where + IIndex: Into>, + IType: Into>, + IId: Into>, { TermvectorsRequest { url: TermvectorsUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -155,7 +156,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum FieldStatsUrlParams<'a> { None, Index(Index<'a>), @@ -174,7 +175,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct FieldStatsRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -187,7 +188,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { FieldStatsRequest { url: FieldStatsUrlParams::Index(index.into()).url(), @@ -204,7 +206,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatThreadPoolUrlParams<'a> { None, ThreadPoolPatterns(ThreadPoolPatterns<'a>), @@ -222,14 +224,20 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatThreadPoolRequest<'a> { pub url: Url<'a>, } impl<'a> CatThreadPoolRequest<'a> { pub fn new() -> Self { - CatThreadPoolRequest { url: CatThreadPoolUrlParams::None.url() } - } pub fn for_thread_pool_patterns < IThreadPoolPatterns > ( thread_pool_patterns : IThreadPoolPatterns ) -> Self where IThreadPoolPatterns : Into < ThreadPoolPatterns < 'a > > { + CatThreadPoolRequest { + url: CatThreadPoolUrlParams::None.url(), + } + } + pub fn for_thread_pool_patterns(thread_pool_patterns: IThreadPoolPatterns) -> Self + where + IThreadPoolPatterns: Into>, + { CatThreadPoolRequest { url: CatThreadPoolUrlParams::ThreadPoolPatterns(thread_pool_patterns.into()).url(), } @@ -244,7 +252,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SnapshotDeleteUrlParams<'a> { RepositorySnapshot(Repository<'a>, Snapshot<'a>), } @@ -252,8 +260,7 @@ pub mod endpoints { pub fn url(self) -> Url<'a> { match self { SnapshotDeleteUrlParams::RepositorySnapshot(ref repository, ref snapshot) => { - let mut url = String::with_capacity(12usize + repository.len() + - snapshot.len()); + let mut url = String::with_capacity(12usize + repository.len() + snapshot.len()); url.push_str("/_snapshot/"); url.push_str(repository.as_ref()); url.push_str("/"); @@ -263,21 +270,18 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SnapshotDeleteRequest<'a> { pub url: Url<'a>, } impl<'a> SnapshotDeleteRequest<'a> { - pub fn for_repository_snapshot(repository: IRepository, - snapshot: ISnapshot) - -> Self - where IRepository: Into>, - ISnapshot: Into> + pub fn for_repository_snapshot(repository: IRepository, snapshot: ISnapshot) -> Self + where + IRepository: Into>, + ISnapshot: Into>, { SnapshotDeleteRequest { - url: SnapshotDeleteUrlParams::RepositorySnapshot(repository.into(), - snapshot.into()) - .url(), + url: SnapshotDeleteUrlParams::RepositorySnapshot(repository.into(), snapshot.into()).url(), } } } @@ -290,7 +294,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesGetSettingsUrlParams<'a> { None, Index(Index<'a>), @@ -325,33 +329,40 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesGetSettingsRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesGetSettingsRequest<'a> { pub fn new() -> Self { - IndicesGetSettingsRequest { url: IndicesGetSettingsUrlParams::None.url() } + IndicesGetSettingsRequest { + url: IndicesGetSettingsUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesGetSettingsRequest { url: IndicesGetSettingsUrlParams::Index(index.into()).url(), } } pub fn for_index_name(index: IIndex, name: IName) -> Self - where IIndex: Into>, - IName: Into> + where + IIndex: Into>, + IName: Into>, { IndicesGetSettingsRequest { url: IndicesGetSettingsUrlParams::IndexName(index.into(), name.into()).url(), } } pub fn for_name(name: IName) -> Self - where IName: Into> + where + IName: Into>, { - IndicesGetSettingsRequest { url: IndicesGetSettingsUrlParams::Name(name.into()).url() } + IndicesGetSettingsRequest { + url: IndicesGetSettingsUrlParams::Name(name.into()).url(), + } } } impl<'a> Into> for IndicesGetSettingsRequest<'a> { @@ -363,7 +374,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CreateUrlParams<'a> { IndexTypeId(Index<'a>, Type<'a>, Id<'a>), } @@ -371,8 +382,7 @@ pub mod endpoints { pub fn url(self) -> Url<'a> { match self { CreateUrlParams::IndexTypeId(ref index, ref ty, ref id) => { - let mut url = String::with_capacity(11usize + index.len() + ty.len() + - id.len()); + let mut url = String::with_capacity(11usize + index.len() + ty.len() + id.len()); url.push_str("/"); url.push_str(index.as_ref()); url.push_str("/"); @@ -385,20 +395,17 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CreateRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> CreateRequest<'a, B> { - pub fn for_index_ty_id(index: IIndex, - ty: IType, - id: IId, - body: B) - -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId, body: B) -> Self + where + IIndex: Into>, + IType: Into>, + IId: Into>, { CreateRequest { url: CreateUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -415,7 +422,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SnapshotDeleteRepositoryUrlParams<'a> { Repository(Repository<'a>), } @@ -431,13 +438,14 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SnapshotDeleteRepositoryRequest<'a> { pub url: Url<'a>, } impl<'a> SnapshotDeleteRepositoryRequest<'a> { pub fn for_repository(repository: IRepository) -> Self - where IRepository: Into> + where + IRepository: Into>, { SnapshotDeleteRepositoryRequest { url: SnapshotDeleteRepositoryUrlParams::Repository(repository.into()).url(), @@ -453,7 +461,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ClusterAllocationExplainUrlParams { None, } @@ -464,7 +472,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ClusterAllocationExplainRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -486,7 +494,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesPutTemplateUrlParams<'a> { Name(Name<'a>), } @@ -502,14 +510,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesPutTemplateRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IndicesPutTemplateRequest<'a, B> { pub fn for_name(name: IName, body: B) -> Self - where IName: Into> + where + IName: Into>, { IndicesPutTemplateRequest { url: IndicesPutTemplateUrlParams::Name(name.into()).url(), @@ -526,7 +535,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesGetTemplateUrlParams<'a> { None, Name(Name<'a>), @@ -544,18 +553,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesGetTemplateRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesGetTemplateRequest<'a> { pub fn new() -> Self { - IndicesGetTemplateRequest { url: IndicesGetTemplateUrlParams::None.url() } + IndicesGetTemplateRequest { + url: IndicesGetTemplateUrlParams::None.url(), + } } pub fn for_name(name: IName) -> Self - where IName: Into> + where + IName: Into>, { - IndicesGetTemplateRequest { url: IndicesGetTemplateUrlParams::Name(name.into()).url() } + IndicesGetTemplateRequest { + url: IndicesGetTemplateUrlParams::Name(name.into()).url(), + } } } impl<'a> Into> for IndicesGetTemplateRequest<'a> { @@ -567,7 +581,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ClusterStateUrlParams<'a> { None, Metric(Metric<'a>), @@ -594,22 +608,28 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ClusterStateRequest<'a> { pub url: Url<'a>, } impl<'a> ClusterStateRequest<'a> { pub fn new() -> Self { - ClusterStateRequest { url: ClusterStateUrlParams::None.url() } + ClusterStateRequest { + url: ClusterStateUrlParams::None.url(), + } } pub fn for_metric(metric: IMetric) -> Self - where IMetric: Into> + where + IMetric: Into>, { - ClusterStateRequest { url: ClusterStateUrlParams::Metric(metric.into()).url() } + ClusterStateRequest { + url: ClusterStateUrlParams::Metric(metric.into()).url(), + } } pub fn for_metric_index(metric: IMetric, index: IIndex) -> Self - where IMetric: Into>, - IIndex: Into> + where + IMetric: Into>, + IIndex: Into>, { ClusterStateRequest { url: ClusterStateUrlParams::MetricIndex(metric.into(), index.into()).url(), @@ -625,7 +645,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum MsearchTemplateUrlParams<'a> { None, Index(Index<'a>), @@ -654,7 +674,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct MsearchTemplateRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -667,7 +687,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { MsearchTemplateRequest { url: MsearchTemplateUrlParams::Index(index.into()).url(), @@ -675,8 +696,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { MsearchTemplateRequest { url: MsearchTemplateUrlParams::IndexType(index.into(), ty.into()).url(), @@ -693,7 +715,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum BulkUrlParams<'a> { None, Index(Index<'a>), @@ -722,7 +744,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct BulkRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -735,7 +757,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { BulkRequest { url: BulkUrlParams::Index(index.into()).url(), @@ -743,8 +766,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { BulkRequest { url: BulkUrlParams::IndexType(index.into(), ty.into()).url(), @@ -761,7 +785,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ExplainUrlParams<'a> { IndexTypeId(Index<'a>, Type<'a>, Id<'a>), } @@ -769,8 +793,7 @@ pub mod endpoints { pub fn url(self) -> Url<'a> { match self { ExplainUrlParams::IndexTypeId(ref index, ref ty, ref id) => { - let mut url = String::with_capacity(12usize + index.len() + ty.len() + - id.len()); + let mut url = String::with_capacity(12usize + index.len() + ty.len() + id.len()); url.push_str("/"); url.push_str(index.as_ref()); url.push_str("/"); @@ -783,20 +806,17 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ExplainRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> ExplainRequest<'a, B> { - pub fn for_index_ty_id(index: IIndex, - ty: IType, - id: IId, - body: B) - -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId, body: B) -> Self + where + IIndex: Into>, + IType: Into>, + IId: Into>, { ExplainRequest { url: ExplainUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -813,7 +833,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SuggestUrlParams<'a> { None, Index(Index<'a>), @@ -832,7 +852,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SuggestRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -845,7 +865,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { SuggestRequest { url: SuggestUrlParams::Index(index.into()).url(), @@ -862,7 +883,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SnapshotGetRepositoryUrlParams<'a> { None, Repository(Repository<'a>), @@ -880,16 +901,19 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SnapshotGetRepositoryRequest<'a> { pub url: Url<'a>, } impl<'a> SnapshotGetRepositoryRequest<'a> { pub fn new() -> Self { - SnapshotGetRepositoryRequest { url: SnapshotGetRepositoryUrlParams::None.url() } + SnapshotGetRepositoryRequest { + url: SnapshotGetRepositoryUrlParams::None.url(), + } } pub fn for_repository(repository: IRepository) -> Self - where IRepository: Into> + where + IRepository: Into>, { SnapshotGetRepositoryRequest { url: SnapshotGetRepositoryUrlParams::Repository(repository.into()).url(), @@ -905,7 +929,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum RenderSearchTemplateUrlParams<'a> { None, Id(Id<'a>), @@ -923,7 +947,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct RenderSearchTemplateRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -936,7 +960,8 @@ pub mod endpoints { } } pub fn for_id(id: IId, body: B) -> Self - where IId: Into> + where + IId: Into>, { RenderSearchTemplateRequest { url: RenderSearchTemplateUrlParams::Id(id.into()).url(), @@ -953,7 +978,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesStatsUrlParams<'a> { None, Index(Index<'a>), @@ -988,31 +1013,40 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesStatsRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesStatsRequest<'a> { pub fn new() -> Self { - IndicesStatsRequest { url: IndicesStatsUrlParams::None.url() } + IndicesStatsRequest { + url: IndicesStatsUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - IndicesStatsRequest { url: IndicesStatsUrlParams::Index(index.into()).url() } + IndicesStatsRequest { + url: IndicesStatsUrlParams::Index(index.into()).url(), + } } pub fn for_index_metric(index: IIndex, metric: IMetric) -> Self - where IIndex: Into>, - IMetric: Into> + where + IIndex: Into>, + IMetric: Into>, { IndicesStatsRequest { url: IndicesStatsUrlParams::IndexMetric(index.into(), metric.into()).url(), } } pub fn for_metric(metric: IMetric) -> Self - where IMetric: Into> + where + IMetric: Into>, { - IndicesStatsRequest { url: IndicesStatsUrlParams::Metric(metric.into()).url() } + IndicesStatsRequest { + url: IndicesStatsUrlParams::Metric(metric.into()).url(), + } } } impl<'a> Into> for IndicesStatsRequest<'a> { @@ -1024,7 +1058,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatRepositoriesUrlParams { None, } @@ -1035,13 +1069,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatRepositoriesRequest<'a> { pub url: Url<'a>, } impl<'a> CatRepositoriesRequest<'a> { pub fn new() -> Self { - CatRepositoriesRequest { url: CatRepositoriesUrlParams::None.url() } + CatRepositoriesRequest { + url: CatRepositoriesUrlParams::None.url(), + } } } impl<'a> Into> for CatRepositoriesRequest<'a> { @@ -1053,7 +1089,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesForcemergeUrlParams<'a> { None, Index(Index<'a>), @@ -1072,7 +1108,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesForcemergeRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -1085,7 +1121,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesForcemergeRequest { url: IndicesForcemergeUrlParams::Index(index.into()).url(), @@ -1102,7 +1139,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum PingUrlParams { None, } @@ -1113,13 +1150,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct PingRequest<'a> { pub url: Url<'a>, } impl<'a> PingRequest<'a> { pub fn new() -> Self { - PingRequest { url: PingUrlParams::None.url() } + PingRequest { + url: PingUrlParams::None.url(), + } } } impl<'a> Into> for PingRequest<'a> { @@ -1131,7 +1170,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum PingHeadUrlParams { None, } @@ -1142,13 +1181,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct PingHeadRequest<'a> { pub url: Url<'a>, } impl<'a> PingHeadRequest<'a> { pub fn new() -> Self { - PingHeadRequest { url: PingHeadUrlParams::None.url() } + PingHeadRequest { + url: PingHeadUrlParams::None.url(), + } } } impl<'a> Into> for PingHeadRequest<'a> { @@ -1160,7 +1201,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum TasksGetUrlParams<'a> { TaskId(TaskId<'a>), } @@ -1176,15 +1217,18 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct TasksGetRequest<'a> { pub url: Url<'a>, } impl<'a> TasksGetRequest<'a> { pub fn for_task_id(task_id: ITaskId) -> Self - where ITaskId: Into> + where + ITaskId: Into>, { - TasksGetRequest { url: TasksGetUrlParams::TaskId(task_id.into()).url() } + TasksGetRequest { + url: TasksGetUrlParams::TaskId(task_id.into()).url(), + } } } impl<'a> Into> for TasksGetRequest<'a> { @@ -1196,7 +1240,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesExistsUrlParams<'a> { Index(Index<'a>), } @@ -1212,15 +1256,18 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesExistsRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesExistsRequest<'a> { pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - IndicesExistsRequest { url: IndicesExistsUrlParams::Index(index.into()).url() } + IndicesExistsRequest { + url: IndicesExistsUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for IndicesExistsRequest<'a> { @@ -1232,7 +1279,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesFlushSyncedUrlParams<'a> { None, Index(Index<'a>), @@ -1251,7 +1298,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesFlushSyncedRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -1264,7 +1311,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesFlushSyncedRequest { url: IndicesFlushSyncedUrlParams::Index(index.into()).url(), @@ -1281,7 +1329,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum MsearchUrlParams<'a> { None, Index(Index<'a>), @@ -1310,7 +1358,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct MsearchRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -1323,7 +1371,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { MsearchRequest { url: MsearchUrlParams::Index(index.into()).url(), @@ -1331,8 +1380,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { MsearchRequest { url: MsearchUrlParams::IndexType(index.into(), ty.into()).url(), @@ -1349,7 +1399,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum InfoUrlParams { None, } @@ -1360,13 +1410,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct InfoRequest<'a> { pub url: Url<'a>, } impl<'a> InfoRequest<'a> { pub fn new() -> Self { - InfoRequest { url: InfoUrlParams::None.url() } + InfoRequest { + url: InfoUrlParams::None.url(), + } } } impl<'a> Into> for InfoRequest<'a> { @@ -1378,7 +1430,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SearchTemplateUrlParams<'a> { None, Index(Index<'a>), @@ -1407,7 +1459,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SearchTemplateRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -1420,7 +1472,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { SearchTemplateRequest { url: SearchTemplateUrlParams::Index(index.into()).url(), @@ -1428,8 +1481,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { SearchTemplateRequest { url: SearchTemplateUrlParams::IndexType(index.into(), ty.into()).url(), @@ -1446,7 +1500,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesDeleteUrlParams<'a> { Index(Index<'a>), } @@ -1462,15 +1516,18 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesDeleteRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesDeleteRequest<'a> { pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - IndicesDeleteRequest { url: IndicesDeleteUrlParams::Index(index.into()).url() } + IndicesDeleteRequest { + url: IndicesDeleteUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for IndicesDeleteRequest<'a> { @@ -1482,7 +1539,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum DeleteByQueryUrlParams<'a> { Index(Index<'a>), IndexType(Index<'a>, Type<'a>), @@ -1509,14 +1566,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct DeleteByQueryRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> DeleteByQueryRequest<'a, B> { pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { DeleteByQueryRequest { url: DeleteByQueryUrlParams::Index(index.into()).url(), @@ -1524,8 +1582,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { DeleteByQueryRequest { url: DeleteByQueryUrlParams::IndexType(index.into(), ty.into()).url(), @@ -1542,7 +1601,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum DeleteTemplateUrlParams<'a> { Id(Id<'a>), } @@ -1558,15 +1617,18 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct DeleteTemplateRequest<'a> { pub url: Url<'a>, } impl<'a> DeleteTemplateRequest<'a> { pub fn for_id(id: IId) -> Self - where IId: Into> + where + IId: Into>, { - DeleteTemplateRequest { url: DeleteTemplateUrlParams::Id(id.into()).url() } + DeleteTemplateRequest { + url: DeleteTemplateUrlParams::Id(id.into()).url(), + } } } impl<'a> Into> for DeleteTemplateRequest<'a> { @@ -1578,7 +1640,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesCreateUrlParams<'a> { Index(Index<'a>), } @@ -1594,14 +1656,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesCreateRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IndicesCreateRequest<'a, B> { pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesCreateRequest { url: IndicesCreateUrlParams::Index(index.into()).url(), @@ -1618,7 +1681,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum PercolateUrlParams<'a> { IndexType(Index<'a>, Type<'a>), IndexTypeId(Index<'a>, Type<'a>, Id<'a>), @@ -1636,8 +1699,7 @@ pub mod endpoints { Url::from(url) } PercolateUrlParams::IndexTypeId(ref index, ref ty, ref id) => { - let mut url = String::with_capacity(14usize + index.len() + ty.len() + - id.len()); + let mut url = String::with_capacity(14usize + index.len() + ty.len() + id.len()); url.push_str("/"); url.push_str(index.as_ref()); url.push_str("/"); @@ -1650,29 +1712,27 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct PercolateRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> PercolateRequest<'a, B> { pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { PercolateRequest { url: PercolateUrlParams::IndexType(index.into(), ty.into()).url(), body: body, } } - pub fn for_index_ty_id(index: IIndex, - ty: IType, - id: IId, - body: B) - -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId, body: B) -> Self + where + IIndex: Into>, + IType: Into>, + IId: Into>, { PercolateRequest { url: PercolateUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -1689,7 +1749,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SimpleSearchUrlParams<'a> { None, Index(Index<'a>), @@ -1718,22 +1778,28 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SimpleSearchRequest<'a> { pub url: Url<'a>, } impl<'a> SimpleSearchRequest<'a> { pub fn new() -> Self { - SimpleSearchRequest { url: SimpleSearchUrlParams::None.url() } + SimpleSearchRequest { + url: SimpleSearchUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - SimpleSearchRequest { url: SimpleSearchUrlParams::Index(index.into()).url() } + SimpleSearchRequest { + url: SimpleSearchUrlParams::Index(index.into()).url(), + } } pub fn for_index_ty(index: IIndex, ty: IType) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { SimpleSearchRequest { url: SimpleSearchUrlParams::IndexType(index.into(), ty.into()).url(), @@ -1749,7 +1815,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SearchUrlParams<'a> { None, Index(Index<'a>), @@ -1778,7 +1844,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SearchRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -1791,7 +1857,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { SearchRequest { url: SearchUrlParams::Index(index.into()).url(), @@ -1799,8 +1866,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { SearchRequest { url: SearchUrlParams::IndexType(index.into(), ty.into()).url(), @@ -1817,7 +1885,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatNodeattrsUrlParams { None, } @@ -1828,13 +1896,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatNodeattrsRequest<'a> { pub url: Url<'a>, } impl<'a> CatNodeattrsRequest<'a> { pub fn new() -> Self { - CatNodeattrsRequest { url: CatNodeattrsUrlParams::None.url() } + CatNodeattrsRequest { + url: CatNodeattrsUrlParams::None.url(), + } } } impl<'a> Into> for CatNodeattrsRequest<'a> { @@ -1846,7 +1916,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SnapshotVerifyRepositoryUrlParams<'a> { Repository(Repository<'a>), } @@ -1863,14 +1933,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SnapshotVerifyRepositoryRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> SnapshotVerifyRepositoryRequest<'a, B> { pub fn for_repository(repository: IRepository, body: B) -> Self - where IRepository: Into> + where + IRepository: Into>, { SnapshotVerifyRepositoryRequest { url: SnapshotVerifyRepositoryUrlParams::Repository(repository.into()).url(), @@ -1887,7 +1958,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CountUrlParams<'a> { None, Index(Index<'a>), @@ -1916,7 +1987,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CountRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -1929,7 +2000,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { CountRequest { url: CountUrlParams::Index(index.into()).url(), @@ -1937,8 +2009,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { CountRequest { url: CountUrlParams::IndexType(index.into(), ty.into()).url(), @@ -1955,7 +2028,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatAllocationUrlParams<'a> { None, NodeId(NodeId<'a>), @@ -1973,18 +2046,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatAllocationRequest<'a> { pub url: Url<'a>, } impl<'a> CatAllocationRequest<'a> { pub fn new() -> Self { - CatAllocationRequest { url: CatAllocationUrlParams::None.url() } + CatAllocationRequest { + url: CatAllocationUrlParams::None.url(), + } } pub fn for_node_id(node_id: INodeId) -> Self - where INodeId: Into> + where + INodeId: Into>, { - CatAllocationRequest { url: CatAllocationUrlParams::NodeId(node_id.into()).url() } + CatAllocationRequest { + url: CatAllocationUrlParams::NodeId(node_id.into()).url(), + } } } impl<'a> Into> for CatAllocationRequest<'a> { @@ -1996,7 +2074,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesFlushUrlParams<'a> { None, Index(Index<'a>), @@ -2015,7 +2093,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesFlushRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -2028,7 +2106,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesFlushRequest { url: IndicesFlushUrlParams::Index(index.into()).url(), @@ -2045,7 +2124,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesRefreshUrlParams<'a> { None, Index(Index<'a>), @@ -2064,7 +2143,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesRefreshRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -2077,7 +2156,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesRefreshRequest { url: IndicesRefreshUrlParams::Index(index.into()).url(), @@ -2094,7 +2174,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatHelpUrlParams { None, } @@ -2105,13 +2185,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatHelpRequest<'a> { pub url: Url<'a>, } impl<'a> CatHelpRequest<'a> { pub fn new() -> Self { - CatHelpRequest { url: CatHelpUrlParams::None.url() } + CatHelpRequest { + url: CatHelpUrlParams::None.url(), + } } } impl<'a> Into> for CatHelpRequest<'a> { @@ -2123,7 +2205,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SearchShardsUrlParams<'a> { None, Index(Index<'a>), @@ -2142,7 +2224,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SearchShardsRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -2155,7 +2237,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { SearchShardsRequest { url: SearchShardsUrlParams::Index(index.into()).url(), @@ -2172,7 +2255,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ClusterHealthUrlParams<'a> { None, Index(Index<'a>), @@ -2190,18 +2273,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ClusterHealthRequest<'a> { pub url: Url<'a>, } impl<'a> ClusterHealthRequest<'a> { pub fn new() -> Self { - ClusterHealthRequest { url: ClusterHealthUrlParams::None.url() } + ClusterHealthRequest { + url: ClusterHealthUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - ClusterHealthRequest { url: ClusterHealthUrlParams::Index(index.into()).url() } + ClusterHealthRequest { + url: ClusterHealthUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for ClusterHealthRequest<'a> { @@ -2213,7 +2301,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesExistsAliasUrlParams<'a> { Index(Index<'a>), IndexName(Index<'a>, Name<'a>), @@ -2246,30 +2334,35 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesExistsAliasRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesExistsAliasRequest<'a> { pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesExistsAliasRequest { url: IndicesExistsAliasUrlParams::Index(index.into()).url(), } } pub fn for_index_name(index: IIndex, name: IName) -> Self - where IIndex: Into>, - IName: Into> + where + IIndex: Into>, + IName: Into>, { IndicesExistsAliasRequest { url: IndicesExistsAliasUrlParams::IndexName(index.into(), name.into()).url(), } } pub fn for_name(name: IName) -> Self - where IName: Into> + where + IName: Into>, { - IndicesExistsAliasRequest { url: IndicesExistsAliasUrlParams::Name(name.into()).url() } + IndicesExistsAliasRequest { + url: IndicesExistsAliasUrlParams::Name(name.into()).url(), + } } } impl<'a> Into> for IndicesExistsAliasRequest<'a> { @@ -2281,7 +2374,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesGetFieldMappingUrlParams<'a> { Fields(Fields<'a>), IndexFields(Index<'a>, Fields<'a>), @@ -2306,8 +2399,7 @@ pub mod endpoints { Url::from(url) } IndicesGetFieldMappingUrlParams::IndexTypeFields(ref index, ref ty, ref fields) => { - let mut url = String::with_capacity(18usize + index.len() + ty.len() + - fields.len()); + let mut url = String::with_capacity(18usize + index.len() + ty.len() + fields.len()); url.push_str("/"); url.push_str(index.as_ref()); url.push_str("/_mapping/"); @@ -2327,45 +2419,42 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesGetFieldMappingRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesGetFieldMappingRequest<'a> { pub fn for_fields(fields: IFields) -> Self - where IFields: Into> + where + IFields: Into>, { IndicesGetFieldMappingRequest { url: IndicesGetFieldMappingUrlParams::Fields(fields.into()).url(), } } pub fn for_index_fields(index: IIndex, fields: IFields) -> Self - where IIndex: Into>, - IFields: Into> + where + IIndex: Into>, + IFields: Into>, { IndicesGetFieldMappingRequest { - url: IndicesGetFieldMappingUrlParams::IndexFields(index.into(), fields.into()) - .url(), + url: IndicesGetFieldMappingUrlParams::IndexFields(index.into(), fields.into()).url(), } } - pub fn for_index_ty_fields(index: IIndex, - ty: IType, - fields: IFields) - -> Self - where IIndex: Into>, - IType: Into>, - IFields: Into> + pub fn for_index_ty_fields(index: IIndex, ty: IType, fields: IFields) -> Self + where + IIndex: Into>, + IType: Into>, + IFields: Into>, { IndicesGetFieldMappingRequest { - url: IndicesGetFieldMappingUrlParams::IndexTypeFields(index.into(), - ty.into(), - fields.into()) - .url(), + url: IndicesGetFieldMappingUrlParams::IndexTypeFields(index.into(), ty.into(), fields.into()).url(), } } pub fn for_ty_fields(ty: IType, fields: IFields) -> Self - where IType: Into>, - IFields: Into> + where + IType: Into>, + IFields: Into>, { IndicesGetFieldMappingRequest { url: IndicesGetFieldMappingUrlParams::TypeFields(ty.into(), fields.into()).url(), @@ -2381,7 +2470,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IngestPutPipelineUrlParams<'a> { Id(Id<'a>), } @@ -2397,14 +2486,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IngestPutPipelineRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IngestPutPipelineRequest<'a, B> { pub fn for_id(id: IId, body: B) -> Self - where IId: Into> + where + IId: Into>, { IngestPutPipelineRequest { url: IngestPutPipelineUrlParams::Id(id.into()).url(), @@ -2421,7 +2511,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ClusterPendingTasksUrlParams { None, } @@ -2432,13 +2522,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ClusterPendingTasksRequest<'a> { pub url: Url<'a>, } impl<'a> ClusterPendingTasksRequest<'a> { pub fn new() -> Self { - ClusterPendingTasksRequest { url: ClusterPendingTasksUrlParams::None.url() } + ClusterPendingTasksRequest { + url: ClusterPendingTasksUrlParams::None.url(), + } } } impl<'a> Into> for ClusterPendingTasksRequest<'a> { @@ -2450,7 +2542,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IngestSimulateUrlParams<'a> { None, Id(Id<'a>), @@ -2469,7 +2561,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IngestSimulateRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -2482,7 +2574,8 @@ pub mod endpoints { } } pub fn for_id(id: IId, body: B) -> Self - where IId: Into> + where + IId: Into>, { IngestSimulateRequest { url: IngestSimulateUrlParams::Id(id.into()).url(), @@ -2499,7 +2592,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesGetAliasUrlParams<'a> { None, Index(Index<'a>), @@ -2534,31 +2627,40 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesGetAliasRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesGetAliasRequest<'a> { pub fn new() -> Self { - IndicesGetAliasRequest { url: IndicesGetAliasUrlParams::None.url() } + IndicesGetAliasRequest { + url: IndicesGetAliasUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - IndicesGetAliasRequest { url: IndicesGetAliasUrlParams::Index(index.into()).url() } + IndicesGetAliasRequest { + url: IndicesGetAliasUrlParams::Index(index.into()).url(), + } } pub fn for_index_name(index: IIndex, name: IName) -> Self - where IIndex: Into>, - IName: Into> + where + IIndex: Into>, + IName: Into>, { IndicesGetAliasRequest { url: IndicesGetAliasUrlParams::IndexName(index.into(), name.into()).url(), } } pub fn for_name(name: IName) -> Self - where IName: Into> + where + IName: Into>, { - IndicesGetAliasRequest { url: IndicesGetAliasUrlParams::Name(name.into()).url() } + IndicesGetAliasRequest { + url: IndicesGetAliasUrlParams::Name(name.into()).url(), + } } } impl<'a> Into> for IndicesGetAliasRequest<'a> { @@ -2570,7 +2672,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum GetScriptUrlParams<'a> { LangId(Lang<'a>, Id<'a>), } @@ -2588,16 +2690,19 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct GetScriptRequest<'a> { pub url: Url<'a>, } impl<'a> GetScriptRequest<'a> { pub fn for_lang_id(lang: ILang, id: IId) -> Self - where ILang: Into>, - IId: Into> + where + ILang: Into>, + IId: Into>, { - GetScriptRequest { url: GetScriptUrlParams::LangId(lang.into(), id.into()).url() } + GetScriptRequest { + url: GetScriptUrlParams::LangId(lang.into(), id.into()).url(), + } } } impl<'a> Into> for GetScriptRequest<'a> { @@ -2609,7 +2714,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesRecoveryUrlParams<'a> { None, Index(Index<'a>), @@ -2628,18 +2733,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesRecoveryRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesRecoveryRequest<'a> { pub fn new() -> Self { - IndicesRecoveryRequest { url: IndicesRecoveryUrlParams::None.url() } + IndicesRecoveryRequest { + url: IndicesRecoveryUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - IndicesRecoveryRequest { url: IndicesRecoveryUrlParams::Index(index.into()).url() } + IndicesRecoveryRequest { + url: IndicesRecoveryUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for IndicesRecoveryRequest<'a> { @@ -2651,7 +2761,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IngestDeletePipelineUrlParams<'a> { Id(Id<'a>), } @@ -2667,15 +2777,18 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IngestDeletePipelineRequest<'a> { pub url: Url<'a>, } impl<'a> IngestDeletePipelineRequest<'a> { pub fn for_id(id: IId) -> Self - where IId: Into> + where + IId: Into>, { - IngestDeletePipelineRequest { url: IngestDeletePipelineUrlParams::Id(id.into()).url() } + IngestDeletePipelineRequest { + url: IngestDeletePipelineUrlParams::Id(id.into()).url(), + } } } impl<'a> Into> for IngestDeletePipelineRequest<'a> { @@ -2687,7 +2800,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum TasksCancelUrlParams<'a> { None, TaskId(TaskId<'a>), @@ -2706,7 +2819,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct TasksCancelRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -2719,7 +2832,8 @@ pub mod endpoints { } } pub fn for_task_id(task_id: ITaskId, body: B) -> Self - where ITaskId: Into> + where + ITaskId: Into>, { TasksCancelRequest { url: TasksCancelUrlParams::TaskId(task_id.into()).url(), @@ -2736,7 +2850,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesClearCacheUrlParams<'a> { None, Index(Index<'a>), @@ -2755,7 +2869,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesClearCacheRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -2768,7 +2882,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesClearCacheRequest { url: IndicesClearCacheUrlParams::Index(index.into()).url(), @@ -2785,7 +2900,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum DeleteUrlParams<'a> { IndexTypeId(Index<'a>, Type<'a>, Id<'a>), } @@ -2805,15 +2920,16 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct DeleteRequest<'a> { pub url: Url<'a>, } impl<'a> DeleteRequest<'a> { pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId) -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + where + IIndex: Into>, + IType: Into>, + IId: Into>, { DeleteRequest { url: DeleteUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -2829,7 +2945,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesPutMappingUrlParams<'a> { IndexType(Index<'a>, Type<'a>), Type(Type<'a>), @@ -2854,15 +2970,16 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesPutMappingRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IndicesPutMappingRequest<'a, B> { pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { IndicesPutMappingRequest { url: IndicesPutMappingUrlParams::IndexType(index.into(), ty.into()).url(), @@ -2870,7 +2987,8 @@ pub mod endpoints { } } pub fn for_ty(ty: IType, body: B) -> Self - where IType: Into> + where + IType: Into>, { IndicesPutMappingRequest { url: IndicesPutMappingUrlParams::Type(ty.into()).url(), @@ -2887,7 +3005,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatAliasesUrlParams<'a> { None, Name(Name<'a>), @@ -2905,18 +3023,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatAliasesRequest<'a> { pub url: Url<'a>, } impl<'a> CatAliasesRequest<'a> { pub fn new() -> Self { - CatAliasesRequest { url: CatAliasesUrlParams::None.url() } + CatAliasesRequest { + url: CatAliasesUrlParams::None.url(), + } } pub fn for_name(name: IName) -> Self - where IName: Into> + where + IName: Into>, { - CatAliasesRequest { url: CatAliasesUrlParams::Name(name.into()).url() } + CatAliasesRequest { + url: CatAliasesUrlParams::Name(name.into()).url(), + } } } impl<'a> Into> for CatAliasesRequest<'a> { @@ -2928,7 +3051,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ClusterStatsUrlParams<'a> { None, NodeId(NodeId<'a>), @@ -2946,18 +3069,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ClusterStatsRequest<'a> { pub url: Url<'a>, } impl<'a> ClusterStatsRequest<'a> { pub fn new() -> Self { - ClusterStatsRequest { url: ClusterStatsUrlParams::None.url() } + ClusterStatsRequest { + url: ClusterStatsUrlParams::None.url(), + } } pub fn for_node_id(node_id: INodeId) -> Self - where INodeId: Into> + where + INodeId: Into>, { - ClusterStatsRequest { url: ClusterStatsUrlParams::NodeId(node_id.into()).url() } + ClusterStatsRequest { + url: ClusterStatsUrlParams::NodeId(node_id.into()).url(), + } } } impl<'a> Into> for ClusterStatsRequest<'a> { @@ -2969,7 +3097,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesValidateQueryUrlParams<'a> { None, Index(Index<'a>), @@ -2998,7 +3126,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesValidateQueryRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -3011,7 +3139,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesValidateQueryRequest { url: IndicesValidateQueryUrlParams::Index(index.into()).url(), @@ -3019,8 +3148,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { IndicesValidateQueryRequest { url: IndicesValidateQueryUrlParams::IndexType(index.into(), ty.into()).url(), @@ -3037,7 +3167,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatPendingTasksUrlParams { None, } @@ -3048,13 +3178,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatPendingTasksRequest<'a> { pub url: Url<'a>, } impl<'a> CatPendingTasksRequest<'a> { pub fn new() -> Self { - CatPendingTasksRequest { url: CatPendingTasksUrlParams::None.url() } + CatPendingTasksRequest { + url: CatPendingTasksUrlParams::None.url(), + } } } impl<'a> Into> for CatPendingTasksRequest<'a> { @@ -3066,7 +3198,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ClearScrollUrlParams<'a> { None, ScrollId(ScrollId<'a>), @@ -3084,7 +3216,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ClearScrollRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -3097,7 +3229,8 @@ pub mod endpoints { } } pub fn for_scroll_id(scroll_id: IScrollId, body: B) -> Self - where IScrollId: Into> + where + IScrollId: Into>, { ClearScrollRequest { url: ClearScrollUrlParams::ScrollId(scroll_id.into()).url(), @@ -3114,7 +3247,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatShardsUrlParams<'a> { None, Index(Index<'a>), @@ -3132,18 +3265,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatShardsRequest<'a> { pub url: Url<'a>, } impl<'a> CatShardsRequest<'a> { pub fn new() -> Self { - CatShardsRequest { url: CatShardsUrlParams::None.url() } + CatShardsRequest { + url: CatShardsUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - CatShardsRequest { url: CatShardsUrlParams::Index(index.into()).url() } + CatShardsRequest { + url: CatShardsUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for CatShardsRequest<'a> { @@ -3155,7 +3293,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesShardStoresUrlParams<'a> { None, Index(Index<'a>), @@ -3174,16 +3312,19 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesShardStoresRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesShardStoresRequest<'a> { pub fn new() -> Self { - IndicesShardStoresRequest { url: IndicesShardStoresUrlParams::None.url() } + IndicesShardStoresRequest { + url: IndicesShardStoresUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesShardStoresRequest { url: IndicesShardStoresUrlParams::Index(index.into()).url(), @@ -3199,7 +3340,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesUpdateAliasesUrlParams { None, } @@ -3210,7 +3351,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesUpdateAliasesRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -3232,7 +3373,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatSegmentsUrlParams<'a> { None, Index(Index<'a>), @@ -3250,18 +3391,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatSegmentsRequest<'a> { pub url: Url<'a>, } impl<'a> CatSegmentsRequest<'a> { pub fn new() -> Self { - CatSegmentsRequest { url: CatSegmentsUrlParams::None.url() } + CatSegmentsRequest { + url: CatSegmentsUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - CatSegmentsRequest { url: CatSegmentsUrlParams::Index(index.into()).url() } + CatSegmentsRequest { + url: CatSegmentsUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for CatSegmentsRequest<'a> { @@ -3273,7 +3419,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum MpercolateUrlParams<'a> { None, Index(Index<'a>), @@ -3302,7 +3448,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct MpercolateRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -3315,7 +3461,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { MpercolateRequest { url: MpercolateUrlParams::Index(index.into()).url(), @@ -3323,8 +3470,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { MpercolateRequest { url: MpercolateUrlParams::IndexType(index.into(), ty.into()).url(), @@ -3341,7 +3489,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesOpenUrlParams<'a> { Index(Index<'a>), } @@ -3358,14 +3506,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesOpenRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IndicesOpenRequest<'a, B> { pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesOpenRequest { url: IndicesOpenUrlParams::Index(index.into()).url(), @@ -3382,7 +3531,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum GetUrlParams<'a> { IndexTypeId(Index<'a>, Type<'a>, Id<'a>), } @@ -3402,17 +3551,20 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct GetRequest<'a> { pub url: Url<'a>, } impl<'a> GetRequest<'a> { pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId) -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + where + IIndex: Into>, + IType: Into>, + IId: Into>, { - GetRequest { url: GetUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url() } + GetRequest { + url: GetUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), + } } } impl<'a> Into> for GetRequest<'a> { @@ -3424,7 +3576,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum UpdateByQueryUrlParams<'a> { Index(Index<'a>), IndexType(Index<'a>, Type<'a>), @@ -3451,14 +3603,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct UpdateByQueryRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> UpdateByQueryRequest<'a, B> { pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { UpdateByQueryRequest { url: UpdateByQueryUrlParams::Index(index.into()).url(), @@ -3466,8 +3619,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { UpdateByQueryRequest { url: UpdateByQueryUrlParams::IndexType(index.into(), ty.into()).url(), @@ -3484,7 +3638,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum MtermvectorsUrlParams<'a> { None, Index(Index<'a>), @@ -3513,7 +3667,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct MtermvectorsRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -3526,7 +3680,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { MtermvectorsRequest { url: MtermvectorsUrlParams::Index(index.into()).url(), @@ -3534,8 +3689,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { MtermvectorsRequest { url: MtermvectorsUrlParams::IndexType(index.into(), ty.into()).url(), @@ -3552,7 +3708,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatRecoveryUrlParams<'a> { None, Index(Index<'a>), @@ -3570,18 +3726,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatRecoveryRequest<'a> { pub url: Url<'a>, } impl<'a> CatRecoveryRequest<'a> { pub fn new() -> Self { - CatRecoveryRequest { url: CatRecoveryUrlParams::None.url() } + CatRecoveryRequest { + url: CatRecoveryUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - CatRecoveryRequest { url: CatRecoveryUrlParams::Index(index.into()).url() } + CatRecoveryRequest { + url: CatRecoveryUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for CatRecoveryRequest<'a> { @@ -3593,7 +3754,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SnapshotRestoreUrlParams<'a> { RepositorySnapshot(Repository<'a>, Snapshot<'a>), } @@ -3601,8 +3762,7 @@ pub mod endpoints { pub fn url(self) -> Url<'a> { match self { SnapshotRestoreUrlParams::RepositorySnapshot(ref repository, ref snapshot) => { - let mut url = String::with_capacity(21usize + repository.len() + - snapshot.len()); + let mut url = String::with_capacity(21usize + repository.len() + snapshot.len()); url.push_str("/_snapshot/"); url.push_str(repository.as_ref()); url.push_str("/"); @@ -3613,23 +3773,19 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SnapshotRestoreRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> SnapshotRestoreRequest<'a, B> { - pub fn for_repository_snapshot(repository: IRepository, - snapshot: ISnapshot, - body: B) - -> Self - where IRepository: Into>, - ISnapshot: Into> + pub fn for_repository_snapshot(repository: IRepository, snapshot: ISnapshot, body: B) -> Self + where + IRepository: Into>, + ISnapshot: Into>, { SnapshotRestoreRequest { - url: SnapshotRestoreUrlParams::RepositorySnapshot(repository.into(), - snapshot.into()) - .url(), + url: SnapshotRestoreUrlParams::RepositorySnapshot(repository.into(), snapshot.into()).url(), body: body, } } @@ -3643,7 +3799,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ReindexUrlParams { None, } @@ -3654,7 +3810,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ReindexRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -3676,7 +3832,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatHealthUrlParams { None, } @@ -3687,13 +3843,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatHealthRequest<'a> { pub url: Url<'a>, } impl<'a> CatHealthRequest<'a> { pub fn new() -> Self { - CatHealthRequest { url: CatHealthUrlParams::None.url() } + CatHealthRequest { + url: CatHealthUrlParams::None.url(), + } } } impl<'a> Into> for CatHealthRequest<'a> { @@ -3705,7 +3863,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatCountUrlParams<'a> { None, Index(Index<'a>), @@ -3723,18 +3881,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatCountRequest<'a> { pub url: Url<'a>, } impl<'a> CatCountRequest<'a> { pub fn new() -> Self { - CatCountRequest { url: CatCountUrlParams::None.url() } + CatCountRequest { + url: CatCountUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - CatCountRequest { url: CatCountUrlParams::Index(index.into()).url() } + CatCountRequest { + url: CatCountUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for CatCountRequest<'a> { @@ -3746,7 +3909,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatSnapshotsUrlParams<'a> { None, Repository(Repository<'a>), @@ -3764,18 +3927,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatSnapshotsRequest<'a> { pub url: Url<'a>, } impl<'a> CatSnapshotsRequest<'a> { pub fn new() -> Self { - CatSnapshotsRequest { url: CatSnapshotsUrlParams::None.url() } + CatSnapshotsRequest { + url: CatSnapshotsUrlParams::None.url(), + } } pub fn for_repository(repository: IRepository) -> Self - where IRepository: Into> + where + IRepository: Into>, { - CatSnapshotsRequest { url: CatSnapshotsUrlParams::Repository(repository.into()).url() } + CatSnapshotsRequest { + url: CatSnapshotsUrlParams::Repository(repository.into()).url(), + } } } impl<'a> Into> for CatSnapshotsRequest<'a> { @@ -3787,7 +3955,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesGetMappingUrlParams<'a> { None, Index(Index<'a>), @@ -3822,31 +3990,40 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesGetMappingRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesGetMappingRequest<'a> { pub fn new() -> Self { - IndicesGetMappingRequest { url: IndicesGetMappingUrlParams::None.url() } + IndicesGetMappingRequest { + url: IndicesGetMappingUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - IndicesGetMappingRequest { url: IndicesGetMappingUrlParams::Index(index.into()).url() } + IndicesGetMappingRequest { + url: IndicesGetMappingUrlParams::Index(index.into()).url(), + } } pub fn for_index_ty(index: IIndex, ty: IType) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { IndicesGetMappingRequest { url: IndicesGetMappingUrlParams::IndexType(index.into(), ty.into()).url(), } } pub fn for_ty(ty: IType) -> Self - where IType: Into> + where + IType: Into>, { - IndicesGetMappingRequest { url: IndicesGetMappingUrlParams::Type(ty.into()).url() } + IndicesGetMappingRequest { + url: IndicesGetMappingUrlParams::Type(ty.into()).url(), + } } } impl<'a> Into> for IndicesGetMappingRequest<'a> { @@ -3858,7 +4035,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SnapshotGetUrlParams<'a> { RepositorySnapshot(Repository<'a>, Snapshot<'a>), } @@ -3866,8 +4043,7 @@ pub mod endpoints { pub fn url(self) -> Url<'a> { match self { SnapshotGetUrlParams::RepositorySnapshot(ref repository, ref snapshot) => { - let mut url = String::with_capacity(12usize + repository.len() + - snapshot.len()); + let mut url = String::with_capacity(12usize + repository.len() + snapshot.len()); url.push_str("/_snapshot/"); url.push_str(repository.as_ref()); url.push_str("/"); @@ -3877,20 +4053,18 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SnapshotGetRequest<'a> { pub url: Url<'a>, } impl<'a> SnapshotGetRequest<'a> { - pub fn for_repository_snapshot(repository: IRepository, - snapshot: ISnapshot) - -> Self - where IRepository: Into>, - ISnapshot: Into> + pub fn for_repository_snapshot(repository: IRepository, snapshot: ISnapshot) -> Self + where + IRepository: Into>, + ISnapshot: Into>, { SnapshotGetRequest { - url: SnapshotGetUrlParams::RepositorySnapshot(repository.into(), snapshot.into()) - .url(), + url: SnapshotGetUrlParams::RepositorySnapshot(repository.into(), snapshot.into()).url(), } } } @@ -3903,7 +4077,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatNodesUrlParams { None, } @@ -3914,13 +4088,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatNodesRequest<'a> { pub url: Url<'a>, } impl<'a> CatNodesRequest<'a> { pub fn new() -> Self { - CatNodesRequest { url: CatNodesUrlParams::None.url() } + CatNodesRequest { + url: CatNodesUrlParams::None.url(), + } } } impl<'a> Into> for CatNodesRequest<'a> { @@ -3932,7 +4108,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ExistsUrlParams<'a> { IndexTypeId(Index<'a>, Type<'a>, Id<'a>), } @@ -3952,15 +4128,16 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ExistsRequest<'a> { pub url: Url<'a>, } impl<'a> ExistsRequest<'a> { pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId) -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + where + IIndex: Into>, + IType: Into>, + IId: Into>, { ExistsRequest { url: ExistsUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -3976,7 +4153,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ClusterRerouteUrlParams { None, } @@ -3987,7 +4164,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ClusterRerouteRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -4009,7 +4186,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum NodesHotThreadsUrlParams<'a> { None, NodeId(NodeId<'a>), @@ -4028,18 +4205,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct NodesHotThreadsRequest<'a> { pub url: Url<'a>, } impl<'a> NodesHotThreadsRequest<'a> { pub fn new() -> Self { - NodesHotThreadsRequest { url: NodesHotThreadsUrlParams::None.url() } + NodesHotThreadsRequest { + url: NodesHotThreadsUrlParams::None.url(), + } } pub fn for_node_id(node_id: INodeId) -> Self - where INodeId: Into> + where + INodeId: Into>, { - NodesHotThreadsRequest { url: NodesHotThreadsUrlParams::NodeId(node_id.into()).url() } + NodesHotThreadsRequest { + url: NodesHotThreadsUrlParams::NodeId(node_id.into()).url(), + } } } impl<'a> Into> for NodesHotThreadsRequest<'a> { @@ -4051,7 +4233,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum NodesStatsUrlParams<'a> { None, Metric(Metric<'a>), @@ -4071,8 +4253,7 @@ pub mod endpoints { Url::from(url) } NodesStatsUrlParams::MetricIndexMetric(ref metric, ref index_metric) => { - let mut url = String::with_capacity(15usize + metric.len() + - index_metric.len()); + let mut url = String::with_capacity(15usize + metric.len() + index_metric.len()); url.push_str("/_nodes/stats/"); url.push_str(metric.as_ref()); url.push_str("/"); @@ -4094,11 +4275,8 @@ pub mod endpoints { url.push_str(metric.as_ref()); Url::from(url) } - NodesStatsUrlParams::NodeIdMetricIndexMetric(ref node_id, - ref metric, - ref index_metric) => { - let mut url = String::with_capacity(16usize + node_id.len() + metric.len() + - index_metric.len()); + NodesStatsUrlParams::NodeIdMetricIndexMetric(ref node_id, ref metric, ref index_metric) => { + let mut url = String::with_capacity(16usize + node_id.len() + metric.len() + index_metric.len()); url.push_str("/_nodes/"); url.push_str(node_id.as_ref()); url.push_str("/stats/"); @@ -4110,48 +4288,58 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct NodesStatsRequest<'a> { pub url: Url<'a>, } impl<'a> NodesStatsRequest<'a> { pub fn new() -> Self { - NodesStatsRequest { url: NodesStatsUrlParams::None.url() } + NodesStatsRequest { + url: NodesStatsUrlParams::None.url(), + } } pub fn for_metric(metric: IMetric) -> Self - where IMetric: Into> + where + IMetric: Into>, { - NodesStatsRequest { url: NodesStatsUrlParams::Metric(metric.into()).url() } + NodesStatsRequest { + url: NodesStatsUrlParams::Metric(metric.into()).url(), + } } - pub fn for_metric_index_metric(metric: IMetric, - index_metric: IIndexMetric) - -> Self - where IMetric: Into>, - IIndexMetric: Into> + pub fn for_metric_index_metric(metric: IMetric, index_metric: IIndexMetric) -> Self + where + IMetric: Into>, + IIndexMetric: Into>, { NodesStatsRequest { - url: NodesStatsUrlParams::MetricIndexMetric(metric.into(), index_metric.into()) - .url(), + url: NodesStatsUrlParams::MetricIndexMetric(metric.into(), index_metric.into()).url(), } } pub fn for_node_id(node_id: INodeId) -> Self - where INodeId: Into> + where + INodeId: Into>, { - NodesStatsRequest { url: NodesStatsUrlParams::NodeId(node_id.into()).url() } + NodesStatsRequest { + url: NodesStatsUrlParams::NodeId(node_id.into()).url(), + } } pub fn for_node_id_metric(node_id: INodeId, metric: IMetric) -> Self - where INodeId: Into>, - IMetric: Into> + where + INodeId: Into>, + IMetric: Into>, { NodesStatsRequest { url: NodesStatsUrlParams::NodeIdMetric(node_id.into(), metric.into()).url(), } - } pub fn for_node_id_metric_index_metric < INodeId , IMetric , IIndexMetric > ( node_id : INodeId , metric : IMetric , index_metric : IIndexMetric ) -> Self where INodeId : Into < NodeId < 'a > > , IMetric : Into < Metric < 'a > > , IIndexMetric : Into < IndexMetric < 'a > > { + } + pub fn for_node_id_metric_index_metric(node_id: INodeId, metric: IMetric, index_metric: IIndexMetric) -> Self + where + INodeId: Into>, + IMetric: Into>, + IIndexMetric: Into>, + { NodesStatsRequest { - url: NodesStatsUrlParams::NodeIdMetricIndexMetric(node_id.into(), - metric.into(), - index_metric.into()) - .url(), + url: NodesStatsUrlParams::NodeIdMetricIndexMetric(node_id.into(), metric.into(), index_metric.into()).url(), } } } @@ -4164,7 +4352,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IngestGetPipelineUrlParams<'a> { None, Id(Id<'a>), @@ -4182,18 +4370,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IngestGetPipelineRequest<'a> { pub url: Url<'a>, } impl<'a> IngestGetPipelineRequest<'a> { pub fn new() -> Self { - IngestGetPipelineRequest { url: IngestGetPipelineUrlParams::None.url() } + IngestGetPipelineRequest { + url: IngestGetPipelineUrlParams::None.url(), + } } pub fn for_id(id: IId) -> Self - where IId: Into> + where + IId: Into>, { - IngestGetPipelineRequest { url: IngestGetPipelineUrlParams::Id(id.into()).url() } + IngestGetPipelineRequest { + url: IngestGetPipelineUrlParams::Id(id.into()).url(), + } } } impl<'a> Into> for IngestGetPipelineRequest<'a> { @@ -4205,7 +4398,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum PutTemplateUrlParams<'a> { Id(Id<'a>), } @@ -4221,14 +4414,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct PutTemplateRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> PutTemplateRequest<'a, B> { pub fn for_id(id: IId, body: B) -> Self - where IId: Into> + where + IId: Into>, { PutTemplateRequest { url: PutTemplateUrlParams::Id(id.into()).url(), @@ -4245,7 +4439,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum GetSourceUrlParams<'a> { IndexTypeId(Index<'a>, Type<'a>, Id<'a>), } @@ -4253,8 +4447,7 @@ pub mod endpoints { pub fn url(self) -> Url<'a> { match self { GetSourceUrlParams::IndexTypeId(ref index, ref ty, ref id) => { - let mut url = String::with_capacity(11usize + index.len() + ty.len() + - id.len()); + let mut url = String::with_capacity(11usize + index.len() + ty.len() + id.len()); url.push_str("/"); url.push_str(index.as_ref()); url.push_str("/"); @@ -4267,15 +4460,16 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct GetSourceRequest<'a> { pub url: Url<'a>, } impl<'a> GetSourceRequest<'a> { pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId) -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + where + IIndex: Into>, + IType: Into>, + IId: Into>, { GetSourceRequest { url: GetSourceUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -4291,7 +4485,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SnapshotCreateUrlParams<'a> { RepositorySnapshot(Repository<'a>, Snapshot<'a>), } @@ -4299,8 +4493,7 @@ pub mod endpoints { pub fn url(self) -> Url<'a> { match self { SnapshotCreateUrlParams::RepositorySnapshot(ref repository, ref snapshot) => { - let mut url = String::with_capacity(12usize + repository.len() + - snapshot.len()); + let mut url = String::with_capacity(12usize + repository.len() + snapshot.len()); url.push_str("/_snapshot/"); url.push_str(repository.as_ref()); url.push_str("/"); @@ -4310,23 +4503,19 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SnapshotCreateRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> SnapshotCreateRequest<'a, B> { - pub fn for_repository_snapshot(repository: IRepository, - snapshot: ISnapshot, - body: B) - -> Self - where IRepository: Into>, - ISnapshot: Into> + pub fn for_repository_snapshot(repository: IRepository, snapshot: ISnapshot, body: B) -> Self + where + IRepository: Into>, + ISnapshot: Into>, { SnapshotCreateRequest { - url: SnapshotCreateUrlParams::RepositorySnapshot(repository.into(), - snapshot.into()) - .url(), + url: SnapshotCreateUrlParams::RepositorySnapshot(repository.into(), snapshot.into()).url(), body: body, } } @@ -4340,7 +4529,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ScrollUrlParams<'a> { None, ScrollId(ScrollId<'a>), @@ -4358,7 +4547,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ScrollRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -4371,7 +4560,8 @@ pub mod endpoints { } } pub fn for_scroll_id(scroll_id: IScrollId, body: B) -> Self - where IScrollId: Into> + where + IScrollId: Into>, { ScrollRequest { url: ScrollUrlParams::ScrollId(scroll_id.into()).url(), @@ -4388,7 +4578,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SnapshotStatusUrlParams<'a> { None, Repository(Repository<'a>), @@ -4406,8 +4596,7 @@ pub mod endpoints { Url::from(url) } SnapshotStatusUrlParams::RepositorySnapshot(ref repository, ref snapshot) => { - let mut url = String::with_capacity(20usize + repository.len() + - snapshot.len()); + let mut url = String::with_capacity(20usize + repository.len() + snapshot.len()); url.push_str("/_snapshot/"); url.push_str(repository.as_ref()); url.push_str("/"); @@ -4418,31 +4607,31 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SnapshotStatusRequest<'a> { pub url: Url<'a>, } impl<'a> SnapshotStatusRequest<'a> { pub fn new() -> Self { - SnapshotStatusRequest { url: SnapshotStatusUrlParams::None.url() } + SnapshotStatusRequest { + url: SnapshotStatusUrlParams::None.url(), + } } pub fn for_repository(repository: IRepository) -> Self - where IRepository: Into> + where + IRepository: Into>, { SnapshotStatusRequest { url: SnapshotStatusUrlParams::Repository(repository.into()).url(), } } - pub fn for_repository_snapshot(repository: IRepository, - snapshot: ISnapshot) - -> Self - where IRepository: Into>, - ISnapshot: Into> + pub fn for_repository_snapshot(repository: IRepository, snapshot: ISnapshot) -> Self + where + IRepository: Into>, + ISnapshot: Into>, { SnapshotStatusRequest { - url: SnapshotStatusUrlParams::RepositorySnapshot(repository.into(), - snapshot.into()) - .url(), + url: SnapshotStatusUrlParams::RepositorySnapshot(repository.into(), snapshot.into()).url(), } } } @@ -4455,7 +4644,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum MgetUrlParams<'a> { None, Index(Index<'a>), @@ -4484,7 +4673,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct MgetRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -4497,7 +4686,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { MgetRequest { url: MgetUrlParams::Index(index.into()).url(), @@ -4505,8 +4695,9 @@ pub mod endpoints { } } pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { MgetRequest { url: MgetUrlParams::IndexType(index.into(), ty.into()).url(), @@ -4523,7 +4714,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesExistsTemplateUrlParams<'a> { Name(Name<'a>), } @@ -4539,13 +4730,14 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesExistsTemplateRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesExistsTemplateRequest<'a> { pub fn for_name(name: IName) -> Self - where IName: Into> + where + IName: Into>, { IndicesExistsTemplateRequest { url: IndicesExistsTemplateUrlParams::Name(name.into()).url(), @@ -4561,7 +4753,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesGetUpgradeUrlParams<'a> { None, Index(Index<'a>), @@ -4580,18 +4772,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesGetUpgradeRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesGetUpgradeRequest<'a> { pub fn new() -> Self { - IndicesGetUpgradeRequest { url: IndicesGetUpgradeUrlParams::None.url() } + IndicesGetUpgradeRequest { + url: IndicesGetUpgradeUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - IndicesGetUpgradeRequest { url: IndicesGetUpgradeUrlParams::Index(index.into()).url() } + IndicesGetUpgradeRequest { + url: IndicesGetUpgradeUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for IndicesGetUpgradeRequest<'a> { @@ -4603,7 +4800,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum PutScriptUrlParams<'a> { LangId(Lang<'a>, Id<'a>), } @@ -4621,15 +4818,16 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct PutScriptRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> PutScriptRequest<'a, B> { pub fn for_lang_id(lang: ILang, id: IId, body: B) -> Self - where ILang: Into>, - IId: Into> + where + ILang: Into>, + IId: Into>, { PutScriptRequest { url: PutScriptUrlParams::LangId(lang.into(), id.into()).url(), @@ -4646,7 +4844,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum GetTemplateUrlParams<'a> { Id(Id<'a>), } @@ -4662,15 +4860,18 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct GetTemplateRequest<'a> { pub url: Url<'a>, } impl<'a> GetTemplateRequest<'a> { pub fn for_id(id: IId) -> Self - where IId: Into> + where + IId: Into>, { - GetTemplateRequest { url: GetTemplateUrlParams::Id(id.into()).url() } + GetTemplateRequest { + url: GetTemplateUrlParams::Id(id.into()).url(), + } } } impl<'a> Into> for GetTemplateRequest<'a> { @@ -4682,7 +4883,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesDeleteTemplateUrlParams<'a> { Name(Name<'a>), } @@ -4698,13 +4899,14 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesDeleteTemplateRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesDeleteTemplateRequest<'a> { pub fn for_name(name: IName) -> Self - where IName: Into> + where + IName: Into>, { IndicesDeleteTemplateRequest { url: IndicesDeleteTemplateUrlParams::Name(name.into()).url(), @@ -4720,7 +4922,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndexUrlParams<'a> { IndexType(Index<'a>, Type<'a>), IndexTypeId(Index<'a>, Type<'a>, Id<'a>), @@ -4749,29 +4951,27 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndexRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IndexRequest<'a, B> { pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { IndexRequest { url: IndexUrlParams::IndexType(index.into(), ty.into()).url(), body: body, } } - pub fn for_index_ty_id(index: IIndex, - ty: IType, - id: IId, - body: B) - -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId, body: B) -> Self + where + IIndex: Into>, + IType: Into>, + IId: Into>, { IndexRequest { url: IndexUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -4788,7 +4988,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesPutSettingsUrlParams<'a> { None, Index(Index<'a>), @@ -4807,7 +5007,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesPutSettingsRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -4820,7 +5020,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesPutSettingsRequest { url: IndicesPutSettingsUrlParams::Index(index.into()).url(), @@ -4837,7 +5038,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatTemplatesUrlParams<'a> { None, Name(Name<'a>), @@ -4855,18 +5056,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatTemplatesRequest<'a> { pub url: Url<'a>, } impl<'a> CatTemplatesRequest<'a> { pub fn new() -> Self { - CatTemplatesRequest { url: CatTemplatesUrlParams::None.url() } + CatTemplatesRequest { + url: CatTemplatesUrlParams::None.url(), + } } pub fn for_name(name: IName) -> Self - where IName: Into> + where + IName: Into>, { - CatTemplatesRequest { url: CatTemplatesUrlParams::Name(name.into()).url() } + CatTemplatesRequest { + url: CatTemplatesUrlParams::Name(name.into()).url(), + } } } impl<'a> Into> for CatTemplatesRequest<'a> { @@ -4878,7 +5084,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatIndicesUrlParams<'a> { None, Index(Index<'a>), @@ -4896,18 +5102,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatIndicesRequest<'a> { pub url: Url<'a>, } impl<'a> CatIndicesRequest<'a> { pub fn new() -> Self { - CatIndicesRequest { url: CatIndicesUrlParams::None.url() } + CatIndicesRequest { + url: CatIndicesUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - CatIndicesRequest { url: CatIndicesUrlParams::Index(index.into()).url() } + CatIndicesRequest { + url: CatIndicesUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for CatIndicesRequest<'a> { @@ -4919,7 +5130,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ClusterPutSettingsUrlParams { None, } @@ -4930,7 +5141,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ClusterPutSettingsRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -4952,7 +5163,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum UpdateUrlParams<'a> { IndexTypeId(Index<'a>, Type<'a>, Id<'a>), } @@ -4960,8 +5171,7 @@ pub mod endpoints { pub fn url(self) -> Url<'a> { match self { UpdateUrlParams::IndexTypeId(ref index, ref ty, ref id) => { - let mut url = String::with_capacity(11usize + index.len() + ty.len() + - id.len()); + let mut url = String::with_capacity(11usize + index.len() + ty.len() + id.len()); url.push_str("/"); url.push_str(index.as_ref()); url.push_str("/"); @@ -4974,20 +5184,17 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct UpdateRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> UpdateRequest<'a, B> { - pub fn for_index_ty_id(index: IIndex, - ty: IType, - id: IId, - body: B) - -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId, body: B) -> Self + where + IIndex: Into>, + IType: Into>, + IId: Into>, { UpdateRequest { url: UpdateUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -5004,7 +5211,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesPutAliasUrlParams<'a> { IndexName(Index<'a>, Name<'a>), } @@ -5022,15 +5229,16 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesPutAliasRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IndicesPutAliasRequest<'a, B> { pub fn for_index_name(index: IIndex, name: IName, body: B) -> Self - where IIndex: Into>, - IName: Into> + where + IIndex: Into>, + IName: Into>, { IndicesPutAliasRequest { url: IndicesPutAliasUrlParams::IndexName(index.into(), name.into()).url(), @@ -5047,7 +5255,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatPluginsUrlParams { None, } @@ -5058,13 +5266,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatPluginsRequest<'a> { pub url: Url<'a>, } impl<'a> CatPluginsRequest<'a> { pub fn new() -> Self { - CatPluginsRequest { url: CatPluginsUrlParams::None.url() } + CatPluginsRequest { + url: CatPluginsUrlParams::None.url(), + } } } impl<'a> Into> for CatPluginsRequest<'a> { @@ -5076,7 +5286,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CountPercolateUrlParams<'a> { IndexType(Index<'a>, Type<'a>), IndexTypeId(Index<'a>, Type<'a>, Id<'a>), @@ -5094,8 +5304,7 @@ pub mod endpoints { Url::from(url) } CountPercolateUrlParams::IndexTypeId(ref index, ref ty, ref id) => { - let mut url = String::with_capacity(20usize + index.len() + ty.len() + - id.len()); + let mut url = String::with_capacity(20usize + index.len() + ty.len() + id.len()); url.push_str("/"); url.push_str(index.as_ref()); url.push_str("/"); @@ -5108,29 +5317,27 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CountPercolateRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> CountPercolateRequest<'a, B> { pub fn for_index_ty(index: IIndex, ty: IType, body: B) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { CountPercolateRequest { url: CountPercolateUrlParams::IndexType(index.into(), ty.into()).url(), body: body, } } - pub fn for_index_ty_id(index: IIndex, - ty: IType, - id: IId, - body: B) - -> Self - where IIndex: Into>, - IType: Into>, - IId: Into> + pub fn for_index_ty_id(index: IIndex, ty: IType, id: IId, body: B) -> Self + where + IIndex: Into>, + IType: Into>, + IId: Into>, { CountPercolateRequest { url: CountPercolateUrlParams::IndexTypeId(index.into(), ty.into(), id.into()).url(), @@ -5147,7 +5354,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesUpgradeUrlParams<'a> { None, Index(Index<'a>), @@ -5166,7 +5373,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesUpgradeRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -5179,7 +5386,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesUpgradeRequest { url: IndicesUpgradeUrlParams::Index(index.into()).url(), @@ -5196,7 +5404,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesDeleteAliasUrlParams<'a> { IndexName(Index<'a>, Name<'a>), } @@ -5214,14 +5422,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesDeleteAliasRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesDeleteAliasRequest<'a> { pub fn for_index_name(index: IIndex, name: IName) -> Self - where IIndex: Into>, - IName: Into> + where + IIndex: Into>, + IName: Into>, { IndicesDeleteAliasRequest { url: IndicesDeleteAliasUrlParams::IndexName(index.into(), name.into()).url(), @@ -5237,7 +5446,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatTasksUrlParams { None, } @@ -5248,13 +5457,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatTasksRequest<'a> { pub url: Url<'a>, } impl<'a> CatTasksRequest<'a> { pub fn new() -> Self { - CatTasksRequest { url: CatTasksUrlParams::None.url() } + CatTasksRequest { + url: CatTasksUrlParams::None.url(), + } } } impl<'a> Into> for CatTasksRequest<'a> { @@ -5266,7 +5477,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesRolloverUrlParams<'a> { Alias(Alias<'a>), AliasNewIndex(Alias<'a>, NewIndex<'a>), @@ -5292,26 +5503,25 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesRolloverRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IndicesRolloverRequest<'a, B> { pub fn for_alias(alias: IAlias, body: B) -> Self - where IAlias: Into> + where + IAlias: Into>, { IndicesRolloverRequest { url: IndicesRolloverUrlParams::Alias(alias.into()).url(), body: body, } } - pub fn for_alias_new_index(alias: IAlias, - new_index: INewIndex, - body: B) - -> Self - where IAlias: Into>, - INewIndex: Into> + pub fn for_alias_new_index(alias: IAlias, new_index: INewIndex, body: B) -> Self + where + IAlias: Into>, + INewIndex: Into>, { IndicesRolloverRequest { url: IndicesRolloverUrlParams::AliasNewIndex(alias.into(), new_index.into()).url(), @@ -5328,7 +5538,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ReindexRethrottleUrlParams<'a> { TaskId(TaskId<'a>), } @@ -5345,14 +5555,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ReindexRethrottleRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> ReindexRethrottleRequest<'a, B> { pub fn for_task_id(task_id: ITaskId, body: B) -> Self - where ITaskId: Into> + where + ITaskId: Into>, { ReindexRethrottleRequest { url: ReindexRethrottleUrlParams::TaskId(task_id.into()).url(), @@ -5369,7 +5580,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum SnapshotCreateRepositoryUrlParams<'a> { Repository(Repository<'a>), } @@ -5385,14 +5596,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct SnapshotCreateRepositoryRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> SnapshotCreateRepositoryRequest<'a, B> { pub fn for_repository(repository: IRepository, body: B) -> Self - where IRepository: Into> + where + IRepository: Into>, { SnapshotCreateRepositoryRequest { url: SnapshotCreateRepositoryUrlParams::Repository(repository.into()).url(), @@ -5409,7 +5621,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesGetUrlParams<'a> { Index(Index<'a>), IndexFeature(Index<'a>, Feature<'a>), @@ -5434,19 +5646,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesGetRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesGetRequest<'a> { pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - IndicesGetRequest { url: IndicesGetUrlParams::Index(index.into()).url() } + IndicesGetRequest { + url: IndicesGetUrlParams::Index(index.into()).url(), + } } pub fn for_index_feature(index: IIndex, feature: IFeature) -> Self - where IIndex: Into>, - IFeature: Into> + where + IIndex: Into>, + IFeature: Into>, { IndicesGetRequest { url: IndicesGetUrlParams::IndexFeature(index.into(), feature.into()).url(), @@ -5462,7 +5678,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesAnalyzeUrlParams<'a> { None, Index(Index<'a>), @@ -5481,7 +5697,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesAnalyzeRequest<'a, B> { pub url: Url<'a>, pub body: B, @@ -5494,7 +5710,8 @@ pub mod endpoints { } } pub fn for_index(index: IIndex, body: B) -> Self - where IIndex: Into> + where + IIndex: Into>, { IndicesAnalyzeRequest { url: IndicesAnalyzeUrlParams::Index(index.into()).url(), @@ -5511,7 +5728,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatFielddataUrlParams<'a> { None, Fields(Fields<'a>), @@ -5529,18 +5746,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatFielddataRequest<'a> { pub url: Url<'a>, } impl<'a> CatFielddataRequest<'a> { pub fn new() -> Self { - CatFielddataRequest { url: CatFielddataUrlParams::None.url() } + CatFielddataRequest { + url: CatFielddataUrlParams::None.url(), + } } pub fn for_fields(fields: IFields) -> Self - where IFields: Into> + where + IFields: Into>, { - CatFielddataRequest { url: CatFielddataUrlParams::Fields(fields.into()).url() } + CatFielddataRequest { + url: CatFielddataUrlParams::Fields(fields.into()).url(), + } } } impl<'a> Into> for CatFielddataRequest<'a> { @@ -5552,7 +5774,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesSegmentsUrlParams<'a> { None, Index(Index<'a>), @@ -5571,18 +5793,23 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesSegmentsRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesSegmentsRequest<'a> { pub fn new() -> Self { - IndicesSegmentsRequest { url: IndicesSegmentsUrlParams::None.url() } + IndicesSegmentsRequest { + url: IndicesSegmentsUrlParams::None.url(), + } } pub fn for_index(index: IIndex) -> Self - where IIndex: Into> + where + IIndex: Into>, { - IndicesSegmentsRequest { url: IndicesSegmentsUrlParams::Index(index.into()).url() } + IndicesSegmentsRequest { + url: IndicesSegmentsUrlParams::Index(index.into()).url(), + } } } impl<'a> Into> for IndicesSegmentsRequest<'a> { @@ -5594,7 +5821,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesShrinkUrlParams<'a> { IndexTarget(Index<'a>, Target<'a>), } @@ -5612,15 +5839,16 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesShrinkRequest<'a, B> { pub url: Url<'a>, pub body: B, } impl<'a, B> IndicesShrinkRequest<'a, B> { pub fn for_index_target(index: IIndex, target: ITarget, body: B) -> Self - where IIndex: Into>, - ITarget: Into> + where + IIndex: Into>, + ITarget: Into>, { IndicesShrinkRequest { url: IndicesShrinkUrlParams::IndexTarget(index.into(), target.into()).url(), @@ -5637,7 +5865,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum TasksListUrlParams { None, } @@ -5648,13 +5876,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct TasksListRequest<'a> { pub url: Url<'a>, } impl<'a> TasksListRequest<'a> { pub fn new() -> Self { - TasksListRequest { url: TasksListUrlParams::None.url() } + TasksListRequest { + url: TasksListUrlParams::None.url(), + } } } impl<'a> Into> for TasksListRequest<'a> { @@ -5666,7 +5896,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum CatMasterUrlParams { None, } @@ -5677,13 +5907,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct CatMasterRequest<'a> { pub url: Url<'a>, } impl<'a> CatMasterRequest<'a> { pub fn new() -> Self { - CatMasterRequest { url: CatMasterUrlParams::None.url() } + CatMasterRequest { + url: CatMasterUrlParams::None.url(), + } } } impl<'a> Into> for CatMasterRequest<'a> { @@ -5695,7 +5927,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum IndicesExistsTypeUrlParams<'a> { IndexType(Index<'a>, Type<'a>), } @@ -5713,14 +5945,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndicesExistsTypeRequest<'a> { pub url: Url<'a>, } impl<'a> IndicesExistsTypeRequest<'a> { pub fn for_index_ty(index: IIndex, ty: IType) -> Self - where IIndex: Into>, - IType: Into> + where + IIndex: Into>, + IType: Into>, { IndicesExistsTypeRequest { url: IndicesExistsTypeUrlParams::IndexType(index.into(), ty.into()).url(), @@ -5736,7 +5969,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum ClusterGetSettingsUrlParams { None, } @@ -5747,13 +5980,15 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ClusterGetSettingsRequest<'a> { pub url: Url<'a>, } impl<'a> ClusterGetSettingsRequest<'a> { pub fn new() -> Self { - ClusterGetSettingsRequest { url: ClusterGetSettingsUrlParams::None.url() } + ClusterGetSettingsRequest { + url: ClusterGetSettingsUrlParams::None.url(), + } } } impl<'a> Into> for ClusterGetSettingsRequest<'a> { @@ -5765,7 +6000,7 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] enum NodesInfoUrlParams<'a> { None, Metric(Metric<'a>), @@ -5799,27 +6034,36 @@ pub mod endpoints { } } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct NodesInfoRequest<'a> { pub url: Url<'a>, } impl<'a> NodesInfoRequest<'a> { pub fn new() -> Self { - NodesInfoRequest { url: NodesInfoUrlParams::None.url() } + NodesInfoRequest { + url: NodesInfoUrlParams::None.url(), + } } pub fn for_metric(metric: IMetric) -> Self - where IMetric: Into> + where + IMetric: Into>, { - NodesInfoRequest { url: NodesInfoUrlParams::Metric(metric.into()).url() } + NodesInfoRequest { + url: NodesInfoUrlParams::Metric(metric.into()).url(), + } } pub fn for_node_id(node_id: INodeId) -> Self - where INodeId: Into> + where + INodeId: Into>, { - NodesInfoRequest { url: NodesInfoUrlParams::NodeId(node_id.into()).url() } + NodesInfoRequest { + url: NodesInfoUrlParams::NodeId(node_id.into()).url(), + } } pub fn for_node_id_metric(node_id: INodeId, metric: IMetric) -> Self - where INodeId: Into>, - IMetric: Into> + where + INodeId: Into>, + IMetric: Into>, { NodesInfoRequest { url: NodesInfoUrlParams::NodeIdMetric(node_id.into(), metric.into()).url(), @@ -5841,8 +6085,8 @@ pub mod http { use std::borrow::Cow; use std::ops::Deref; - # [ derive ( Debug , PartialEq , Clone ) ] - # [ doc = r" A wrapper around an owned or borrowed url." ] + #[derive(Debug, PartialEq, Clone)] + #[doc = r" A wrapper around an owned or borrowed url."] pub struct Url<'a>(Cow<'a, str>); impl<'a> From<&'a str> for Url<'a> { fn from(value: &'a str) -> Url<'a> { @@ -5860,22 +6104,22 @@ pub mod http { &self.0 } } - # [ doc = r" A default body type." ] + #[doc = r" A default body type."] pub type DefaultBody = &'static [u8]; - # [ doc = r" A convenience method for a default, empty body." ] - # [ doc = r" This method doesn't allocate." ] + #[doc = r" A convenience method for a default, empty body."] + #[doc = r" This method doesn't allocate."] pub fn empty_body() -> DefaultBody { &[] } - # [ derive ( Debug , PartialEq , Clone ) ] - # [ doc = r" A general request type that all endpoints can be converted into." ] + #[derive(Debug, PartialEq, Clone)] + #[doc = r" A general request type that all endpoints can be converted into."] pub struct HttpRequest<'a, B> { pub url: Url<'a>, pub method: HttpMethod, pub body: Option, } - # [ derive ( Debug , PartialEq , Clone ) ] - # [ doc = r" A standard HTTP verb." ] + #[derive(Debug, PartialEq, Clone)] + #[doc = r" A standard HTTP verb."] pub enum HttpMethod { Head, Get, @@ -5891,10 +6135,11 @@ pub mod params { include!("genned.params.rs"); - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Alias<'a>(pub Cow<'a, str>); pub fn alias<'a, I>(value: I) -> Alias<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -5915,10 +6160,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Feature<'a>(pub Cow<'a, str>); pub fn feature<'a, I>(value: I) -> Feature<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -5939,10 +6185,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Fields<'a>(pub Cow<'a, str>); pub fn fields<'a, I>(value: I) -> Fields<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -5963,10 +6210,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Id<'a>(pub Cow<'a, str>); pub fn id<'a, I>(value: I) -> Id<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -5987,10 +6235,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Index<'a>(pub Cow<'a, str>); pub fn index<'a, I>(value: I) -> Index<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6011,10 +6260,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct IndexMetric<'a>(pub Cow<'a, str>); pub fn index_metric<'a, I>(value: I) -> IndexMetric<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6035,10 +6285,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Lang<'a>(pub Cow<'a, str>); pub fn lang<'a, I>(value: I) -> Lang<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6059,10 +6310,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Metric<'a>(pub Cow<'a, str>); pub fn metric<'a, I>(value: I) -> Metric<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6083,10 +6335,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Name<'a>(pub Cow<'a, str>); pub fn name<'a, I>(value: I) -> Name<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6107,10 +6360,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct NewIndex<'a>(pub Cow<'a, str>); pub fn new_index<'a, I>(value: I) -> NewIndex<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6131,10 +6385,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct NodeId<'a>(pub Cow<'a, str>); pub fn node_id<'a, I>(value: I) -> NodeId<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6155,10 +6410,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Repository<'a>(pub Cow<'a, str>); pub fn repository<'a, I>(value: I) -> Repository<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6179,10 +6435,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ScrollId<'a>(pub Cow<'a, str>); pub fn scroll_id<'a, I>(value: I) -> ScrollId<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6203,10 +6460,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Snapshot<'a>(pub Cow<'a, str>); pub fn snapshot<'a, I>(value: I) -> Snapshot<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6227,10 +6485,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Target<'a>(pub Cow<'a, str>); pub fn target<'a, I>(value: I) -> Target<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6251,10 +6510,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct TaskId<'a>(pub Cow<'a, str>); pub fn task_id<'a, I>(value: I) -> TaskId<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6275,10 +6535,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct ThreadPoolPatterns<'a>(pub Cow<'a, str>); pub fn thread_pool_patterns<'a, I>(value: I) -> ThreadPoolPatterns<'a> - where I: Into> + where + I: Into>, { value.into() } @@ -6299,10 +6560,11 @@ pub mod params { } } - # [ derive ( Debug , PartialEq , Clone ) ] + #[derive(Debug, PartialEq, Clone)] pub struct Type<'a>(pub Cow<'a, str>); pub fn ty<'a, I>(value: I) -> Type<'a> - where I: Into> + where + I: Into>, { value.into() } diff --git a/src/requests/src/lib.rs b/src/requests/src/lib.rs index 7f55284c32..958a532de0 100644 --- a/src/requests/src/lib.rs +++ b/src/requests/src/lib.rs @@ -123,10 +123,7 @@ mod tests { fn do_something_with_request<'a, I: Into>, B: AsRef<[u8]>>(_: I) {} - fn do_something_with_static_request>, - B: 'static + AsRef<[u8]> + Send> - (req: I) - -> thread::JoinHandle<()> { + fn do_something_with_static_request>, B: 'static + AsRef<[u8]> + Send>(req: I) -> thread::JoinHandle<()> { let req = req.into(); thread::spawn(move || { assert_eq!("/test_index/test_ty/_search", *req.url); @@ -135,8 +132,7 @@ mod tests { #[test] fn it_works() { - let req = - SearchRequest::for_index_ty("test_index", "test_ty", "{'query': { 'match_all': {}}}"); + let req = SearchRequest::for_index_ty("test_index", "test_ty", "{'query': { 'match_all': {}}}"); assert_eq!("/test_index/test_ty/_search", *req.url); @@ -159,7 +155,14 @@ mod tests { #[test] fn id_from_number() { - let ids = vec![Id::from(1i32), Id::from(1u32), Id::from(1i64), Id::from(1u64), Id::from(1isize), Id::from(1usize)]; + let ids = vec![ + Id::from(1i32), + Id::from(1u32), + Id::from(1i64), + Id::from(1u64), + Id::from(1isize), + Id::from(1usize), + ]; for id in ids { assert_eq!("1", &*id); diff --git a/src/requests_codegen/src/gen/mod.rs b/src/requests_codegen/src/gen/mod.rs index 6e6780dad5..4400b9c1d9 100644 --- a/src/requests_codegen/src/gen/mod.rs +++ b/src/requests_codegen/src/gen/mod.rs @@ -11,7 +11,7 @@ pub mod types { pub mod url { use syn; use quote; - use ::gen::helpers; + use gen::helpers; pub fn ident() -> &'static str { "Url" @@ -57,7 +57,7 @@ pub mod types { pub mod body { use syn; use quote; - use ::gen::helpers; + use gen::helpers; pub fn ident() -> &'static str { "B" @@ -91,10 +91,10 @@ pub mod types { /// /// This type is a simple, standard wrapper for a HTTP request. pub mod request { - use super::{ body, url }; + use super::{body, url}; use quote; use syn; - use ::gen::helpers; + use gen::helpers; pub fn method_ident() -> &'static str { "HttpMethod" @@ -152,7 +152,7 @@ pub mod types { pub mod wrapped_ty { use inflector::Inflector; use quote; - use ::gen::helpers; + use gen::helpers; pub fn item(ty: &str) -> quote::Tokens { let ty = ty.to_pascal_case(); @@ -214,7 +214,9 @@ pub mod helpers { /// A standard `'a` lifetime. pub fn lifetime() -> syn::Lifetime { - syn::Lifetime { ident: syn::Ident::new("'a") } + syn::Lifetime { + ident: syn::Ident::new("'a"), + } } /// Generics with a standard `'a` lifetime. @@ -232,10 +234,12 @@ pub mod helpers { syn::Generics { lifetimes: lifetimes .into_iter() - .map(|l| syn::LifetimeDef { - attrs: vec![], - lifetime: l, - bounds: vec![] + .map(|l| { + syn::LifetimeDef { + attrs: vec![], + lifetime: l, + bounds: vec![], + } }) .collect(), ty_params: types, @@ -259,17 +263,19 @@ pub mod helpers { attrs: vec![], ident: ident(ty), bounds: bounds, - default: None + default: None, } } /// AST for a generic type param bound. pub fn ty_bound(trait_ref: syn::Path) -> syn::TyParamBound { - syn::TyParamBound::Trait(syn::PolyTraitRef { - bound_lifetimes: vec![], - trait_ref: trait_ref, - }, - syn::TraitBoundModifier::None) + syn::TyParamBound::Trait( + syn::PolyTraitRef { + bound_lifetimes: vec![], + trait_ref: trait_ref, + }, + syn::TraitBoundModifier::None, + ) } /// AST for a path type with lifetimes and type parameters. @@ -290,30 +296,30 @@ pub mod helpers { /// AST for a path variable. pub fn path_segments(paths: Vec<(&str, Vec, Vec)>) -> syn::Path { syn::Path { - global: false, - segments: paths.into_iter() - .map(|(path, lifetimes, types)| { - syn::PathSegment { - ident: syn::Ident::new(sanitise_ident(path)), - parameters: syn::PathParameters::AngleBracketed( - syn::AngleBracketedParameterData { - lifetimes: lifetimes, - types: types, - bindings: vec![] - } - ) - } - }) - .collect(), + global: false, + segments: paths + .into_iter() + .map(|(path, lifetimes, types)| { + syn::PathSegment { + ident: syn::Ident::new(sanitise_ident(path)), + parameters: syn::PathParameters::AngleBracketed(syn::AngleBracketedParameterData { + lifetimes: lifetimes, + types: types, + bindings: vec![], + }), + } + }) + .collect(), } } /// AST for a simple method call. pub fn method(method: &str, args: Vec<&str>) -> syn::Expr { - syn::ExprKind::MethodCall(ident(method), - vec![], - args.iter().map(|a| path_none(a).into_expr()).collect()) - .into() + syn::ExprKind::MethodCall( + ident(method), + vec![], + args.iter().map(|a| path_none(a).into_expr()).collect(), + ).into() } /// AST for a simple field access. @@ -355,10 +361,7 @@ pub mod helpers { impl<'a> IntoRustVarName for &'a str { fn into_rust_var(self) -> String { - let ident = self.split(".") - .last() - .unwrap() - .to_snake_case(); + let ident = self.split(".").last().unwrap().to_snake_case(); sanitise_ident(&ident).to_string() } @@ -403,11 +406,11 @@ pub mod helpers { fn has_lifetime(&self) -> bool; } - impl HasLifetime for T { + impl HasLifetime for T { fn has_lifetime(&self) -> bool { match &self.get_path().segments[0].parameters { &syn::PathParameters::AngleBracketed(ref params) => params.lifetimes.len() > 0, - _ => false + _ => false, } } } diff --git a/src/requests_codegen/src/gen/request_ctors.rs b/src/requests_codegen/src/gen/request_ctors.rs index 15861ee7b5..43a3c6e3d1 100644 --- a/src/requests_codegen/src/gen/request_ctors.rs +++ b/src/requests_codegen/src/gen/request_ctors.rs @@ -1,5 +1,5 @@ use syn; -use ::parse::Endpoint; +use parse::Endpoint; use super::helpers::*; use super::types; @@ -12,9 +12,7 @@ struct Constructor { impl Constructor { pub fn fields(&self) -> Vec<&(syn::Ident, syn::Ty)> { - self.params_fields - .iter() - .collect() + self.params_fields.iter().collect() } } @@ -43,9 +41,7 @@ impl RequestParamsCtorBuilder { let name: Vec = params.iter().map(|i| i.into_rust_var()).collect(); let name = format!("for_{}", name.join("_")); - let cased: Vec = params.iter() - .map(|i| i.into_rust_type()) - .collect(); + let cased: Vec = params.iter().map(|i| i.into_rust_type()).collect(); Self::ctor(&name, cased, self.has_body) } @@ -73,7 +69,8 @@ impl RequestParamsCtorBuilder { /// /// This function has the form `param1_param2(param1, param2, body?)`. fn ctor(name: &str, fields: Vec, has_body: bool) -> Constructor { - let fields: Vec<(syn::Ident, syn::Ty)> = fields.iter() + let fields: Vec<(syn::Ident, syn::Ty)> = fields + .iter() .map(|f| (ident(f.into_rust_var()), ty_a(f))) .collect(); @@ -162,18 +159,24 @@ impl RequestParamsCtorBuilder { let params_expr = match ctor.params_fields.len() { 0 => syn::ExprKind::Path(None, params_ty).into(), - _ => syn::ExprKind::Call(Box::new(syn::ExprKind::Path(None, params_ty).into()), - ctor.params_fields.iter().map(|&(ref f, _)| Self::expr_into(f)).collect()) - .into() + _ => syn::ExprKind::Call( + Box::new(syn::ExprKind::Path(None, params_ty).into()), + ctor.params_fields + .iter() + .map(|&(ref f, _)| Self::expr_into(f)) + .collect(), + ).into(), }; // AST to set the url field: `url: UrlParams::SomeVariant(a, b).url()` - let mut fields = vec![syn::FieldValue { - attrs: vec![], - ident: ident("url"), - expr: syn::ExprKind::MethodCall(ident("url"), vec![], vec![params_expr]).into(), - is_shorthand: false, - }]; + let mut fields = vec![ + syn::FieldValue { + attrs: vec![], + ident: ident("url"), + expr: syn::ExprKind::MethodCall(ident("url"), vec![], vec![params_expr]).into(), + is_shorthand: false, + }, + ]; // AST to set the body field, if present: `body: Body::new(body)` if let &Some((ref body_ident, _)) = &ctor.body_field { @@ -213,7 +216,10 @@ impl RequestParamsCtorBuilder { args.push({ let (ref name, _) = *body; - syn::FnArg::Captured(syn::Pat::Path(None, path_none(&name.to_string())), types::body::ty()) + syn::FnArg::Captured( + syn::Pat::Path(None, path_none(&name.to_string())), + types::body::ty(), + ) }); } @@ -236,22 +242,20 @@ impl RequestParamsCtorBuilder { let generic_field_tys: Vec = generic_fields .iter() - .map(|ty| { - Self::ctor_field_generic(ty) - }) + .map(|ty| Self::ctor_field_generic(ty)) .collect(); let generic_field_where_tys: Vec = generic_fields .iter() - .map(|ty| { - Self::ctor_field_generic_where_bound(ty) - }) + .map(|ty| Self::ctor_field_generic_where_bound(ty)) .collect(); let generics = syn::Generics { lifetimes: vec![], ty_params: generic_field_tys, - where_clause: syn::WhereClause { predicates: generic_field_where_tys }, + where_clause: syn::WhereClause { + predicates: generic_field_where_tys, + }, }; let fndecl = Self::ctor_decl(&ctor); @@ -263,21 +267,25 @@ impl RequestParamsCtorBuilder { vis: syn::Visibility::Public, defaultness: syn::Defaultness::Final, attrs: vec![], - node: syn::ImplItemKind::Method(syn::MethodSig { - unsafety: syn::Unsafety::Normal, - constness: syn::Constness::NotConst, - abi: None, - decl: fndecl, - generics: generics, - }, - body), + node: syn::ImplItemKind::Method( + syn::MethodSig { + unsafety: syn::Unsafety::Normal, + constness: syn::Constness::NotConst, + abi: None, + decl: fndecl, + generics: generics, + }, + body, + ), } } pub fn build(self) -> syn::Item { let ctors: Vec = self.ctors .iter() - .map(|c| Self::ctor_item(self.req_ty.clone(), self.params_ty.clone(), c)) + .map(|c| { + Self::ctor_item(self.req_ty.clone(), self.params_ty.clone(), c) + }) .collect(); let generics = { @@ -288,14 +296,17 @@ impl RequestParamsCtorBuilder { .into_iter() .next() .unwrap(); - + match segment.parameters { syn::PathParameters::AngleBracketed(data) => { - let types = data.types.iter().map(|t| ty_param(t.get_ident().as_ref(), vec![])).collect(); + let types = data.types + .iter() + .map(|t| ty_param(t.get_ident().as_ref(), vec![])) + .collect(); generics(data.lifetimes, types) - }, - _ => panic!("Only angle bracketed generics are supported.") + } + _ => panic!("Only angle bracketed generics are supported."), } }; @@ -303,34 +314,54 @@ impl RequestParamsCtorBuilder { ident: ident(""), vis: syn::Visibility::Public, attrs: vec![], - node: syn::ItemKind::Impl(syn::Unsafety::Normal, - syn::ImplPolarity::Positive, - generics, - None, - Box::new(self.req_ty), - ctors), + node: syn::ItemKind::Impl( + syn::Unsafety::Normal, + syn::ImplPolarity::Positive, + generics, + None, + Box::new(self.req_ty), + ctors, + ), } } } -impl<'a> From<(&'a (String, Endpoint), &'a syn::Ty, &'a (syn::Item, syn::Ty))> for RequestParamsCtorBuilder { - fn from(value: (&'a (String, Endpoint), &'a syn::Ty, &'a (syn::Item, syn::Ty))) -> Self { +impl< + 'a, +> From< + ( + &'a (String, Endpoint), + &'a syn::Ty, + &'a (syn::Item, syn::Ty), + ), +> for RequestParamsCtorBuilder { + fn from( + value: ( + &'a (String, Endpoint), + &'a syn::Ty, + &'a (syn::Item, syn::Ty), + ) + ) -> Self { let (&(_, ref endpoint), ref req_ty, &(ref params, ref params_ty)) = value; - let mut builder = RequestParamsCtorBuilder::new(endpoint.has_body(), (*req_ty).to_owned(), (*params_ty).to_owned()); + let mut builder = RequestParamsCtorBuilder::new( + endpoint.has_body(), + (*req_ty).to_owned(), + (*params_ty).to_owned(), + ); let ctors: Vec> = match params.node { - syn::ItemKind::Enum(ref variants, _) => { - variants.iter() - .map(|v| { - match v.data { - syn::VariantData::Unit => vec![], - syn::VariantData::Tuple(ref fields) => fields.iter().map(|f| f.ty.get_ident().to_string()).collect(), - _ => panic!("Only tuple and unit variants are supported."), - } - }) - .collect() - } + syn::ItemKind::Enum(ref variants, _) => variants + .iter() + .map(|v| match v.data { + syn::VariantData::Unit => vec![], + syn::VariantData::Tuple(ref fields) => fields + .iter() + .map(|f| f.ty.get_ident().to_string()) + .collect(), + _ => panic!("Only tuple and unit variants are supported."), + }) + .collect(), _ => panic!("Only enum types are supported."), }; @@ -370,11 +401,7 @@ pub mod tests { fn gen_request_ctor_params() { let req_ty = ty_a("Request"); let result = RequestParamsCtorBuilder::new(false, req_ty, ty_a("UrlParams")) - .with_constructor(vec![ - "Index".into(), - "Type".into(), - "Id".into() - ]) + .with_constructor(vec!["Index".into(), "Type".into(), "Id".into()]) .build(); let expected = quote!( @@ -419,11 +446,7 @@ pub mod tests { fn gen_request_ctor_params_body() { let req_ty = ty_path("Request", vec![lifetime()], vec![types::body::ty()]); let result = RequestParamsCtorBuilder::new(true, req_ty, ty_a("UrlParams")) - .with_constructor(vec![ - "Index".into(), - "Type".into(), - "Id".into() - ]) + .with_constructor(vec!["Index".into(), "Type".into(), "Id".into()]) .build(); let expected = quote!( @@ -446,18 +469,26 @@ pub mod tests { #[test] fn gen_request_ctor_from_endpoint() { - use ::parse::*; - use ::gen::url_params::UrlParamBuilder; - - let endpoint = ("indices.exists_alias".to_string(), - Endpoint { - documentation: String::new(), - methods: vec![HttpMethod::Get], - url: get_url(), - body: Some(Body { description: String::new() }), - }); + use parse::*; + use gen::url_params::UrlParamBuilder; + + let endpoint = ( + "indices.exists_alias".to_string(), + Endpoint { + documentation: String::new(), + methods: vec![HttpMethod::Get], + url: get_url(), + body: Some(Body { + description: String::new(), + }), + }, + ); - let req_ty = ty_path("IndicesExistsAliasRequest", vec![lifetime()], vec![types::body::ty()]); + let req_ty = ty_path( + "IndicesExistsAliasRequest", + vec![lifetime()], + vec![types::body::ty()], + ); let url_params = UrlParamBuilder::from(&endpoint).build(); let result = RequestParamsCtorBuilder::from((&endpoint, &req_ty, &url_params)).build(); diff --git a/src/requests_codegen/src/gen/request_into_http.rs b/src/requests_codegen/src/gen/request_into_http.rs index e558476510..b4f0f9fed0 100644 --- a/src/requests_codegen/src/gen/request_into_http.rs +++ b/src/requests_codegen/src/gen/request_into_http.rs @@ -1,6 +1,6 @@ use syn; use quote; -use ::parse::{Endpoint, HttpMethod}; +use parse::{Endpoint, HttpMethod}; use super::types; use super::helpers::*; @@ -44,8 +44,7 @@ impl RequestIntoHttpRequestBuilder { } } ) - } - else { + } else { let default_body = ident(types::body::default_ident()); quote!( @@ -76,18 +75,22 @@ impl<'a> From<(&'a (String, Endpoint), &'a syn::Ty)> for RequestIntoHttpRequestB #[cfg(test)] mod tests { - use ::parse::*; + use parse::*; use super::*; #[test] fn gen_into_http_req_with_body() { - let endpoint = ("indices.exists_alias".to_string(), - Endpoint { - documentation: String::new(), - methods: vec![HttpMethod::Get], - url: get_url(), - body: Some(Body { description: String::new() }), - }); + let endpoint = ( + "indices.exists_alias".to_string(), + Endpoint { + documentation: String::new(), + methods: vec![HttpMethod::Get], + url: get_url(), + body: Some(Body { + description: String::new(), + }), + }, + ); let req_ty = ty_path("Request", vec![lifetime()], vec![types::body::ty()]); let result = RequestIntoHttpRequestBuilder::from((&endpoint, &req_ty)).build(); @@ -109,13 +112,15 @@ mod tests { #[test] fn gen_into_http_req_no_body() { - let endpoint = ("indices.exists_alias".to_string(), - Endpoint { - documentation: String::new(), - methods: vec![HttpMethod::Get], - url: get_url(), - body: None, - }); + let endpoint = ( + "indices.exists_alias".to_string(), + Endpoint { + documentation: String::new(), + methods: vec![HttpMethod::Get], + url: get_url(), + body: None, + }, + ); let req_ty = ty_a("Request"); let result = RequestIntoHttpRequestBuilder::from((&endpoint, &req_ty)).build(); diff --git a/src/requests_codegen/src/gen/request_params.rs b/src/requests_codegen/src/gen/request_params.rs index 44cf97649b..09ee7b718a 100644 --- a/src/requests_codegen/src/gen/request_params.rs +++ b/src/requests_codegen/src/gen/request_params.rs @@ -1,5 +1,5 @@ use syn; -use ::parse; +use parse; use super::types; use super::helpers::*; @@ -24,12 +24,14 @@ impl RequestParamBuilder { } pub fn build(self) -> (syn::Item, syn::Ty) { - let mut fields = vec![syn::Field { - ident: Some(ident("url")), - vis: syn::Visibility::Public, - attrs: vec![], - ty: types::url::ty() - }]; + let mut fields = vec![ + syn::Field { + ident: Some(ident("url")), + vis: syn::Visibility::Public, + attrs: vec![], + ty: types::url::ty(), + }, + ]; let mut generics = generics(vec![lifetime()], vec![]); @@ -41,20 +43,26 @@ impl RequestParamBuilder { ty: types::body::ty(), }); - generics.ty_params.push(ty_param(types::body::ident(), vec![])); + generics + .ty_params + .push(ty_param(types::body::ident(), vec![])); } let fields = syn::VariantData::Struct(fields); - let ty = ty_path(self.name.as_ref(), - generics.lifetimes - .iter() - .map(|l| l.lifetime.to_owned()) - .collect(), - generics.ty_params - .iter() - .map(|t| ty(t.ident.as_ref())) - .collect()); + let ty = ty_path( + self.name.as_ref(), + generics + .lifetimes + .iter() + .map(|l| l.lifetime.to_owned()) + .collect(), + generics + .ty_params + .iter() + .map(|t| ty(t.ident.as_ref())) + .collect(), + ); let item = syn::Item { ident: self.name, @@ -130,15 +138,19 @@ mod tests { #[test] fn gen_params_enum_from_endpoint() { - use ::parse::*; - - let endpoint = ("indices.exists_alias".to_string(), - Endpoint { - documentation: String::new(), - methods: vec![HttpMethod::Get], - url: get_url(), - body: Some(Body { description: String::new() }), - }); + use parse::*; + + let endpoint = ( + "indices.exists_alias".to_string(), + Endpoint { + documentation: String::new(), + methods: vec![HttpMethod::Get], + url: get_url(), + body: Some(Body { + description: String::new(), + }), + }, + ); let (result, _) = RequestParamBuilder::from(&endpoint).build(); diff --git a/src/requests_codegen/src/gen/url_builder.rs b/src/requests_codegen/src/gen/url_builder.rs index 4f9bebfddc..3e792af03b 100644 --- a/src/requests_codegen/src/gen/url_builder.rs +++ b/src/requests_codegen/src/gen/url_builder.rs @@ -1,5 +1,5 @@ use syn; -use ::parse::{Endpoint, PathPart}; +use parse::{Endpoint, PathPart}; use super::types; use super::helpers::*; @@ -51,7 +51,8 @@ impl UrlParamMatchBuilder { segment.parameters = syn::PathParameters::none(); } - ty.segments.push(syn::PathSegment::from(variant.ident.to_string())); + ty.segments + .push(syn::PathSegment::from(variant.ident.to_string())); ty } @@ -59,17 +60,18 @@ impl UrlParamMatchBuilder { /// Get the fields for the enum variant to match. fn match_fields(variant: &syn::Variant) -> Vec { match variant.data { - syn::VariantData::Tuple(ref fields) => { - fields.iter() - .map(|f| { - let path = f.ty.get_ident().into_rust_var(); - - syn::Pat::Ident(syn::BindingMode::ByRef(syn::Mutability::Immutable), - ident(path), - None) - }) - .collect() - } + syn::VariantData::Tuple(ref fields) => fields + .iter() + .map(|f| { + let path = f.ty.get_ident().into_rust_var(); + + syn::Pat::Ident( + syn::BindingMode::ByRef(syn::Mutability::Immutable), + ident(path), + None, + ) + }) + .collect(), syn::VariantData::Unit => vec![], _ => panic!("Only Unit and Tuple variants are supported."), } @@ -89,11 +91,9 @@ impl<'a> From<(&'a (syn::Item, syn::Ty), Vec)> for UrlParamMatchBuil let mut builder = UrlParamMatchBuilder::new(params_ty.to_owned()); match params_item.node { - syn::ItemKind::Enum(ref variants, _) => { - for (variant, body) in variants.iter().zip(bodies.iter()) { - builder = builder.with_variant(variant, body); - } - } + syn::ItemKind::Enum(ref variants, _) => for (variant, body) in variants.iter().zip(bodies.iter()) { + builder = builder.with_variant(variant, body); + }, _ => panic!("expected syn::ItemKind::Enum"), }; @@ -132,9 +132,7 @@ impl<'a> UrlReplaceBuilder<'a> { let return_expr = syn::Stmt::Expr(Box::new(parse_expr(quote!(Url::from(#url_ident))))); - let mut stmts = vec![ - let_stmt - ]; + let mut stmts = vec![let_stmt]; stmts.append(&mut push_stmts); @@ -159,7 +157,9 @@ impl<'a> UrlReplaceBuilder<'a> { let expr = parse_expr(quote!(Url::from(#lit))); - syn::Block { stmts: vec![syn::Stmt::Expr(Box::new(expr))] } + syn::Block { + stmts: vec![syn::Stmt::Expr(Box::new(expr))], + } } /// Get the number of chars in all literal parts for the url. @@ -178,12 +178,13 @@ impl<'a> UrlReplaceBuilder<'a> { fn parameter_length_exprs(url: &[PathPart<'a>]) -> Vec { url.iter() .filter_map(|p| match *p { - PathPart::Param(p) => { - Some(syn::ExprKind::MethodCall(ident("len"), - vec![], - vec![syn::ExprKind::Path(None, path_none(p)).into()]) - .into()) - } + PathPart::Param(p) => Some( + syn::ExprKind::MethodCall( + ident("len"), + vec![], + vec![syn::ExprKind::Path(None, path_none(p)).into()], + ).into(), + ), _ => None, }) .collect() @@ -198,28 +199,34 @@ impl<'a> UrlReplaceBuilder<'a> { let first_expr = Box::new(len_iter.next().unwrap()); - *(len_iter.map(|p| Box::new(p)) - .fold(first_expr, - |acc, p| Box::new(syn::ExprKind::Binary(syn::BinOp::Add, acc, p).into()))) + *(len_iter.map(|p| Box::new(p)).fold(first_expr, |acc, p| { + Box::new(syn::ExprKind::Binary(syn::BinOp::Add, acc, p).into()) + })) } } } /// Get a statement to build a `String` with a capacity of the given expression. fn let_url_stmt(url_ident: syn::Ident, len_expr: syn::Expr) -> syn::Stmt { - let string_with_capacity = syn::ExprKind::Call(Box::new(syn::ExprKind::Path(None, { - let mut method = path_none("String"); - method.segments.push(syn::PathSegment::from("with_capacity")); - method - }) - .into()), - vec![len_expr]) - .into(); + let string_with_capacity = syn::ExprKind::Call( + Box::new( + syn::ExprKind::Path(None, { + let mut method = path_none("String"); + method + .segments + .push(syn::PathSegment::from("with_capacity")); + method + }).into(), + ), + vec![len_expr], + ).into(); syn::Stmt::Local(Box::new(syn::Local { - pat: Box::new(syn::Pat::Ident(syn::BindingMode::ByValue(syn::Mutability::Mutable), - url_ident.to_owned(), - None)), + pat: Box::new(syn::Pat::Ident( + syn::BindingMode::ByValue(syn::Mutability::Mutable), + url_ident.to_owned(), + None, + )), ty: None, init: Some(Box::new(string_with_capacity)), attrs: vec![], @@ -238,18 +245,18 @@ impl<'a> UrlReplaceBuilder<'a> { PathPart::Param(p) => { let ident = ident(p); - syn::Stmt::Semi(Box::new(parse_expr(quote!(#url_ident.push_str(#ident.as_ref()))))) + syn::Stmt::Semi(Box::new( + parse_expr(quote!(#url_ident.push_str(#ident.as_ref()))), + )) } }) .collect() } pub fn build(self) -> syn::Block { - let has_params = self.url.iter().any(|p| { - match *p { - PathPart::Param(_) => true, - _ => false, - } + let has_params = self.url.iter().any(|p| match *p { + PathPart::Param(_) => true, + _ => false, }); if has_params { @@ -291,8 +298,7 @@ impl UrlMethodBuilder { let (generics, fngenerics) = { if self.params_ty.has_lifetime() { (generics_a(), generics_none()) - } - else { + } else { (generics_none(), generics_a()) } }; @@ -302,26 +308,32 @@ impl UrlMethodBuilder { vis: syn::Visibility::Public, defaultness: syn::Defaultness::Final, attrs: vec![], - node: syn::ImplItemKind::Method(syn::MethodSig { - unsafety: syn::Unsafety::Normal, - constness: syn::Constness::NotConst, - abi: None, - decl: fndecl, - generics: fngenerics, - }, - syn::Block { stmts: vec![self.body.into_stmt()] }), + node: syn::ImplItemKind::Method( + syn::MethodSig { + unsafety: syn::Unsafety::Normal, + constness: syn::Constness::NotConst, + abi: None, + decl: fndecl, + generics: fngenerics, + }, + syn::Block { + stmts: vec![self.body.into_stmt()], + }, + ), }; syn::Item { ident: ident(""), vis: syn::Visibility::Public, attrs: vec![], - node: syn::ItemKind::Impl(syn::Unsafety::Normal, - syn::ImplPolarity::Positive, - generics, - None, - Box::new(self.params_ty), - vec![item]), + node: syn::ItemKind::Impl( + syn::Unsafety::Normal, + syn::ImplPolarity::Positive, + generics, + None, + Box::new(self.params_ty), + vec![item], + ), } } } @@ -331,7 +343,8 @@ impl<'a> From<(&'a (String, Endpoint), &'a (syn::Item, syn::Ty))> for UrlMethodB let (&(_, ref endpoint), params) = value; let &(_, ref params_ty) = params; - let bodies: Vec = endpoint.url + let bodies: Vec = endpoint + .url .paths .iter() .map(|p| UrlReplaceBuilder::new(p.split()).build()) @@ -361,17 +374,16 @@ mod tests { let bodies = vec![ syn::Block { stmts: vec![] }, syn::Block { stmts: vec![] }, - syn::Block { stmts: vec![] } + syn::Block { stmts: vec![] }, ]; let result = UrlParamMatchBuilder::from((¶ms, bodies)).build(); - let expected = quote!( - match self { - RequestParams::None => {} - RequestParams::Index(ref index) => {} - RequestParams::IndexTypeId(ref index, ref ty, ref id) => {} - }); + let expected = quote!(match self { + RequestParams::None => {} + RequestParams::Index(ref index) => {} + RequestParams::IndexTypeId(ref index, ref ty, ref id) => {} + }); ast_eq(expected, result); } @@ -380,9 +392,7 @@ mod tests { fn gen_url_no_params() { let result = UrlReplaceBuilder::from(vec![PathPart::Literal("/_search")]).build(); - let expected = quote!({ - Url::from("/_search") - }); + let expected = quote!({ Url::from("/_search") }); ast_eq(expected, result); } @@ -393,9 +403,8 @@ mod tests { PathPart::Literal("/"), PathPart::Param("index"), PathPart::Literal("/_search/"), - PathPart::Param("type") - ]) - .build(); + PathPart::Param("type"), + ]).build(); let expected = quote!({ let mut url = String::with_capacity(10usize + index.len() + ty.len()); @@ -429,16 +438,20 @@ mod tests { #[test] fn gen_url_with_params_from_endpoint() { - use ::parse::*; - use ::gen::url_params::*; - - let endpoint = ("indices.exists_alias".to_string(), - Endpoint { - documentation: String::new(), - methods: vec![HttpMethod::Get], - url: get_url(), - body: Some(Body { description: String::new() }), - }); + use parse::*; + use gen::url_params::*; + + let endpoint = ( + "indices.exists_alias".to_string(), + Endpoint { + documentation: String::new(), + methods: vec![HttpMethod::Get], + url: get_url(), + body: Some(Body { + description: String::new(), + }), + }, + ); let params = UrlParamBuilder::from(&endpoint).build(); let result = UrlMethodBuilder::from((&endpoint, ¶ms)).build(); diff --git a/src/requests_codegen/src/gen/url_params.rs b/src/requests_codegen/src/gen/url_params.rs index 4dec643804..ff10a71f7a 100644 --- a/src/requests_codegen/src/gen/url_params.rs +++ b/src/requests_codegen/src/gen/url_params.rs @@ -1,6 +1,6 @@ use inflector::Inflector; use syn; -use ::parse; +use parse; use super::helpers::*; /// Builder for request url parameters enum. @@ -33,9 +33,7 @@ impl UrlParamBuilder { _ => { self.has_lifetime = true; - let cased: Vec = params.iter() - .map(|i| i.to_pascal_case()) - .collect(); + let cased: Vec = params.iter().map(|i| i.to_pascal_case()).collect(); let name = cased.join(""); @@ -54,16 +52,19 @@ impl UrlParamBuilder { ident: ident(name), attrs: vec![], discriminant: None, - data: syn::VariantData::Tuple(params.iter() - .map(|param| { - syn::Field { - ident: None, - vis: syn::Visibility::Inherited, - attrs: vec![], - ty: ty_a(param.as_ref()), - } - }) - .collect()), + data: syn::VariantData::Tuple( + params + .iter() + .map(|param| { + syn::Field { + ident: None, + vis: syn::Visibility::Inherited, + attrs: vec![], + ty: ty_a(param.as_ref()), + } + }) + .collect(), + ), } } @@ -87,8 +88,7 @@ impl UrlParamBuilder { let (ty, generics) = { if self.has_lifetime { (ty_a(self.name.as_ref()), generics_a()) - } - else { + } else { (ty(self.name.as_ref()), generics_none()) } }; @@ -160,15 +160,17 @@ mod tests { #[test] fn gen_params_enum_from_endpoint() { - use ::parse::*; - - let endpoint = ("indices.exists_alias".to_string(), - Endpoint { - documentation: String::new(), - methods: vec![HttpMethod::Get], - url: get_url(), - body: None, - }); + use parse::*; + + let endpoint = ( + "indices.exists_alias".to_string(), + Endpoint { + documentation: String::new(), + methods: vec![HttpMethod::Get], + url: get_url(), + body: None, + }, + ); let (result, _) = UrlParamBuilder::from(&endpoint).build(); diff --git a/src/requests_codegen/src/main.rs b/src/requests_codegen/src/main.rs index 2828d227cc..a02c7db3fc 100644 --- a/src/requests_codegen/src/main.rs +++ b/src/requests_codegen/src/main.rs @@ -1,17 +1,17 @@ -#![recursion_limit="200"] +#![recursion_limit = "200"] #[cfg(test)] #[macro_use] extern crate json_str; +extern crate serde; #[macro_use] extern crate serde_derive; -extern crate serde; extern crate serde_json; -extern crate syn; #[macro_use] extern crate quote; +extern crate syn; extern crate inflector; @@ -20,7 +20,7 @@ pub mod gen; use std::collections::BTreeMap; use std::io::{stdout, Read, Write}; -use std::fs::{File, read_dir}; +use std::fs::{read_dir, File}; use quote::Tokens; use parse::*; @@ -45,7 +45,7 @@ fn main() { .add_simple_search() .add_get_ping_req(); - endpoints = endpoints + endpoints = endpoints .into_iter() .map(|e| strip_verbs(e)) .map(|e| dedup_urls(e)) @@ -53,17 +53,23 @@ fn main() { let http_mod_name = "http"; - build_mod("endpoints", &mut tokens, - |ref mut tokens| endpoints_mod(tokens, derives.clone(), http_mod_name, endpoints, &mut params_to_emit) - ); + build_mod("endpoints", &mut tokens, |ref mut tokens| { + endpoints_mod( + tokens, + derives.clone(), + http_mod_name, + endpoints, + &mut params_to_emit, + ) + }); - build_mod(http_mod_name, &mut tokens, - |ref mut tokens| http_mod(tokens, derives.clone()) - ); + build_mod(http_mod_name, &mut tokens, |ref mut tokens| { + http_mod(tokens, derives.clone()) + }); - build_mod("params", &mut tokens, - |ref mut tokens| params_mod(tokens, derives.clone(), params_to_emit) - ); + build_mod("params", &mut tokens, |ref mut tokens| { + params_mod(tokens, derives.clone(), params_to_emit) + }); end_comment_block_for_logging(); @@ -97,10 +103,10 @@ fn from_dir(path: &str) -> Result, String> { } fn from_reader(name: String, rdr: &mut R) -> Result<(String, Endpoint), String> - where R: Read +where + R: Read, { - let endpoint: BTreeMap = try!(serde_json::from_reader(rdr) - .map_err(|e| format!("Failed to parse {} because: {}", name, e))); + let endpoint: BTreeMap = try!(serde_json::from_reader(rdr).map_err(|e| format!("Failed to parse {} because: {}", name, e))); Ok(endpoint.endpoint()) } @@ -113,13 +119,11 @@ fn strip_verbs(endpoint: (String, Endpoint)) -> (String, Endpoint) { let verb = match iter.len() { 0 => unreachable!(), 1 => iter.next().unwrap(), - _ => { - if iter.any(|m| m == HttpMethod::Post) { - HttpMethod::Post - } else { - iter.next().unwrap() - } - } + _ => if iter.any(|m| m == HttpMethod::Post) { + HttpMethod::Post + } else { + iter.next().unwrap() + }, }; endpoint.methods = vec![verb]; @@ -138,9 +142,7 @@ fn dedup_urls(endpoint: (String, Endpoint)) -> (String, Endpoint) { deduped_paths.insert(key, path); } - endpoint.url.paths = deduped_paths.into_iter() - .map(|(_, p)| p) - .collect(); + endpoint.url.paths = deduped_paths.into_iter().map(|(_, p)| p).collect(); (name, endpoint) } @@ -162,8 +164,8 @@ impl CustomEndpoints for Vec<(String, Endpoint)> { endpoints.push((String::from("simple_search"), simple_search_endpoint)); endpoints.push((String::from("search"), endpoint)); - }, - _ => endpoints.push((name, endpoint)) + } + _ => endpoints.push((name, endpoint)), } endpoints @@ -180,8 +182,8 @@ impl CustomEndpoints for Vec<(String, Endpoint)> { endpoints.push((String::from("ping"), get_endpoint)); endpoints.push((String::from("ping_head"), endpoint)); - }, - _ => endpoints.push((name, endpoint)) + } + _ => endpoints.push((name, endpoint)), } endpoints @@ -192,7 +194,7 @@ impl CustomEndpoints for Vec<(String, Endpoint)> { fn endpoints_mod(tokens: &mut Tokens, derives: Tokens, http_mod: &'static str, endpoints: Vec<(String, Endpoint)>, params_to_emit: &mut BTreeMap) { let mut http_mod_tokens = Tokens::new(); http_mod_tokens.append(http_mod); - + let uses = quote!( use super:: #http_mod_tokens ::*; use super::params::*; @@ -209,19 +211,13 @@ fn endpoints_mod(tokens: &mut Tokens, derives: Tokens, http_mod: &'static str, e let url_params = gen::url_params::UrlParamBuilder::from(&e).build(); let (ref url_params_item, _) = url_params; - let (req_params_item, req_params_ty) = - gen::request_params::RequestParamBuilder::from(&e).build(); + let (req_params_item, req_params_ty) = gen::request_params::RequestParamBuilder::from(&e).build(); - let req_ctors_item = - gen::request_ctors::RequestParamsCtorBuilder::from((&e, &req_params_ty, &url_params)) - .build(); + let req_ctors_item = gen::request_ctors::RequestParamsCtorBuilder::from((&e, &req_params_ty, &url_params)).build(); - let url_method_item = - gen::url_builder::UrlMethodBuilder::from((&e, &url_params)).build(); + let url_method_item = gen::url_builder::UrlMethodBuilder::from((&e, &url_params)).build(); - let req_into_http_item = - gen::request_into_http::RequestIntoHttpRequestBuilder::from((&e, &req_params_ty)) - .build(); + let req_into_http_item = gen::request_into_http::RequestIntoHttpRequestBuilder::from((&e, &req_params_ty)).build(); tokens.append_all(vec![ derives.clone(), @@ -230,7 +226,7 @@ fn endpoints_mod(tokens: &mut Tokens, derives: Tokens, http_mod: &'static str, e derives.clone(), quote!(#req_params_item), quote!(#req_ctors_item), - quote!(#req_into_http_item) + quote!(#req_into_http_item), ]); } } @@ -254,11 +250,11 @@ fn http_mod(tokens: &mut Tokens, derives: Tokens) { tokens.append_all(vec![ derives.clone(), url_tokens, - body_tokens, + body_tokens, derives.clone(), - http_req_item, + http_req_item, derives.clone(), - quote!(#http_method_item) + quote!(#http_method_item), ]); } @@ -273,23 +269,20 @@ fn params_mod(tokens: &mut Tokens, derives: Tokens, params_to_emit: BTreeMap(mod_name: &'static str, tokens: &mut Tokens, bldr: F) - where F: FnOnce(&mut Tokens) -> () +fn build_mod(mod_name: &'static str, tokens: &mut Tokens, bldr: F) +where + F: FnOnce(&mut Tokens) -> (), { tokens.append(&format!("pub mod {} {{", mod_name)); diff --git a/src/requests_codegen/src/parse/mod.rs b/src/requests_codegen/src/parse/mod.rs index cf670796f2..601778176b 100644 --- a/src/requests_codegen/src/parse/mod.rs +++ b/src/requests_codegen/src/parse/mod.rs @@ -23,34 +23,29 @@ pub struct Endpoint { impl Endpoint { pub fn has_body(&self) -> bool { - self.body.is_some() || self.methods.iter().any(|m| m == &HttpMethod::Post || m == &HttpMethod::Put) + self.body.is_some() || + self.methods + .iter() + .any(|m| m == &HttpMethod::Post || m == &HttpMethod::Put) } } #[derive(Debug, PartialEq, Deserialize, Clone, Copy)] pub enum HttpMethod { - #[serde(rename = "HEAD")] - Head, - #[serde(rename = "GET")] - Get, - #[serde(rename = "POST")] - Post, - #[serde(rename = "PUT")] - Put, - #[serde(rename = "PATCH")] - Patch, - #[serde(rename = "DELETE")] - Delete, + #[serde(rename = "HEAD")] Head, + #[serde(rename = "GET")] Get, + #[serde(rename = "POST")] Post, + #[serde(rename = "PUT")] Put, + #[serde(rename = "PATCH")] Patch, + #[serde(rename = "DELETE")] Delete, } #[derive(Debug, PartialEq, Deserialize, Clone)] pub struct Url { pub path: Path, pub paths: Vec, - #[serde(default = "BTreeMap::new")] - pub parts: BTreeMap, - #[serde(default = "BTreeMap::new")] - pub params: BTreeMap, + #[serde(default = "BTreeMap::new")] pub parts: BTreeMap, + #[serde(default = "BTreeMap::new")] pub params: BTreeMap, } impl Url { @@ -61,38 +56,25 @@ impl Url { #[derive(Debug, PartialEq, Deserialize, Clone)] pub struct Type { - #[serde(rename = "type", default)] - pub ty: TypeKind, + #[serde(rename = "type", default)] pub ty: TypeKind, pub description: String, - #[serde(default = "Vec::new")] - pub options: Vec, - #[serde(default)] - pub default: Option, + #[serde(default = "Vec::new")] pub options: Vec, + #[serde(default)] pub default: Option, } #[derive(Debug, PartialEq, Deserialize, Clone)] pub enum TypeKind { None, - #[serde(rename = "list")] - List, - #[serde(rename = "enum")] - Enum, - #[serde(rename = "string")] - String, - #[serde(rename = "text")] - Text, - #[serde(rename = "boolean")] - Boolean, - #[serde(rename = "number")] - Number, - #[serde(rename = "float")] - Float, - #[serde(rename = "integer")] - Integer, - #[serde(rename = "time")] - Time, - #[serde(rename = "duration")] - Duration, + #[serde(rename = "list")] List, + #[serde(rename = "enum")] Enum, + #[serde(rename = "string")] String, + #[serde(rename = "text")] Text, + #[serde(rename = "boolean")] Boolean, + #[serde(rename = "number")] Number, + #[serde(rename = "float")] Float, + #[serde(rename = "integer")] Integer, + #[serde(rename = "time")] Time, + #[serde(rename = "duration")] Duration, } impl Default for TypeKind { @@ -112,11 +94,9 @@ impl Path { pub fn params<'a>(&'a self) -> Vec<&'a str> { self.split() .iter() - .filter_map(|p| { - match *p { - PathPart::Param(p) => Some(p), - _ => None, - } + .filter_map(|p| match *p { + PathPart::Param(p) => Some(p), + _ => None, }) .collect() } @@ -187,11 +167,9 @@ pub trait PathParams<'a> { impl<'a> PathParams<'a> for Vec> { fn params(&'a self) -> Vec<&'a str> { self.iter() - .filter_map(|p| { - match *p { - PathPart::Param(p) => Some(p), - _ => None, - } + .filter_map(|p| match *p { + PathPart::Param(p) => Some(p), + _ => None, }) .collect() } @@ -206,38 +184,48 @@ pub struct Body { pub fn get_url() -> Url { Url { path: Path("/_search".to_string()), - paths: vec![Path("/_search".to_string()), Path("/{index}/_search".to_string()), Path("/{index}/{type}/_search".to_string())], + paths: vec![ + Path("/_search".to_string()), + Path("/{index}/_search".to_string()), + Path("/{index}/{type}/_search".to_string()), + ], parts: { let mut map = BTreeMap::new(); - map.insert("index".to_string(), - Type { - ty: TypeKind::List, - description: "A comma-separated list of index names to search".to_string(), - options: vec![], - default: None, - }); - - map.insert("type".to_string(), - Type { - ty: TypeKind::List, - description: "A comma-separated list of document types to search".to_string(), - options: vec![], - default: None, - }); + map.insert( + "index".to_string(), + Type { + ty: TypeKind::List, + description: "A comma-separated list of index names to search".to_string(), + options: vec![], + default: None, + }, + ); + + map.insert( + "type".to_string(), + Type { + ty: TypeKind::List, + description: "A comma-separated list of document types to search".to_string(), + options: vec![], + default: None, + }, + ); map }, params: { let mut map = BTreeMap::new(); - map.insert("analyzer".to_string(), - Type { - ty: TypeKind::String, - description: "The analyzer to use for the query string".to_string(), - options: vec![], - default: None, - }); + map.insert( + "analyzer".to_string(), + Type { + ty: TypeKind::String, + description: "The analyzer to use for the query string".to_string(), + options: vec![], + default: None, + }, + ); map }, @@ -247,7 +235,7 @@ pub fn get_url() -> Url { #[cfg(test)] mod tests { mod path { - use ::parse::{Path, PathPart}; + use parse::{Path, PathPart}; #[test] fn parse_param_only() { @@ -262,7 +250,11 @@ mod tests { fn parse_param_first() { let path = Path("{index}/{type}".to_string()); - let expected = vec![PathPart::Param("index"), PathPart::Literal("/"), PathPart::Param("type")]; + let expected = vec![ + PathPart::Param("index"), + PathPart::Literal("/"), + PathPart::Param("type"), + ]; assert_eq!(expected, path.split()); } @@ -271,7 +263,12 @@ mod tests { fn parse_params_and_literals() { let path = Path("/{index}/part/{type}".to_string()); - let expected = vec![PathPart::Literal("/"), PathPart::Param("index"), PathPart::Literal("/part/"), PathPart::Param("type")]; + let expected = vec![ + PathPart::Literal("/"), + PathPart::Param("index"), + PathPart::Literal("/part/"), + PathPart::Param("type"), + ]; assert_eq!(expected, path.split()); } @@ -296,7 +293,7 @@ mod tests { } mod endpoint { - use ::parse::*; + use parse::*; #[test] fn has_body_if_body_is_some() { @@ -304,7 +301,9 @@ mod tests { documentation: String::new(), methods: vec![HttpMethod::Get], url: get_url(), - body: Some(Body { description: String::new() }), + body: Some(Body { + description: String::new(), + }), }; assert!(endpoint.has_body()); @@ -348,7 +347,7 @@ mod tests { } mod url { - use ::parse::*; + use parse::*; #[test] fn lookup_param_type_in_part() { @@ -387,7 +386,7 @@ mod tests { use std::collections::BTreeMap; use serde_json; use serde_json::value::to_value; - use ::parse::*; + use parse::*; fn http_eq(expected: HttpMethod, ser: &'static str) { assert_eq!(expected, serde_json::from_str::(ser).unwrap()); @@ -450,7 +449,7 @@ mod tests { let expected = Type { ty: TypeKind::Enum, description: "The default operator for query string query (AND or OR)".to_string(), - options: vec![ to_value("AND").unwrap(), to_value("OR").unwrap() ], + options: vec![to_value("AND").unwrap(), to_value("OR").unwrap()], default: Some(to_value("OR").unwrap()), }; @@ -463,16 +462,24 @@ mod tests { "description": "The search definition using the Query DSL" }); - let expected = Some(Body { description: "The search definition using the Query DSL".to_string() }); + let expected = Some(Body { + description: "The search definition using the Query DSL".to_string(), + }); - assert_eq!(expected, serde_json::from_str::>(&ser).unwrap()); + assert_eq!( + expected, + serde_json::from_str::>(&ser).unwrap() + ); } #[test] fn deserialise_body_none() { let expected: Option = None; - assert_eq!(expected, serde_json::from_str::>("null").unwrap()); + assert_eq!( + expected, + serde_json::from_str::>("null").unwrap() + ); } #[test] @@ -503,39 +510,45 @@ mod tests { paths: vec![ Path("/_search".to_string()), Path("/{index}/_search".to_string()), - Path("/{index}/{type}/_search".to_string()) + Path("/{index}/{type}/_search".to_string()), ], parts: { let mut map = BTreeMap::new(); - map.insert("index".to_string(), - Type { - ty: TypeKind::List, - description: "A comma-separated list of index names to search".to_string(), - options: vec![], - default: None, - }); - - map.insert("type".to_string(), - Type { - ty: TypeKind::List, - description: "A comma-separated list of document types to search".to_string(), - options: vec![], - default: None, - }); + map.insert( + "index".to_string(), + Type { + ty: TypeKind::List, + description: "A comma-separated list of index names to search".to_string(), + options: vec![], + default: None, + }, + ); + + map.insert( + "type".to_string(), + Type { + ty: TypeKind::List, + description: "A comma-separated list of document types to search".to_string(), + options: vec![], + default: None, + }, + ); map }, params: { let mut map = BTreeMap::new(); - map.insert("analyzer".to_string(), - Type { - ty: TypeKind::String, - description: "The analyzer to use for the query string".to_string(), - options: vec![], - default: None, - }); + map.insert( + "analyzer".to_string(), + Type { + ty: TypeKind::String, + description: "The analyzer to use for the query string".to_string(), + options: vec![], + default: None, + }, + ); map }, @@ -563,18 +576,22 @@ mod tests { }); let mut expected = BTreeMap::new(); - expected.insert("search".to_string(), - Endpoint { - documentation: "http://www.elastic.co/guide/en/elasticsearch/reference/master/search-search.html".to_string(), - methods: vec![ HttpMethod::Get, HttpMethod::Post ], - url: Url { - path: Path("/_search".to_string()), - paths: vec![], - parts: BTreeMap::new(), - params: BTreeMap::new(), - }, - body: Some(Body { description: "The search definition using the Query DSL".to_string() }), - }); + expected.insert( + "search".to_string(), + Endpoint { + documentation: "http://www.elastic.co/guide/en/elasticsearch/reference/master/search-search.html".to_string(), + methods: vec![HttpMethod::Get, HttpMethod::Post], + url: Url { + path: Path("/_search".to_string()), + paths: vec![], + parts: BTreeMap::new(), + params: BTreeMap::new(), + }, + body: Some(Body { + description: "The search definition using the Query DSL".to_string(), + }), + }, + ); let de: BTreeMap = serde_json::from_str(&ser).unwrap(); diff --git a/src/requests_codegen/src/parse/parse.rs b/src/requests_codegen/src/parse/parse.rs index 8590274829..956c24d13e 100644 --- a/src/requests_codegen/src/parse/parse.rs +++ b/src/requests_codegen/src/parse/parse.rs @@ -3,7 +3,8 @@ use std::str; pub fn shift_while(i: &[u8], f: F) -> &[u8] - where F: Fn(u8) -> bool +where + F: Fn(u8) -> bool, { let mut ctr = 0; for c in i { @@ -18,7 +19,8 @@ pub fn shift_while(i: &[u8], f: F) -> &[u8] } pub fn take_while(i: &[u8], f: F) -> (&[u8], &str) - where F: Fn(u8) -> bool +where + F: Fn(u8) -> bool, { let mut ctr = 0; @@ -34,7 +36,8 @@ pub fn take_while(i: &[u8], f: F) -> (&[u8], &str) } pub fn take_while1(i: &[u8], f: F) -> (&[u8], &str) - where F: Fn(u8) -> bool +where + F: Fn(u8) -> bool, { let mut ctr = 0; diff --git a/src/reqwest/src/async.rs b/src/reqwest/src/async.rs index c229207a58..a068cafa7d 100644 --- a/src/reqwest/src/async.rs +++ b/src/reqwest/src/async.rs @@ -4,14 +4,14 @@ use std::mem; use bytes::Bytes; use serde::de::DeserializeOwned; use serde_json::Value; -use reqwest::unstable::async::{Client, ClientBuilder, Decoder, RequestBuilder, Response, Body}; -use futures::{Future, Stream, Poll}; +use reqwest::unstable::async::{Body, Client, ClientBuilder, Decoder, RequestBuilder, Response}; +use futures::{Future, Poll, Stream}; use tokio_core::reactor::Handle; use private; use super::req::HttpRequest; -use super::res::parsing::{Parse, IsOk}; -use super::{Error, RequestParams, build_url, build_method}; +use super::res::parsing::{IsOk, Parse}; +use super::{build_method, build_url, Error, RequestParams}; /** Get a default `Client` and `RequestParams`. */ pub fn default(handle: &Handle) -> Result<(Client, RequestParams), Error> { @@ -95,8 +95,9 @@ pub trait AsyncElasticClient: private::Sealed { ``` */ fn elastic_req(&self, params: &RequestParams, req: I) -> Pending - where I: Into>, - B: Into; + where + I: Into>, + B: Into; } /** A future returned by calling `elastic_req`. */ @@ -105,7 +106,10 @@ pub struct Pending { } impl Pending { - fn new(fut: F) -> Self where F: Future + 'static { + fn new(fut: F) -> Self + where + F: Future + 'static, + { Pending { inner: Box::new(fut), } @@ -123,8 +127,9 @@ impl Future for Pending { /** Build an asynchronous `reqwest::RequestBuilder` from an Elasticsearch request. */ pub fn build_req(client: &Client, params: &RequestParams, req: I) -> RequestBuilder - where I: Into>, - B: Into +where + I: Into>, + B: Into, { let req = req.into(); @@ -146,8 +151,9 @@ pub fn build_req(client: &Client, params: &RequestParams, req: I) -> Reque impl AsyncElasticClient for Client { fn elastic_req(&self, params: &RequestParams, req: I) -> Pending - where I: Into>, - B: Into + where + I: Into>, + B: Into, { let mut req = build_req(&self, params, req); Pending::new(req.send().map_err(Into::into)) @@ -168,7 +174,10 @@ pub struct FromResponse { } impl FromResponse { - fn new(fut: F) -> Self where F: Future + 'static { + fn new(fut: F) -> Self + where + F: Future + 'static, + { FromResponse { inner: Box::new(fut), } @@ -193,10 +202,9 @@ impl AsyncFromResponse .concat2() .map_err(Into::into); - let de_future = body_future - .and_then(move |body| { - self.from_slice(status, body.as_ref()).map_err(Into::into) - }); + let de_future = body_future.and_then(move |body| { + self.from_slice(status, body.as_ref()).map_err(Into::into) + }); FromResponse::new(de_future) } @@ -266,9 +274,11 @@ mod tests { #[test] fn post_req() { let cli = Client::new(&core().handle()); - let req = build_req(&cli, - ¶ms(), - PercolateRequest::for_index_ty("idx", "ty", vec![])); + let req = build_req( + &cli, + ¶ms(), + PercolateRequest::for_index_ty("idx", "ty", vec![]), + ); let url = "eshost:9200/path/idx/ty/_percolate?pretty=true&q=*"; @@ -280,9 +290,11 @@ mod tests { #[test] fn put_req() { let cli = Client::new(&core().handle()); - let req = build_req(&cli, - ¶ms(), - IndicesCreateRequest::for_index("idx", vec![])); + let req = build_req( + &cli, + ¶ms(), + IndicesCreateRequest::for_index("idx", vec![]), + ); let url = "eshost:9200/path/idx?pretty=true&q=*"; diff --git a/src/reqwest/src/lib.rs b/src/reqwest/src/lib.rs index d38c963574..9b6b359826 100644 --- a/src/reqwest/src/lib.rs +++ b/src/reqwest/src/lib.rs @@ -215,16 +215,16 @@ A library for generating minified json strings from Rust syntax. #[macro_use] extern crate quick_error; +extern crate bytes; extern crate elastic_requests; extern crate elastic_responses; +extern crate futures; +extern crate reqwest; extern crate serde; -#[cfg_attr(test, macro_use)] +#[cfg_attr(test, macro_use)] extern crate serde_json; -extern crate reqwest; -extern crate url; -extern crate bytes; extern crate tokio_core; -extern crate futures; +extern crate url; mod private { pub trait Sealed {} @@ -233,8 +233,8 @@ mod private { pub mod sync; pub mod async; -pub use self::sync::{SyncElasticClient, SyncBody, SyncFromResponse}; -pub use self::async::{AsyncElasticClient, AsyncBody, AsyncFromResponse}; +pub use self::sync::{SyncBody, SyncElasticClient, SyncFromResponse}; +pub use self::async::{AsyncBody, AsyncElasticClient, AsyncFromResponse}; /** Request types. @@ -260,7 +260,7 @@ use std::sync::Arc; use std::collections::BTreeMap; use std::str; use reqwest::Error as ReqwestError; -use reqwest::header::{Header, Headers, ContentType}; +use reqwest::header::{ContentType, Header, Headers}; use url::form_urlencoded::Serializer; use self::res::error::ResponseError; @@ -275,14 +275,14 @@ quick_error! { from() description("http error") display("http error: {}", err) - cause(err) + cause(err) } /** A response error. */ Response(err: ResponseError) { from() description("response error") display("response error: {}", err) - cause(err) + cause(err) } #[doc(hidden)] __NonExhaustive @@ -339,12 +339,9 @@ let params = RequestParams::default() */ #[derive(Clone)] pub struct RequestParams { - /** Base url for Elasticsearch. */ - base_url: String, - /** Simple key-value store for url query params. */ - url_params: BTreeMap<&'static str, String>, - /** The complete set of headers that will be sent with the request. */ - headers_factory: Option>, + /** Base url for Elasticsearch. */ base_url: String, + /** Simple key-value store for url query params. */ url_params: BTreeMap<&'static str, String>, + /** The complete set of headers that will be sent with the request. */ headers_factory: Option>, } impl RequestParams { @@ -381,7 +378,8 @@ impl RequestParams { /** Set a request header. */ pub fn header(self, header: H) -> Self - where H: Header + Clone + where + H: Header + Clone, { self.headers(move |h| h.set(header.clone())) } @@ -395,7 +393,8 @@ impl RequestParams { Once we can depend on `http` this might go away. */ fn headers(mut self, headers_factory: F) -> Self - where F: Fn(&mut Headers) + Send + Sync + 'static + where + F: Fn(&mut Headers) + Send + Sync + 'static, { if let Some(old_headers_factory) = self.headers_factory { let headers_factory = move |mut headers: &mut Headers| { @@ -488,7 +487,7 @@ fn assert_sync() {} #[cfg(test)] mod tests { - use reqwest::header::{Referer, Authorization, ContentType}; + use reqwest::header::{Authorization, ContentType, Referer}; use super::*; #[test] @@ -516,8 +515,14 @@ mod tests { let headers = req.get_headers(); assert_eq!(Some(&ContentType::json()), headers.get::()); - assert_eq!(Some(&Referer::new("/People.html#tim")), headers.get::()); - assert_eq!(Some(&Authorization("let me in".to_owned())), headers.get::>()); + assert_eq!( + Some(&Referer::new("/People.html#tim")), + headers.get::() + ); + assert_eq!( + Some(&Authorization("let me in".to_owned())), + headers.get::>() + ); } #[test] @@ -541,8 +546,10 @@ mod tests { .url_param("pretty", true) .url_param("q", "*"); - assert_eq!((16, Some(String::from("?pretty=true&q=*"))), - req.get_url_qry()); + assert_eq!( + (16, Some(String::from("?pretty=true&q=*"))), + req.get_url_qry() + ); } #[test] diff --git a/src/reqwest/src/sync.rs b/src/reqwest/src/sync.rs index d06bbe1d34..8b5ef03d09 100644 --- a/src/reqwest/src/sync.rs +++ b/src/reqwest/src/sync.rs @@ -4,12 +4,12 @@ use std::io::Cursor; use std::fs::File; use serde::de::DeserializeOwned; use serde_json::Value; -use reqwest::{Client, ClientBuilder, RequestBuilder, Response, Body}; +use reqwest::{Body, Client, ClientBuilder, RequestBuilder, Response}; use private; use super::req::HttpRequest; -use super::res::parsing::{Parse, IsOk}; -use super::{Error, RequestParams, build_url, build_method}; +use super::res::parsing::{IsOk, Parse}; +use super::{build_method, build_url, Error, RequestParams}; /** Get a default `Client` and `RequestParams`. */ pub fn default() -> Result<(Client, RequestParams), Error> { @@ -96,14 +96,16 @@ pub trait SyncElasticClient: private::Sealed { ``` */ fn elastic_req(&self, params: &RequestParams, req: I) -> Result - where I: Into>, - B: Into; + where + I: Into>, + B: Into; } /** Build a synchronous `reqwest::RequestBuilder` from an Elasticsearch request. */ pub fn build_req(client: &Client, params: &RequestParams, req: I) -> RequestBuilder - where I: Into>, - B: Into +where + I: Into>, + B: Into, { let req = req.into(); @@ -125,8 +127,9 @@ pub fn build_req(client: &Client, params: &RequestParams, req: I) -> Reque impl SyncElasticClient for Client { fn elastic_req(&self, params: &RequestParams, req: I) -> Result - where I: Into>, - B: Into + where + I: Into>, + B: Into, { build_req(&self, params, req).send().map_err(Into::into) } @@ -150,7 +153,7 @@ impl SyncFromResponse for Parse { took: u64, errors: bool, - #[serde(deserialize_with = "deserialize_bulk_items")] - items: Vec>, + #[serde(deserialize_with = "deserialize_bulk_items")] items: Vec>, } impl BulkResponse { @@ -307,8 +306,7 @@ fn takes_default_response(res: BulkErrorsResponse) { pub struct BulkErrorsResponse { took: u64, errors: bool, - #[serde(deserialize_with = "deserialize_bulk_item_errors")] - items: Vec>, + #[serde(deserialize_with = "deserialize_bulk_item_errors")] items: Vec>, } impl IntoIterator for BulkErrorsResponse { @@ -431,17 +429,17 @@ impl OkItem { pub fn found(&self) -> bool { self.found.clone().unwrap_or(false) } - + /** The index for this item. */ pub fn index(&self) -> &TIndex { &self.index } - + /** The document type for this item. */ pub fn ty(&self) -> &TType { &self.ty } - + /** The document id for this item. */ pub fn id(&self) -> &TId { &self.id @@ -455,7 +453,7 @@ pub struct ErrorItem ErrorItem { @@ -468,12 +466,12 @@ impl ErrorItem { pub fn index(&self) -> &TIndex { &self.index } - + /** The document type for this item. */ pub fn ty(&self) -> &TType { &self.ty } - + /** The document id for this item. */ pub fn id(&self) -> &TId { &self.id @@ -481,19 +479,28 @@ impl ErrorItem { } impl fmt::Display for ErrorItem - where TIndex: fmt::Display + fmt::Debug, - TType: fmt::Display + fmt::Debug, - TId: fmt::Display + fmt::Debug +where + TIndex: fmt::Display + fmt::Debug, + TType: fmt::Display + fmt::Debug, + TId: fmt::Display + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "bulk item failed. Details: index: {}, type: {}, id: {}, inner error: {}", self.index, self.ty, self.id, self.err) - } -} - -impl Error for ErrorItem - where TIndex: fmt::Display + fmt::Debug, - TType: fmt::Display + fmt::Debug, - TId: fmt::Display + fmt::Debug + write!( + f, + "bulk item failed. Details: index: {}, type: {}, id: {}, inner error: {}", + self.index, + self.ty, + self.id, + self.err + ) + } +} + +impl Error for ErrorItem +where + TIndex: fmt::Display + fmt::Debug, + TType: fmt::Display + fmt::Debug, + TId: fmt::Display + fmt::Debug, { fn description(&self) -> &str { "bulk item failed" @@ -507,14 +514,10 @@ impl Error for ErrorItem /** The bulk action being performed. */ #[derive(Deserialize, Debug, Clone, Copy)] pub enum Action { - #[serde(rename = "index")] - Index, - #[serde(rename = "create")] - Create, - #[serde(rename = "update")] - Update, - #[serde(rename = "delete")] - Delete, + #[serde(rename = "index")] Index, + #[serde(rename = "create")] Create, + #[serde(rename = "update")] Update, + #[serde(rename = "delete")] Delete, } impl IsOk for BulkResponse { @@ -544,16 +547,11 @@ struct ItemDe { #[derive(Deserialize, Debug, Clone)] struct ItemDeInner { - #[serde(rename = "_index")] - index: TIndex, - #[serde(rename = "_type")] - ty: TType, - #[serde(rename = "_id")] - id: TId, - #[serde(rename = "_version")] - version: Option, - #[serde(rename = "_shards")] - shards: Option, + #[serde(rename = "_index")] index: TIndex, + #[serde(rename = "_type")] ty: TType, + #[serde(rename = "_id")] id: TId, + #[serde(rename = "_version")] version: Option, + #[serde(rename = "_shards")] shards: Option, created: Option, found: Option, status: u16, @@ -561,9 +559,10 @@ struct ItemDeInner { } impl<'de, TIndex, TType, TId> ItemDe - where TIndex: Deserialize<'de>, - TType: Deserialize<'de>, - TId: Deserialize<'de>, +where + TIndex: Deserialize<'de>, + TType: Deserialize<'de>, + TId: Deserialize<'de>, { fn into_err(self) -> Option> { match self.inner.error { @@ -572,17 +571,16 @@ impl<'de, TIndex, TType, TId> ItemDe index: self.inner.index, ty: self.inner.ty, id: self.inner.id, - err: err + err: err, }), - None => None + None => None, } } fn into_result(self) -> ItemResult { if self.inner.error.is_some() { Err(self.into_err().expect("expected an error")) - } - else { + } else { Ok(OkItem { action: self.action, index: self.inner.index, @@ -598,21 +596,24 @@ impl<'de, TIndex, TType, TId> ItemDe } impl<'de, TIndex, TType, TId> Deserialize<'de> for ItemDe - where TIndex: Deserialize<'de>, - TType: Deserialize<'de>, - TId: Deserialize<'de>, +where + TIndex: Deserialize<'de>, + TType: Deserialize<'de>, + TId: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> + where + D: Deserializer<'de>, { struct ItemDeVisitor { - _marker: PhantomData<(TIndex, TType, TId)> + _marker: PhantomData<(TIndex, TType, TId)>, } impl<'de, TIndex, TType, TId> Visitor<'de> for ItemDeVisitor - where TIndex: Deserialize<'de>, - TType: Deserialize<'de>, - TId: Deserialize<'de>, + where + TIndex: Deserialize<'de>, + TType: Deserialize<'de>, + TId: Deserialize<'de>, { type Value = ItemDe; @@ -621,111 +622,128 @@ impl<'de, TIndex, TType, TId> Deserialize<'de> for ItemDe } fn visit_map(self, mut visitor: V) -> Result - where V: MapAccess<'de> + where + V: MapAccess<'de>, { - let (action, inner) = visitor.next_entry()?.ok_or(V::Error::custom("expected at least one field"))?; + let (action, inner) = visitor + .next_entry()? + .ok_or(V::Error::custom("expected at least one field"))?; let result = ItemDe { action: action, - inner: inner + inner: inner, }; Ok(result) } } - deserializer.deserialize_any(ItemDeVisitor { _marker: PhantomData }) + deserializer.deserialize_any(ItemDeVisitor { + _marker: PhantomData, + }) } } fn deserialize_bulk_items<'de, D, TIndex, TType, TId>(deserializer: D) -> Result>, D::Error> - where D: Deserializer <'de>, - TIndex: Deserialize<'de>, - TType: Deserialize<'de>, - TId: Deserialize<'de> +where + D: Deserializer<'de>, + TIndex: Deserialize<'de>, + TType: Deserialize<'de>, + TId: Deserialize<'de>, { struct OkItemsVisitor { - _marker: PhantomData<(TIndex, TType, TId)>, + _marker: PhantomData<(TIndex, TType, TId)>, + } + + impl<'de, TIndex, TType, TId> Visitor<'de> for OkItemsVisitor + where + TIndex: Deserialize<'de>, + TType: Deserialize<'de>, + TId: Deserialize<'de>, + { + type Value = Vec>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") } - impl<'de, TIndex, TType, TId> Visitor<'de> for OkItemsVisitor - where TIndex: Deserialize<'de>, - TType: Deserialize<'de>, - TId: Deserialize<'de> + #[inline] + fn visit_unit(self) -> Result>, E> + where + E: DeError, { - type Value = Vec>; + Ok(vec![]) + } - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a sequence") - } + #[inline] + fn visit_seq(self, mut visitor: V) -> Result>, V::Error> + where + V: SeqAccess<'de>, + { + let mut values = Vec::with_capacity(cmp::min(visitor.size_hint().unwrap_or(0), 4096)); - #[inline] - fn visit_unit(self) -> Result>, E> - where E: DeError, - { - Ok(vec![]) + while let Some(value) = visitor.next_element::>()? { + values.push(value.into_result()); } - #[inline] - fn visit_seq(self, mut visitor: V) -> Result>, V::Error> - where V: SeqAccess<'de>, - { - let mut values = Vec::with_capacity(cmp::min(visitor.size_hint().unwrap_or(0), 4096)); - - while let Some(value) = visitor.next_element::>()? { - values.push(value.into_result()); - } - - Ok(values) - } + Ok(values) } + } - deserializer.deserialize_any(OkItemsVisitor { _marker: PhantomData }) + deserializer.deserialize_any(OkItemsVisitor { + _marker: PhantomData, + }) } fn deserialize_bulk_item_errors<'de, D, TIndex, TType, TId>(deserializer: D) -> Result>, D::Error> - where D: Deserializer <'de>, - TIndex: Deserialize<'de>, - TType: Deserialize<'de>, - TId: Deserialize<'de> +where + D: Deserializer<'de>, + TIndex: Deserialize<'de>, + TType: Deserialize<'de>, + TId: Deserialize<'de>, { struct BulkErrorItemsVisitor { - _marker: PhantomData<(TIndex, TType, TId)>, - } + _marker: PhantomData<(TIndex, TType, TId)>, + } - impl<'de, TIndex, TType, TId> Visitor<'de> for BulkErrorItemsVisitor - where TIndex: Deserialize<'de>, - TType: Deserialize<'de>, - TId: Deserialize<'de> - { - type Value = Vec>; + impl<'de, TIndex, TType, TId> Visitor<'de> for BulkErrorItemsVisitor + where + TIndex: Deserialize<'de>, + TType: Deserialize<'de>, + TId: Deserialize<'de>, + { + type Value = Vec>; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a sequence") - } + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } - #[inline] - fn visit_unit(self) -> Result>, E> - where E: DeError, - { - Ok(vec![]) - } + #[inline] + fn visit_unit(self) -> Result>, E> + where + E: DeError, + { + Ok(vec![]) + } - #[inline] - fn visit_seq(self, mut visitor: V) -> Result>, V::Error> - where V: SeqAccess<'de>, - { - let mut values = Vec::with_capacity(cmp::min(visitor.size_hint().unwrap_or(0), 4096)); + #[inline] + fn visit_seq(self, mut visitor: V) -> Result>, V::Error> + where + V: SeqAccess<'de>, + { + let mut values = Vec::with_capacity(cmp::min(visitor.size_hint().unwrap_or(0), 4096)); - while let Some(value) = visitor.next_element::>()? { - if let Some(value) = value.into_err() { - values.push(value); - } + while let Some(value) = visitor.next_element::>()? { + if let Some(value) = value.into_err() { + values.push(value); } - - Ok(values) } + + Ok(values) } + } - deserializer.deserialize_any(BulkErrorItemsVisitor { _marker: PhantomData }) -} \ No newline at end of file + deserializer.deserialize_any(BulkErrorItemsVisitor { + _marker: PhantomData, + }) +} diff --git a/src/responses/src/command.rs b/src/responses/src/command.rs index 51c1df6889..e154258260 100644 --- a/src/responses/src/command.rs +++ b/src/responses/src/command.rs @@ -2,13 +2,13 @@ Response types for a standard command. */ -use parsing::{IsOk, HttpResponseHead, ResponseBody, Unbuffered, MaybeOkResponse}; +use parsing::{HttpResponseHead, IsOk, MaybeOkResponse, ResponseBody, Unbuffered}; use error::*; /** A standard command acknowledgement response. */ #[derive(Deserialize, Debug, Clone)] pub struct CommandResponse { - acknowledged: bool + acknowledged: bool, } impl CommandResponse { diff --git a/src/responses/src/common.rs b/src/responses/src/common.rs index 652990712b..e0628d80c1 100644 --- a/src/responses/src/common.rs +++ b/src/responses/src/common.rs @@ -24,4 +24,4 @@ impl Shards { pub fn failed(&self) -> u32 { self.failed } -} \ No newline at end of file +} diff --git a/src/responses/src/error.rs b/src/responses/src/error.rs index 5ff185b196..8cee570b52 100644 --- a/src/responses/src/error.rs +++ b/src/responses/src/error.rs @@ -3,7 +3,7 @@ Error types from Elasticsearch */ use serde::{Deserialize, Deserializer}; -use serde_json::{Map, Value, Error as JsonError}; +use serde_json::{Error as JsonError, Map, Value}; use std::io::Error as IoError; quick_error! { @@ -82,7 +82,8 @@ macro_rules! error_key { impl<'de> Deserialize<'de> for ApiError { fn deserialize(deserializer: D) -> Result - where D: Deserializer<'de> + where + D: Deserializer<'de>, { let value = Map::deserialize(deserializer)?; @@ -114,12 +115,16 @@ impl From> for ApiError { "index_not_found_exception" => { let index = error_key!(obj[index]: |v| v.as_str()); - ApiError::IndexNotFound { index: index.into() } + ApiError::IndexNotFound { + index: index.into(), + } } "index_already_exists_exception" => { let index = error_key!(obj[index]: |v| v.as_str()); - ApiError::IndexAlreadyExists { index: index.into() } + ApiError::IndexAlreadyExists { + index: index.into(), + } } "parsing_exception" => { let line = error_key!(obj[line]: |v| v.as_u64()); diff --git a/src/responses/src/get.rs b/src/responses/src/get.rs index 0840538180..55aa335117 100644 --- a/src/responses/src/get.rs +++ b/src/responses/src/get.rs @@ -4,25 +4,19 @@ Response types for a [get document request](https://www.elastic.co/guide/en/elas use serde::de::DeserializeOwned; -use parsing::{IsOk, HttpResponseHead, ResponseBody, Unbuffered, MaybeOkResponse}; +use parsing::{HttpResponseHead, IsOk, MaybeOkResponse, ResponseBody, Unbuffered}; use error::*; /** Response for a [get document request](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html). */ #[derive(Deserialize, Debug)] pub struct GetResponse { - #[serde(rename = "_index")] - index: String, - #[serde(rename = "_type")] - ty: String, - #[serde(rename = "_id")] - id: String, - #[serde(rename = "_version")] - version: Option, + #[serde(rename = "_index")] index: String, + #[serde(rename = "_type")] ty: String, + #[serde(rename = "_id")] id: String, + #[serde(rename = "_version")] version: Option, found: bool, - #[serde(rename = "_source")] - source: Option, - #[serde(rename="_routing")] - routing: Option, + #[serde(rename = "_source")] source: Option, + #[serde(rename = "_routing")] routing: Option, } impl GetResponse { @@ -71,7 +65,8 @@ impl IsOk for GetResponse { // Check if the response contains a root 'error' node let (maybe_err, body) = body.body()?; - let is_ok = maybe_err.as_object() + let is_ok = maybe_err + .as_object() .and_then(|maybe_err| maybe_err.get("error")) .is_none(); diff --git a/src/responses/src/index.rs b/src/responses/src/index.rs index bc9dc006fc..8d266aa1d4 100644 --- a/src/responses/src/index.rs +++ b/src/responses/src/index.rs @@ -3,23 +3,18 @@ Response types for an [index document request](https://www.elastic.co/guide/en/e */ use common::Shards; -use parsing::{IsOk, HttpResponseHead, ResponseBody, Unbuffered, MaybeOkResponse}; +use parsing::{HttpResponseHead, IsOk, MaybeOkResponse, ResponseBody, Unbuffered}; use error::*; /** Response for an [index document request](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html). */ #[derive(Deserialize, Debug)] pub struct IndexResponse { - #[serde(rename = "_index")] - index: String, - #[serde(rename = "_type")] - ty: String, - #[serde(rename = "_id")] - id: String, - #[serde(rename = "_version")] - version: Option, + #[serde(rename = "_index")] index: String, + #[serde(rename = "_type")] ty: String, + #[serde(rename = "_id")] id: String, + #[serde(rename = "_version")] version: Option, created: bool, - #[serde(rename = "_shards")] - shards: Shards, + #[serde(rename = "_shards")] shards: Shards, } impl IndexResponse { diff --git a/src/responses/src/lib.rs b/src/responses/src/lib.rs index 4c1ea65c7b..1f3a55c317 100644 --- a/src/responses/src/lib.rs +++ b/src/responses/src/lib.rs @@ -137,8 +137,8 @@ extern crate quick_error; extern crate serde; extern crate serde_json; -extern crate slog_stdlog; extern crate slog_envlogger; +extern crate slog_stdlog; pub mod error; pub mod parsing; @@ -156,10 +156,10 @@ pub use self::command::*; pub use self::ping::*; pub use self::get::*; pub use self::search::SearchResponse; -pub use self::bulk::{BulkResponse, BulkErrorsResponse}; +pub use self::bulk::{BulkErrorsResponse, BulkResponse}; pub use self::index::*; pub use self::parsing::parse; /** Re-export of `serde_json::Value` for convenience. */ -pub use serde_json::Value; \ No newline at end of file +pub use serde_json::Value; diff --git a/src/responses/src/parsing.rs b/src/responses/src/parsing.rs index 3f6072f2c6..051b86fd8b 100644 --- a/src/responses/src/parsing.rs +++ b/src/responses/src/parsing.rs @@ -122,14 +122,14 @@ impl HttpResponseHead { impl From for HttpResponseHead { fn from(status: u16) -> Self { - HttpResponseHead { - code: status - } + HttpResponseHead { code: status } } } /** A http response body that can be buffered into a json value. */ -pub trait ResponseBody where Self: Sized +pub trait ResponseBody +where + Self: Sized, { /** The type of a buffered response body. */ type Buffered: ResponseBody; @@ -243,8 +243,7 @@ impl IsOk for MyResponse { } ``` */ -pub trait IsOk -{ +pub trait IsOk { /** Inspect the http response to determine whether or not it succeeded. */ fn is_ok(head: HttpResponseHead, unbuffered: Unbuffered) -> Result, ParseResponseError>; } @@ -259,21 +258,25 @@ impl IsOk for Value { } /** A response that might be successful or an `ApiError`. */ -pub struct MaybeOkResponse - where B: ResponseBody +pub struct MaybeOkResponse +where + B: ResponseBody, { ok: bool, res: MaybeBufferedResponse, } -impl MaybeOkResponse where B: ResponseBody +impl MaybeOkResponse +where + B: ResponseBody, { /** Create a new response that indicates where or not the body is successful or an `ApiError`. */ pub fn new(ok: bool, res: I) -> Self - where I: Into> + where + I: Into>, { MaybeOkResponse { ok: ok, @@ -283,14 +286,16 @@ impl MaybeOkResponse where B: ResponseBody /** Create a response where the body is successful. */ pub fn ok(res: I) -> Self - where I: Into> + where + I: Into>, { Self::new(true, res) } /** Create a resposne where the body is an error. */ pub fn err(res: I) -> Self - where I: Into> + where + I: Into>, { Self::new(false, res) } @@ -316,32 +321,35 @@ This type makes it possible to inspect the response body for an error type before passing it along to be deserialised properly. */ pub enum MaybeBufferedResponse - where B: ResponseBody +where + B: ResponseBody, { Unbuffered(B), Buffered(B::Buffered), } impl MaybeBufferedResponse - where B: ResponseBody +where + B: ResponseBody, { fn parse_ok(self) -> Result { match self { MaybeBufferedResponse::Unbuffered(b) => b.parse_ok(), - MaybeBufferedResponse::Buffered(b) => b.parse_ok() + MaybeBufferedResponse::Buffered(b) => b.parse_ok(), } } fn parse_err(self) -> Result { match self { MaybeBufferedResponse::Unbuffered(b) => b.parse_err(), - MaybeBufferedResponse::Buffered(b) => b.parse_err() + MaybeBufferedResponse::Buffered(b) => b.parse_err(), } } } impl From> for MaybeBufferedResponse - where B: ResponseBody +where + B: ResponseBody, { fn from(value: Unbuffered) -> Self { MaybeBufferedResponse::Unbuffered(value.0) @@ -349,7 +357,8 @@ impl From> for MaybeBufferedResponse } impl From> for MaybeBufferedResponse - where B: ResponseBody +where + B: ResponseBody, { fn from(value: Buffered) -> Self { MaybeBufferedResponse::Buffered(value.0) diff --git a/src/responses/src/ping.rs b/src/responses/src/ping.rs index bad1c2bbbf..d0d62b718f 100644 --- a/src/responses/src/ping.rs +++ b/src/responses/src/ping.rs @@ -2,7 +2,7 @@ Response types for a cluster ping request. */ -use parsing::{IsOk, HttpResponseHead, ResponseBody, Unbuffered, MaybeOkResponse}; +use parsing::{HttpResponseHead, IsOk, MaybeOkResponse, ResponseBody, Unbuffered}; use error::*; /** Response for a cluster ping request. */ @@ -21,7 +21,7 @@ pub struct ClusterVersion { build_hash: String, build_date: String, build_snapshot: bool, - lucene_version: String + lucene_version: String, } impl PingResponse { @@ -75,4 +75,4 @@ impl IsOk for PingResponse { _ => Ok(MaybeOkResponse::err(body)), } } -} \ No newline at end of file +} diff --git a/src/responses/src/search.rs b/src/responses/src/search.rs index 2477d338c3..98b7f7a50e 100644 --- a/src/responses/src/search.rs +++ b/src/responses/src/search.rs @@ -6,7 +6,7 @@ use serde::de::DeserializeOwned; use serde_json::{Map, Value}; use common::Shards; -use parsing::{IsOk, HttpResponseHead, ResponseBody, Unbuffered, MaybeOkResponse}; +use parsing::{HttpResponseHead, IsOk, MaybeOkResponse, ResponseBody, Unbuffered}; use error::*; use std::borrow::Cow; @@ -56,8 +56,7 @@ for hit in response.hits() { pub struct SearchResponse { took: u64, timed_out: bool, - #[serde(rename = "_shards")] - shards: Shards, + #[serde(rename = "_shards")] shards: Shards, hits: HitsWrapper, aggregations: Option, status: Option, @@ -68,8 +67,7 @@ pub struct SearchResponse { struct HitsWrapper { total: u64, max_score: Option, - #[serde(rename = "hits")] - inner: Vec>, + #[serde(rename = "hits")] inner: Vec>, } impl SearchResponse { @@ -154,7 +152,7 @@ pub struct Hits<'a, T: 'a> { impl<'a, T: 'a> Hits<'a, T> { fn new(hits: &'a HitsWrapper) -> Self { Hits { - inner: hits.inner.iter() + inner: hits.inner.iter(), } } } @@ -175,7 +173,7 @@ pub struct IntoHits { impl IntoHits { fn new(hits: HitsWrapper) -> Self { IntoHits { - inner: hits.inner.into_iter() + inner: hits.inner.into_iter(), } } } @@ -196,7 +194,7 @@ pub struct Documents<'a, T: 'a> { impl<'a, T: 'a> Documents<'a, T> { fn new(hits: &'a HitsWrapper) -> Self { Documents { - inner: hits.inner.iter() + inner: hits.inner.iter(), } } } @@ -217,7 +215,7 @@ pub struct IntoDocuments { impl IntoDocuments { fn new(hits: HitsWrapper) -> Self { IntoDocuments { - inner: hits.inner.into_iter() + inner: hits.inner.into_iter(), } } } @@ -233,18 +231,12 @@ impl Iterator for IntoDocuments { /** Full metadata and source for a single hit. */ #[derive(Deserialize, Debug)] pub struct Hit { - #[serde(rename = "_index")] - index: String, - #[serde(rename = "_type")] - ty: String, - #[serde(rename = "_version")] - version: Option, - #[serde(rename = "_score")] - score: Option, - #[serde(rename = "_source")] - source: Option, - #[serde(rename="_routing")] - routing: Option, + #[serde(rename = "_index")] index: String, + #[serde(rename = "_type")] ty: String, + #[serde(rename = "_version")] version: Option, + #[serde(rename = "_score")] score: Option, + #[serde(rename = "_source")] source: Option, + #[serde(rename = "_routing")] routing: Option, } impl Hit { @@ -297,16 +289,15 @@ impl<'a> Aggs<'a> { fn new(aggregations: Option<&'a AggsWrapper>) -> Aggs<'a> { let iter_stack = { match aggregations.and_then(|aggs| aggs.0.as_object()) { - Some(o) => { - o.into_iter() - .filter_map(|(key, child)| { - child.as_object() - .and_then(|child| child.get("buckets")) - .and_then(Value::as_array) - .map(|array| (key.as_ref(), array.iter())) - }) - .collect() - }, + Some(o) => o.into_iter() + .filter_map(|(key, child)| { + child + .as_object() + .and_then(|child| child.get("buckets")) + .and_then(Value::as_array) + .map(|array| (key.as_ref(), array.iter())) + }) + .collect(), None => Vec::new(), } }; @@ -314,7 +305,7 @@ impl<'a> Aggs<'a> { Aggs { current_row: None, current_row_finished: false, - iter_stack: iter_stack + iter_stack: iter_stack, } } } @@ -322,10 +313,7 @@ impl<'a> Aggs<'a> { type Object = Map; type RowData<'a> = BTreeMap, &'a Value>; -fn insert_value<'a>(fieldname: &str, - json_object: &'a Object, - keyname: &str, - rowdata: &mut RowData<'a>) { +fn insert_value<'a>(fieldname: &str, json_object: &'a Object, keyname: &str, rowdata: &mut RowData<'a>) { if let Some(v) = json_object.get(fieldname) { let field_name = format!("{}_{}", keyname, fieldname); debug!("ITER: Insert value! {} {:?}", field_name, v); @@ -384,19 +372,19 @@ impl<'a> Iterator for Aggs<'a> { insert_value("std_deviation", c, key, row); if c.contains_key("std_deviation_bounds") { - if let Some(child_values) = c.get("std_deviation_bounds") - .unwrap() - .as_object() { + if let Some(child_values) = c.get("std_deviation_bounds").unwrap().as_object() { let u = child_values.get("upper"); let l = child_values.get("lower"); let un = format!("{}_std_deviation_bounds_upper", key); let ln = format!("{}_std_deviation_bounds_lower", key); - debug!("ITER: Insert std_dev_bounds! {} {} u: {:?} l: \ - {:?}", - un, - ln, - u.unwrap(), - l.unwrap()); + debug!( + "ITER: Insert std_dev_bounds! {} {} u: {:?} l: \ + {:?}", + un, + ln, + u.unwrap(), + l.unwrap() + ); row.insert(Cow::Owned(un), u.unwrap()); row.insert(Cow::Owned(ln), l.unwrap()); } diff --git a/src/types/src/boolean/impls.rs b/src/types/src/boolean/impls.rs index a5b758e1f6..d2f9525bdc 100644 --- a/src/types/src/boolean/impls.rs +++ b/src/types/src/boolean/impls.rs @@ -1,7 +1,7 @@ use std::borrow::Borrow; use std::marker::PhantomData; -use serde::{Serialize, Deserialize, Serializer, Deserializer}; -use serde::de::{Visitor, Error}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde::de::{Error, Visitor}; use super::mapping::{BooleanFieldType, BooleanMapping, DefaultBooleanMapping}; impl BooleanFieldType for bool {} @@ -21,13 +21,17 @@ let boolean = Boolean::::new(true); ``` */ #[derive(Debug, Clone, Default, PartialEq)] -pub struct Boolean where TMapping: BooleanMapping { +pub struct Boolean +where + TMapping: BooleanMapping, +{ value: bool, _m: PhantomData, } impl Boolean - where TMapping: BooleanMapping +where + TMapping: BooleanMapping, { /** Creates a new `Boolean` with the given mapping. @@ -42,7 +46,8 @@ impl Boolean ``` */ pub fn new(boolean: I) -> Boolean - where I: Into + where + I: Into, { Boolean { value: boolean.into(), @@ -73,31 +78,40 @@ impl Boolean ``` */ pub fn remap(boolean: Boolean) -> Boolean - where TNewMapping: BooleanMapping + where + TNewMapping: BooleanMapping, { Boolean::::new(boolean.value) } } -impl BooleanFieldType for Boolean where TMapping: BooleanMapping {} +impl BooleanFieldType for Boolean +where + TMapping: BooleanMapping, +{ +} impl_mapping_type!(bool, Boolean, BooleanMapping); impl Serialize for Boolean - where TMapping: BooleanMapping +where + TMapping: BooleanMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_bool(self.value) } } impl<'de, TMapping> Deserialize<'de> for Boolean - where TMapping: BooleanMapping +where + TMapping: BooleanMapping, { fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> + where + D: Deserializer<'de>, { #[derive(Default)] struct BooleanVisitor { @@ -105,7 +119,8 @@ impl<'de, TMapping> Deserialize<'de> for Boolean } impl<'de, TMapping> Visitor<'de> for BooleanVisitor - where TMapping: BooleanMapping + where + TMapping: BooleanMapping, { type Value = Boolean; @@ -114,7 +129,8 @@ impl<'de, TMapping> Deserialize<'de> for Boolean } fn visit_bool(self, v: bool) -> Result, E> - where E: Error + where + E: Error, { Ok(Boolean::::new(v)) } diff --git a/src/types/src/boolean/mapping.rs b/src/types/src/boolean/mapping.rs index 492cd89dc3..4aa14a605e 100644 --- a/src/types/src/boolean/mapping.rs +++ b/src/types/src/boolean/mapping.rs @@ -64,7 +64,8 @@ This will produce the following mapping: ``` */ pub trait BooleanMapping - where Self: Default +where + Self: Default, { /** Field-level index time boosting. Accepts a floating point number, defaults to `1.0`. */ fn boost() -> Option { @@ -110,19 +111,22 @@ impl BooleanMapping for DefaultBooleanMapping {} mod private { use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; - use private::field::{FieldType, DocumentField, FieldMapping}; + use private::field::{DocumentField, FieldMapping, FieldType}; use super::{BooleanFieldType, BooleanMapping}; #[derive(Default)] pub struct BooleanPivot; impl FieldType for TField - where TMapping: BooleanMapping, - TField: BooleanFieldType + Serialize - { } + where + TMapping: BooleanMapping, + TField: BooleanFieldType + Serialize, + { + } impl FieldMapping for TMapping - where TMapping: BooleanMapping + where + TMapping: BooleanMapping, { type DocumentField = DocumentField; @@ -132,10 +136,12 @@ mod private { } impl Serialize for DocumentField - where TMapping: FieldMapping + BooleanMapping + where + TMapping: FieldMapping + BooleanMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 6)); @@ -157,7 +163,7 @@ mod tests { use serde_json; use prelude::*; - use private::field::{FieldType, DocumentField}; + use private::field::{DocumentField, FieldType}; #[derive(Default, Clone)] pub struct MyBooleanMapping; diff --git a/src/types/src/date/format.rs b/src/types/src/date/format.rs index 4ae7581535..82a6f88df4 100644 --- a/src/types/src/date/format.rs +++ b/src/types/src/date/format.rs @@ -1,10 +1,10 @@ -use chrono::{self, Utc, NaiveDateTime, NaiveDate, NaiveTime}; -use chrono::format::{Item, DelayedFormat}; +use chrono::{self, NaiveDate, NaiveDateTime, NaiveTime, Utc}; +use chrono::format::{DelayedFormat, Item}; use std::ops::Deref; use std::marker::PhantomData; use std::borrow::Borrow; use std::error::Error; -use std::fmt::{Display, Result as FmtResult, Formatter}; +use std::fmt::{Display, Formatter, Result as FmtResult}; use std::vec::IntoIter; use super::ChronoDateTime; @@ -91,7 +91,10 @@ You probably don't need to use it directly except to ensure date formats aren't #[derive(Debug, Clone, PartialEq)] pub struct FormattableDateValue(DateValue, PhantomData); -impl FormattableDateValue where TFormat: DateFormat { +impl FormattableDateValue +where + TFormat: DateFormat, +{ /** Format the wrapped date value using the generic format. */ pub fn format<'a>(&'a self) -> FormattedDate<'a> { TFormat::format(&self.0) @@ -184,7 +187,8 @@ struct MyFormat; ``` */ pub trait DateFormat - where Self: Default +where + Self: Default, { /** Parses a date string to a `chrono::DateTime` result. */ fn parse(date: &str) -> Result; @@ -218,7 +222,8 @@ enum FormattedDateInner<'a> { impl<'a> Display for FormattedDateInner<'a> { fn fmt(&self, f: &mut Formatter) -> FmtResult { fn fmt_inner(inner: &T, f: &mut Formatter) -> FmtResult - where T: Display + where + T: Display, { inner.fmt(f) } @@ -239,19 +244,25 @@ impl<'a> Display for FormattedDate<'a> { impl<'a> From>>> for FormattedDate<'a> { fn from(formatted: DelayedFormat>>) -> Self { - FormattedDate { inner: FormattedDateInner::Delayed(formatted) } + FormattedDate { + inner: FormattedDateInner::Delayed(formatted), + } } } impl<'a> From for FormattedDate<'a> { fn from(formatted: String) -> Self { - FormattedDate { inner: FormattedDateInner::Buffered(formatted) } + FormattedDate { + inner: FormattedDateInner::Buffered(formatted), + } } } impl<'a> From for FormattedDate<'a> { fn from(formatted: i64) -> Self { - FormattedDate { inner: FormattedDateInner::Number(formatted) } + FormattedDate { + inner: FormattedDateInner::Number(formatted), + } } } @@ -294,12 +305,16 @@ impl Error for ParseError { impl From for ParseError { fn from(err: chrono::ParseError) -> ParseError { - ParseError { kind: ParseErrorKind::Chrono(err) } + ParseError { + kind: ParseErrorKind::Chrono(err), + } } } impl From for ParseError { fn from(err: String) -> ParseError { - ParseError { kind: ParseErrorKind::Other(err) } + ParseError { + kind: ParseErrorKind::Other(err), + } } } diff --git a/src/types/src/date/formats.rs b/src/types/src/date/formats.rs index 7e5342af71..71f2d07936 100644 --- a/src/types/src/date/formats.rs +++ b/src/types/src/date/formats.rs @@ -1,5 +1,5 @@ use std::error::Error; -use chrono::{DateTime, Utc, NaiveDateTime, Timelike}; +use chrono::{DateTime, NaiveDateTime, Timelike, Utc}; use super::{DateFormat, DateValue, FormattedDate, ParseError}; /** The default `date` format (`BasicDateTime`). */ @@ -7,7 +7,7 @@ pub type DefaultDateFormat = BasicDateTime; /** Format for default `chrono::DateTime`. */ #[derive(ElasticDateFormat, PartialEq, Debug, Default, Clone, Copy)] -#[elastic(date_format="yyyy-MM-dd'T'HH:mm:ssZ")] +#[elastic(date_format = "yyyy-MM-dd'T'HH:mm:ssZ")] pub struct ChronoFormat; /** @@ -17,7 +17,7 @@ Format for `basic_date_time_no_millis`. - [Elasticsearch Doc](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-date-format.html#built-in-date-formats) */ #[derive(ElasticDateFormat, PartialEq, Debug, Default, Clone, Copy)] -#[elastic(date_format="yyyyMMdd'T'HHmmssZ", date_format_name="basic_date_time_no_millis")] +#[elastic(date_format = "yyyyMMdd'T'HHmmssZ", date_format_name = "basic_date_time_no_millis")] pub struct BasicDateTimeNoMillis; /** @@ -27,7 +27,7 @@ Format for `basic_date_time`. - [Elasticsearch Doc](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-date-format.html#built-in-date-formats) */ #[derive(ElasticDateFormat, PartialEq, Debug, Default, Clone, Copy)] -#[elastic(date_format="yyyyMMdd'T'HHmmss.SSSZ", date_format_name="basic_date_time")] +#[elastic(date_format = "yyyyMMdd'T'HHmmss.SSSZ", date_format_name = "basic_date_time")] pub struct BasicDateTime; /** diff --git a/src/types/src/date/impls.rs b/src/types/src/date/impls.rs index 7bdf8b7f84..48fbcaa29c 100644 --- a/src/types/src/date/impls.rs +++ b/src/types/src/date/impls.rs @@ -1,11 +1,11 @@ use std::borrow::Borrow; use std::ops::Deref; use std::marker::PhantomData; -use std::fmt::{Display, Result as FmtResult, Formatter}; +use std::fmt::{Display, Formatter, Result as FmtResult}; use chrono::{DateTime, Utc}; -use serde::{Serialize, Deserialize, Serializer, Deserializer}; -use serde::de::{Visitor, Error}; -use super::format::{DateValue, FormattableDateValue, DateFormat, FormattedDate, ParseError}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde::de::{Error, Visitor}; +use super::format::{DateFormat, DateValue, FormattableDateValue, FormattedDate, ParseError}; use super::formats::ChronoFormat; use super::mapping::{DateFieldType, DateMapping, DefaultDateMapping}; use private::field::StdField; @@ -68,11 +68,16 @@ println!("{}/{}/{} {}:{}:{}.{}", - [Elasticsearch Doc](https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html) */ #[derive(Debug, Clone, PartialEq)] -pub struct Date where TMapping: DateMapping { +pub struct Date +where + TMapping: DateMapping, +{ value: FormattableDateValue, } -impl Date where TMapping: DateMapping +impl Date +where + TMapping: DateMapping, { /** Creates a new `Date` from the given `chrono::DateTime`. @@ -127,12 +132,11 @@ impl Date where TMapping: DateMapping # } ``` */ - pub fn new(date: I) -> Self - where I: Into> + pub fn new(date: I) -> Self + where + I: Into>, { - Date { - value: date.into() - } + Date { value: date.into() } } /** @@ -144,7 +148,15 @@ impl Date where TMapping: DateMapping ``` */ pub fn build(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32, milli: u32) -> Self { - Date::new(DateValue::build(year, month, day, hour, minute, second, milli)) + Date::new(DateValue::build( + year, + month, + day, + hour, + minute, + second, + milli, + )) } /** @@ -176,37 +188,49 @@ impl Date where TMapping: DateMapping ``` */ pub fn remap(date: Date) -> Date - where TNewMapping: DateMapping + where + TNewMapping: DateMapping, { Date::new(DateValue::from(date.value)) } } impl DateFieldType for Date - where TMapping: DateMapping +where + TMapping: DateMapping, { } -impl From> for FormattableDateValue where TMapping: DateMapping { +impl From> for FormattableDateValue +where + TMapping: DateMapping, +{ fn from(date: Date) -> Self { date.value } } -impl From> for Date where TMapping: DateMapping { +impl From> for Date +where + TMapping: DateMapping, +{ fn from(date: FormattableDateValue) -> Self { Date::new(date) } } -impl From> for DateValue where TMapping: DateMapping { +impl From> for DateValue +where + TMapping: DateMapping, +{ fn from(date: Date) -> Self { date.value.into() } } -impl From for Date - where TMapping: DateMapping +impl From for Date +where + TMapping: DateMapping, { fn from(value: DateValue) -> Self { Date::new(value) @@ -214,12 +238,14 @@ impl From for Date } impl StdField for Date - where TMapping: DateMapping +where + TMapping: DateMapping, { } -impl PartialEq for Date - where TMapping: DateMapping +impl PartialEq for Date +where + TMapping: DateMapping, { fn eq(&self, other: &ChronoDateTime) -> bool { PartialEq::eq(&self.value, other) @@ -230,8 +256,9 @@ impl PartialEq for Date } } -impl PartialEq> for ChronoDateTime - where TMapping: DateMapping +impl PartialEq> for ChronoDateTime +where + TMapping: DateMapping, { fn eq(&self, other: &Date) -> bool { PartialEq::eq(self, &other.value) @@ -242,8 +269,9 @@ impl PartialEq> for ChronoDateTime } } -impl Deref for Date - where TMapping: DateMapping +impl Deref for Date +where + TMapping: DateMapping, { type Target = ChronoDateTime; fn deref(&self) -> &ChronoDateTime { @@ -251,8 +279,9 @@ impl Deref for Date } } -impl Borrow for Date - where TMapping: DateMapping +impl Borrow for Date +where + TMapping: DateMapping, { fn borrow(&self) -> &ChronoDateTime { self.value.borrow() @@ -260,7 +289,8 @@ impl Borrow for Date } impl Default for Date - where TMapping: DateMapping +where + TMapping: DateMapping, { fn default() -> Self { Date::now() @@ -268,7 +298,8 @@ impl Default for Date } impl Display for Date - where TMapping: DateMapping +where + TMapping: DateMapping, { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{}", format(self)) @@ -276,20 +307,24 @@ impl Display for Date } impl Serialize for Date - where TMapping: DateMapping +where + TMapping: DateMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.collect_str(&self) } } impl<'de, TMapping> Deserialize<'de> for Date - where TMapping: DateMapping +where + TMapping: DateMapping, { fn deserialize(deserializer: D) -> Result - where D: Deserializer<'de> + where + D: Deserializer<'de>, { #[derive(Default)] struct DateTimeVisitor { @@ -297,29 +332,35 @@ impl<'de, TMapping> Deserialize<'de> for Date } impl<'de, TMapping> Visitor<'de> for DateTimeVisitor - where TMapping: DateMapping + where + TMapping: DateMapping, { type Value = Date; fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - write!(formatter, - "a json string or number containing a formatted date") + write!( + formatter, + "a json string or number containing a formatted date" + ) } fn visit_str(self, v: &str) -> Result, E> - where E: Error + where + E: Error, { parse(v).map_err(|err| Error::custom(format!("{}", err))) } fn visit_i64(self, v: i64) -> Result, E> - where E: Error + where + E: Error, { parse(&v.to_string()).map_err(|err| Error::custom(format!("{}", err))) } fn visit_u64(self, v: u64) -> Result, E> - where E: Error + where + E: Error, { parse(&v.to_string()).map_err(|err| Error::custom(format!("{}", err))) } @@ -331,14 +372,16 @@ impl<'de, TMapping> Deserialize<'de> for Date /** A convenience function for formatting a date. */ pub(crate) fn format<'a, TMapping>(date: &'a Date) -> FormattedDate<'a> - where TMapping: DateMapping +where + TMapping: DateMapping, { date.value.format() } /** A convenience function for parsing a date. */ -pub(crate) fn parse(date: &str) -> Result, ParseError> - where TMapping: DateMapping +pub(crate) fn parse(date: &str) -> Result, ParseError> +where + TMapping: DateMapping, { let parsed = FormattableDateValue::parse(date)?; @@ -406,8 +449,9 @@ pub struct DateExpr { ops: Vec, } -impl Display for DateExpr - where TFormat: DateFormat +impl Display for DateExpr +where + TFormat: DateFormat, { fn fmt(&self, f: &mut Formatter) -> FmtResult { self.anchor.fmt(f)?; @@ -423,11 +467,12 @@ impl Display for DateExpr #[derive(Debug, Clone, PartialEq)] enum DateExprAnchor { Now, - Value(FormattableDateValue) + Value(FormattableDateValue), } impl Display for DateExprAnchor - where TFormat: DateFormat +where + TFormat: DateFormat, { fn fmt(&self, f: &mut Formatter) -> FmtResult { match *self { @@ -441,7 +486,7 @@ impl Display for DateExprAnchor enum DateExprOp { Add(usize, DateExprOpUnit), Sub(usize, DateExprOpUnit), - Round(DateExprOpUnit) + Round(DateExprOpUnit), } impl Display for DateExprOp { @@ -449,7 +494,7 @@ impl Display for DateExprOp { match *self { DateExprOp::Add(size, unit) => write!(f, "+{}{}", size, unit), DateExprOp::Sub(size, unit) => write!(f, "-{}{}", size, unit), - DateExprOp::Round(unit) => write!(f, "/{}", unit) + DateExprOp::Round(unit) => write!(f, "/{}", unit), } } } @@ -462,7 +507,7 @@ enum DateExprOpUnit { Day, Hour, Minute, - Second + Second, } impl Display for DateExprOpUnit { @@ -474,7 +519,7 @@ impl Display for DateExprOpUnit { DateExprOpUnit::Day => "d", DateExprOpUnit::Hour => "h", DateExprOpUnit::Minute => "m", - DateExprOpUnit::Second => "s" + DateExprOpUnit::Second => "s", }; fmtd.fmt(f) @@ -504,7 +549,8 @@ macro_rules! impl_expr_ops { } impl DateExpr - where TFormat: DateFormat +where + TFormat: DateFormat, { /** Create a new date expression for `now`. @@ -569,10 +615,11 @@ impl DateExpr ``` */ pub fn value(date: TDate) -> Self - where TDate: Into> + where + TDate: Into>, { let date = date.into(); - + DateExpr { anchor: DateExprAnchor::Value(date), ops: Vec::new(), @@ -584,15 +631,27 @@ impl DateExpr impl_expr_ops!(DateExprOpUnit::Week, add_weeks, sub_weeks, round_week); impl_expr_ops!(DateExprOpUnit::Day, add_days, sub_days, round_day); impl_expr_ops!(DateExprOpUnit::Hour, add_hours, sub_hours, round_hour); - impl_expr_ops!(DateExprOpUnit::Minute, add_minutes, sub_minutes, round_minute); - impl_expr_ops!(DateExprOpUnit::Second, add_seconds, sub_seconds, round_second); + impl_expr_ops!( + DateExprOpUnit::Minute, + add_minutes, + sub_minutes, + round_minute + ); + impl_expr_ops!( + DateExprOpUnit::Second, + add_seconds, + sub_seconds, + round_second + ); } -impl Serialize for DateExpr - where TFormat: DateFormat +impl Serialize for DateExpr +where + TFormat: DateFormat, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.collect_str(&self) } @@ -607,11 +666,11 @@ mod tests { use prelude::*; #[derive(ElasticDateFormat, Default, Clone)] - #[elastic(date_format="yyyy/MM/dd HH:mm:ss", date_format_name="test_date_1")] + #[elastic(date_format = "yyyy/MM/dd HH:mm:ss", date_format_name = "test_date_1")] pub struct NamedDateFormat; #[derive(ElasticDateFormat, Default, Clone, Copy)] - #[elastic(date_format="yyyyMMdd")] + #[elastic(date_format = "yyyyMMdd")] pub struct UnNamedDateFormat; #[test] @@ -659,26 +718,55 @@ mod tests { fn can_build_date_from_value() { let date: Date = Date::new(DateValue::build(2015, 05, 13, 0, 0, 0, 0)); - assert_eq!((2015, 5, 13, 0, 0, 0), - (date.year(), date.month(), date.day(), date.hour(), date.minute(), date.second())); + assert_eq!( + (2015, 5, 13, 0, 0, 0), + ( + date.year(), + date.month(), + date.day(), + date.hour(), + date.minute(), + date.second() + ) + ); } #[test] fn can_build_date_from_chrono() { - let date = chrono::Utc.datetime_from_str("13/05/2015 00:00:00", "%d/%m/%Y %H:%M:%S").unwrap(); + let date = chrono::Utc + .datetime_from_str("13/05/2015 00:00:00", "%d/%m/%Y %H:%M:%S") + .unwrap(); let date: Date> = Date::new(date); - assert_eq!((2015, 5, 13, 0, 0, 0), - (date.year(), date.month(), date.day(), date.hour(), date.minute(), date.second())); + assert_eq!( + (2015, 5, 13, 0, 0, 0), + ( + date.year(), + date.month(), + date.day(), + date.hour(), + date.minute(), + date.second() + ) + ); } #[test] fn can_build_date_from_prim() { let date: Date = Date::build(2015, 5, 13, 0, 0, 0, 0); - assert_eq!((2015, 5, 13, 0, 0, 0), - (date.year(), date.month(), date.day(), date.hour(), date.minute(), date.second())); + assert_eq!( + (2015, 5, 13, 0, 0, 0), + ( + date.year(), + date.month(), + date.day(), + date.hour(), + date.minute(), + date.second() + ) + ); } #[test] @@ -708,7 +796,9 @@ mod tests { #[test] fn serialise_date_expr_chrono() { - let date = chrono::Utc.datetime_from_str("13/05/2015 00:00:00", "%d/%m/%Y %H:%M:%S").unwrap(); + let date = chrono::Utc + .datetime_from_str("13/05/2015 00:00:00", "%d/%m/%Y %H:%M:%S") + .unwrap(); let expr = DateExpr::value(date); @@ -719,7 +809,15 @@ mod tests { #[test] fn serialise_date_expr_date() { - let expr = DateExpr::value(Date::>::build(2015, 5, 13, 0, 0, 0, 0)); + let expr = DateExpr::value(Date::>::build( + 2015, + 5, + 13, + 0, + 0, + 0, + 0, + )); let ser = serde_json::to_string(&expr).unwrap(); @@ -728,8 +826,15 @@ mod tests { #[test] fn serialise_date_expr_value_with_ops() { - let expr = DateExpr::value(Date::>::build(2015, 5, 13, 0, 0, 0, 0)) - .add_days(2) + let expr = DateExpr::value(Date::>::build( + 2015, + 5, + 13, + 0, + 0, + 0, + 0, + )).add_days(2) .round_week(); let ser = serde_json::to_string(&expr).unwrap(); diff --git a/src/types/src/date/mapping.rs b/src/types/src/date/mapping.rs index 0530882c9c..94793909c0 100644 --- a/src/types/src/date/mapping.rs +++ b/src/types/src/date/mapping.rs @@ -1,13 +1,15 @@ /*! Mapping for the Elasticsearch `date` type. */ use std::marker::PhantomData; -use super::{DateFormat, DefaultDateFormat, FormattableDateValue, Date}; +use super::{Date, DateFormat, DefaultDateFormat, FormattableDateValue}; /** A field that will be mapped as a `date`. */ -pub trait DateFieldType - where Self: Into>, - TMapping: DateMapping -{ } +pub trait DateFieldType +where + Self: Into>, + TMapping: DateMapping, +{ +} /** The base requirements for mapping a `date` type. @@ -95,7 +97,8 @@ impl DateMapping for MyDateMapping This is how `DefaultDateMapping` is able to support any format. */ pub trait DateMapping - where Self: Default +where + Self: Default, { /** The date format bound to this mapping. @@ -162,13 +165,15 @@ pub trait DateMapping /** Default mapping for `date`. */ #[derive(PartialEq, Debug, Default, Clone, Copy)] pub struct DefaultDateMapping - where TFormat: DateFormat +where + TFormat: DateFormat, { _f: PhantomData, } impl DateMapping for DefaultDateMapping - where TFormat: DateFormat +where + TFormat: DateFormat, { type Format = TFormat; } @@ -177,21 +182,24 @@ mod private { use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; use date::{DateFormat, FormattableDateValue}; - use private::field::{FieldType, DocumentField, FieldMapping}; + use private::field::{DocumentField, FieldMapping, FieldType}; use super::{DateFieldType, DateMapping}; impl FieldType for TField - where TField: DateFieldType + Serialize, - TField: Into>, - TMapping: DateMapping - { } + where + TField: DateFieldType + Serialize, + TField: Into>, + TMapping: DateMapping, + { + } #[derive(Default)] pub struct DatePivot; impl FieldMapping for TMapping - where TMapping: DateMapping, - TFormat: DateFormat + where + TMapping: DateMapping, + TFormat: DateFormat, { type DocumentField = DocumentField; @@ -201,11 +209,13 @@ mod private { } impl Serialize for DocumentField - where TMapping: FieldMapping + DateMapping, - TFormat: DateFormat + where + TMapping: FieldMapping + DateMapping, + TFormat: DateFormat, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 9)); @@ -231,7 +241,7 @@ mod tests { use chrono::{DateTime, Utc}; use prelude::*; - use private::field::{FieldType, DocumentField}; + use private::field::{DocumentField, FieldType}; #[derive(Default, Clone)] pub struct MyDateMapping; @@ -269,12 +279,17 @@ mod tests { #[test] fn datetime_has_default_mapping() { - assert_eq!(DefaultDateMapping::::default(), DateTime::::field_mapping()); + assert_eq!( + DefaultDateMapping::::default(), + DateTime::::field_mapping() + ); } #[test] fn serialise_mapping_default() { - let ser = serde_json::to_string(&DocumentField::from(DefaultDateMapping::::default())).unwrap(); + let ser = serde_json::to_string(&DocumentField::from( + DefaultDateMapping::::default(), + )).unwrap(); let expected = json_str!({ "type": "date", diff --git a/src/types/src/derive.rs b/src/types/src/derive.rs index 1c2c701208..e810cd72e6 100644 --- a/src/types/src/derive.rs +++ b/src/types/src/derive.rs @@ -10,21 +10,22 @@ use serde::Serialize; use chrono::{DateTime, Utc}; use chrono::format::{self, Parsed}; -use private::field::{FieldType, FieldMapping, DocumentField}; +use private::field::{DocumentField, FieldMapping, FieldType}; -pub use date::{DateFormat, DateValue, ParseError, FormattedDate}; +pub use date::{DateFormat, DateValue, FormattedDate, ParseError}; pub use document::DocumentType; pub use document::mapping::{DocumentMapping, PropertiesMapping}; -pub use chrono::format::{Item, Pad, Numeric, Fixed}; +pub use chrono::format::{Fixed, Item, Numeric, Pad}; pub use serde::ser::SerializeStruct; /** Get the mapping for a field. */ #[inline] pub fn mapping() -> TMapping - where TField: FieldType, - TMapping: FieldMapping, - TPivot: Default +where + TField: FieldType, + TMapping: FieldMapping, + TPivot: Default, { TMapping::default() } @@ -32,10 +33,11 @@ pub fn mapping() -> TMapping /** Serialise a field mapping as a field using the given serialiser. */ #[inline] pub fn field_ser(state: &mut S, field: &'static str, _: TMapping) -> Result<(), S::Error> - where S: SerializeStruct, - TMapping: FieldMapping, - TPivot: Default, - DocumentField: Serialize, +where + S: SerializeStruct, + TMapping: FieldMapping, + TPivot: Default, + DocumentField: Serialize, { state.serialize_field(field, &DocumentField::::default()) } @@ -47,9 +49,10 @@ This method isn't intended to be used publicly, but is useful in the docs. */ #[inline] pub fn standalone_field_ser(_: TMapping) -> Result - where TMapping: FieldMapping, - TPivot: Default, - DocumentField: Serialize, +where + TMapping: FieldMapping, + TPivot: Default, + DocumentField: Serialize, { serde_json::to_string(&DocumentField::::default()) } diff --git a/src/types/src/document/impls.rs b/src/types/src/document/impls.rs index 300f907170..f56cdfc173 100644 --- a/src/types/src/document/impls.rs +++ b/src/types/src/document/impls.rs @@ -212,7 +212,8 @@ impl Serialize for Mappings { */ #[derive(Default)] pub struct IndexDocumentMapping - where TMapping: DocumentMapping +where + TMapping: DocumentMapping, { _m: PhantomData, } @@ -237,36 +238,41 @@ impl PropertiesMapping for ValueDocumentMapping { } fn serialize_props(_: &mut S) -> Result<(), S::Error> - where S: SerializeStruct + where + S: SerializeStruct, { Ok(()) } } impl<'a, TDocument, TMapping> DocumentType for &'a TDocument - where TDocument: DocumentType + Serialize, - TMapping: DocumentMapping +where + TDocument: DocumentType + Serialize, + TMapping: DocumentMapping, { type Mapping = TMapping; } impl DocumentType for Mutex - where TDocument: DocumentType + Serialize, - TMapping: DocumentMapping +where + TDocument: DocumentType + Serialize, + TMapping: DocumentMapping, { type Mapping = TMapping; } impl DocumentType for RwLock - where TDocument: DocumentType + Serialize, - TMapping: DocumentMapping +where + TDocument: DocumentType + Serialize, + TMapping: DocumentMapping, { type Mapping = TMapping; } impl<'a, TDocument, TMapping> DocumentType for Cow<'a, TDocument> - where TDocument: DocumentType + Serialize + Clone, - TMapping: DocumentMapping +where + TDocument: DocumentType + Serialize + Clone, + TMapping: DocumentMapping, { type Mapping = TMapping; } @@ -288,7 +294,7 @@ mod tests { } #[derive(Default, ElasticDateFormat)] - #[elastic(date_format="yyyy")] + #[elastic(date_format = "yyyy")] pub struct DateFormatWithNoPath; } @@ -301,7 +307,7 @@ mod tests { } #[derive(Default, ElasticDateFormat)] - #[elastic(date_format="yyyy")] + #[elastic(date_format = "yyyy")] pub struct DateFormatInFn; } @@ -317,13 +323,11 @@ mod tests { } #[derive(Serialize, ElasticType)] - #[elastic(mapping="ManualCustomTypeMapping")] + #[elastic(mapping = "ManualCustomTypeMapping")] pub struct CustomType { pub field: i32, - #[serde(skip_serializing)] - pub ignored_field: i32, - #[serde(rename="renamed_field")] - pub field2: i32, + #[serde(skip_serializing)] pub ignored_field: i32, + #[serde(rename = "renamed_field")] pub field2: i32, } #[derive(PartialEq, Debug, Default)] @@ -359,7 +363,8 @@ mod tests { #[test] fn use_doc_as_generic_without_supplying_mapping_param() { fn use_document() - where TDocument: DocumentType + where + TDocument: DocumentType, { assert!(true); } @@ -560,20 +565,12 @@ mod tests { #[test] fn serialise_mapping_dynamic() { - let d_opts: Vec = vec![ - Dynamic::True, - Dynamic::False, - Dynamic::Strict - ] - .iter() - .map(|i| serde_json::to_string(i).unwrap()) - .collect(); - - let expected_opts = vec![ - r#"true"#, - r#"false"#, - r#""strict""# - ]; + let d_opts: Vec = vec![Dynamic::True, Dynamic::False, Dynamic::Strict] + .iter() + .map(|i| serde_json::to_string(i).unwrap()) + .collect(); + + let expected_opts = vec![r#"true"#, r#"false"#, r#""strict""#]; let mut success = true; for i in 0..d_opts.len() { diff --git a/src/types/src/document/mapping.rs b/src/types/src/document/mapping.rs index c3904d05d5..969684889e 100644 --- a/src/types/src/document/mapping.rs +++ b/src/types/src/document/mapping.rs @@ -5,7 +5,11 @@ use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; /** A field that will be mapped as a nested document. */ -pub trait DocumentFieldType where M: DocumentMapping {} +pub trait DocumentFieldType +where + M: DocumentMapping, +{ +} /** Elasticsearch datatype name. */ pub const OBJECT_DATATYPE: &'static str = "object"; @@ -18,7 +22,8 @@ pub const NESTED_DATATYPE: &'static str = "nested"; /** The base requirements for mapping an `object` type. */ pub trait DocumentMapping - where Self: PropertiesMapping + Default +where + Self: PropertiesMapping + Default, { /** Get the indexed name for this mapping. */ fn name() -> &'static str; @@ -71,21 +76,26 @@ pub trait PropertiesMapping { You can use the `field_ser` function to simplify `serde` calls. */ - fn serialize_props(state: &mut S) -> Result<(), S::Error> where S: SerializeStruct; + fn serialize_props(state: &mut S) -> Result<(), S::Error> + where + S: SerializeStruct; } #[derive(Default)] struct Properties - where TMapping: DocumentMapping +where + TMapping: DocumentMapping, { _m: PhantomData, } impl Serialize for Properties - where TMapping: DocumentMapping +where + TMapping: DocumentMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("properties", TMapping::props_len())); try!(TMapping::serialize_props(&mut state)); @@ -99,17 +109,15 @@ Inner objects inherit the setting from their parent object or from the mapping t */ #[derive(Debug, Clone, Copy)] pub enum Dynamic { - /** Newly detected fields are added to the mapping. (default). */ - True, - /** Newly detected fields are ignored. New fields must be added explicitly. */ - False, - /** If new fields are detected, an exception is thrown and the document is rejected. */ - Strict, + /** Newly detected fields are added to the mapping. (default). */ True, + /** Newly detected fields are ignored. New fields must be added explicitly. */ False, + /** If new fields are detected, an exception is thrown and the document is rejected. */ Strict, } impl Serialize for Dynamic { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { match *self { Dynamic::True => serializer.serialize_bool(true), @@ -123,25 +131,29 @@ mod private { use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; use document::{DocumentType, IndexDocumentMapping}; - use private::field::{FieldType, DocumentField, FieldMapping}; - use super::{DocumentFieldType, Properties, DocumentMapping, OBJECT_DATATYPE}; + use private::field::{DocumentField, FieldMapping, FieldType}; + use super::{DocumentFieldType, DocumentMapping, Properties, OBJECT_DATATYPE}; #[derive(Default)] pub struct DocumentPivot; impl FieldType for TField - where TMapping: DocumentMapping, - TField: DocumentFieldType - { } + where + TMapping: DocumentMapping, + TField: DocumentFieldType, + { + } impl DocumentFieldType for TDocument - where TDocument: DocumentType, - TMapping: DocumentMapping + where + TDocument: DocumentType, + TMapping: DocumentMapping, { } impl FieldMapping for TMapping - where TMapping: DocumentMapping + where + TMapping: DocumentMapping, { type DocumentField = DocumentField; @@ -151,10 +163,12 @@ mod private { } impl Serialize for DocumentField - where TMapping: FieldMapping + DocumentMapping + where + TMapping: FieldMapping + DocumentMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let ty = ::data_type(); let (is_object, has_props) = (ty == OBJECT_DATATYPE, TMapping::props_len() > 0); @@ -185,10 +199,12 @@ mod private { } impl Serialize for IndexDocumentMapping - where TMapping: DocumentMapping + where + TMapping: DocumentMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 1)); diff --git a/src/types/src/geo/mapping.rs b/src/types/src/geo/mapping.rs index 4fb17bbb1f..450088ab70 100644 --- a/src/types/src/geo/mapping.rs +++ b/src/types/src/geo/mapping.rs @@ -5,20 +5,13 @@ use serde::Serialize; /** A unit of measure for distance. */ pub enum DistanceUnit { - /** For `in`. */ - Inches, - /** For `yd`. */ - Yards, - /** For `mi`. */ - Miles, - /** For `km`. */ - Kilometers, - /** For `m`. */ - Meters, - /** For `cm`. */ - Centimeters, - /** For `mm`. */ - Millimeters, + /** For `in`. */ Inches, + /** For `yd`. */ Yards, + /** For `mi`. */ Miles, + /** For `km`. */ Kilometers, + /** For `m`. */ Meters, + /** For `cm`. */ Centimeters, + /** For `mm`. */ Millimeters, } /** A distance value paired with a unit of measure. */ @@ -47,7 +40,8 @@ impl ToString for Distance { impl Serialize for Distance { fn serialize(&self, serializer: S) -> Result - where S: serde::Serializer + where + S: serde::Serializer, { serializer.serialize_str(&self.to_string()) } diff --git a/src/types/src/geo/point/format.rs b/src/types/src/geo/point/format.rs index eab627f754..78b848954c 100644 --- a/src/types/src/geo/point/format.rs +++ b/src/types/src/geo/point/format.rs @@ -1,10 +1,11 @@ -use serde::{Serializer, Deserializer}; +use serde::{Deserializer, Serializer}; use super::Point; use super::mapping::GeoPointMapping; /** A format used for parsing and formatting geo points. */ pub trait GeoPointFormat - where Self: Default +where + Self: Default, { /** Parses a `geo::Point`. @@ -12,7 +13,9 @@ pub trait GeoPointFormat This requires access to the full `serde` deserializer because geo points can be serialised as different kinds of complex objects. */ - fn parse<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>; + fn parse<'de, D>(deserializer: D) -> Result + where + D: Deserializer<'de>; /** Formats a `geo::Point`. @@ -24,6 +27,7 @@ pub trait GeoPointFormat properly. */ fn format(point: &Point, serializer: S) -> Result - where TMapping: GeoPointMapping, - S: Serializer; + where + TMapping: GeoPointMapping, + S: Serializer; } diff --git a/src/types/src/geo/point/formats.rs b/src/types/src/geo/point/formats.rs index 4f16786a6c..2b9ab47ec3 100644 --- a/src/types/src/geo/point/formats.rs +++ b/src/types/src/geo/point/formats.rs @@ -1,9 +1,9 @@ use std::str::FromStr; use std::fmt::Write; -use serde::{Serialize, Serializer, Deserialize, Deserializer}; -use serde::de::{Error, Unexpected, Visitor, SeqAccess}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde::de::{Error, SeqAccess, Unexpected, Visitor}; use geohash; -use super::{Coordinate, Point, GeoPointFormat}; +use super::{Coordinate, GeoPointFormat, Point}; use super::mapping::GeoPointMapping; use geo::mapping::Distance; @@ -22,7 +22,8 @@ struct GeoPointObjectType { impl GeoPointFormat for GeoPointObject { fn parse<'de, D>(deserializer: D) -> Result - where D: Deserializer<'de> + where + D: Deserializer<'de>, { let point = try!(GeoPointObjectType::deserialize(deserializer)); @@ -30,14 +31,14 @@ impl GeoPointFormat for GeoPointObject { } fn format(point: &Point, serializer: S) -> Result - where TMapping: GeoPointMapping, - S: Serializer + where + TMapping: GeoPointMapping, + S: Serializer, { GeoPointObjectType { - lon: point.x(), - lat: point.y(), - } - .serialize(serializer) + lon: point.x(), + lat: point.y(), + }.serialize(serializer) } } @@ -46,7 +47,8 @@ impl GeoPointFormat for GeoPointObject { pub struct GeoPointString; impl GeoPointFormat for GeoPointString { fn parse<'de, D>(deserializer: D) -> Result - where D: Deserializer<'de> + where + D: Deserializer<'de>, { struct PointVisitor; @@ -58,13 +60,15 @@ impl GeoPointFormat for GeoPointString { } fn visit_str(self, value: &str) -> Result - where E: Error + where + E: Error, { Ok(String::from(value)) } fn visit_string(self, value: String) -> Result - where E: Error + where + E: Error, { Ok(value) } @@ -74,8 +78,10 @@ impl GeoPointFormat for GeoPointString { let xy: Vec<&str> = fmtd.split(",").collect(); if xy.len() != 2 { - return Err(D::Error::invalid_value(Unexpected::Str(&fmtd), - &"point must be formatted as `'y,x'`")); + return Err(D::Error::invalid_value( + Unexpected::Str(&fmtd), + &"point must be formatted as `'y,x'`", + )); } let x = match f64::from_str(xy[1]) { @@ -91,8 +97,9 @@ impl GeoPointFormat for GeoPointString { } fn format(point: &Point, serializer: S) -> Result - where TMapping: GeoPointMapping, - S: Serializer + where + TMapping: GeoPointMapping, + S: Serializer, { let mut fmtd = String::new(); @@ -107,7 +114,8 @@ impl GeoPointFormat for GeoPointString { pub struct GeoPointHash; impl GeoPointFormat for GeoPointHash { fn parse<'de, D>(deserializer: D) -> Result - where D: Deserializer<'de> + where + D: Deserializer<'de>, { struct PointVisitor; impl<'de> Visitor<'de> for PointVisitor { @@ -118,13 +126,15 @@ impl GeoPointFormat for GeoPointHash { } fn visit_str(self, value: &str) -> Result - where E: Error + where + E: Error, { Ok(String::from(value)) } fn visit_string(self, value: String) -> Result - where E: Error + where + E: Error, { Ok(value) } @@ -136,20 +146,22 @@ impl GeoPointFormat for GeoPointHash { } fn format(point: &Point, serializer: S) -> Result - where TMapping: GeoPointMapping, - S: Serializer + where + TMapping: GeoPointMapping, + S: Serializer, { let len = match TMapping::geohash_precision() { Some(Distance(l, _)) => l as usize, None => 12usize, }; - geohash::encode(Coordinate { - x: point.x(), - y: point.y(), - }, - len) - .serialize(serializer) + geohash::encode( + Coordinate { + x: point.x(), + y: point.y(), + }, + len, + ).serialize(serializer) } } @@ -158,7 +170,8 @@ impl GeoPointFormat for GeoPointHash { pub struct GeoPointArray; impl GeoPointFormat for GeoPointArray { fn parse<'de, D>(deserializer: D) -> Result - where D: Deserializer<'de> + where + D: Deserializer<'de>, { struct PointVisitor; impl<'de> Visitor<'de> for PointVisitor { @@ -169,20 +182,27 @@ impl GeoPointFormat for GeoPointArray { } fn visit_seq(self, mut visitor: S) -> Result - where S: SeqAccess<'de> + where + S: SeqAccess<'de>, { let mut values = Vec::with_capacity(2); while let Some(value) = visitor.next_element()? { if values.len() == 2 { - Err(S::Error::invalid_value(Unexpected::Seq, &"a json array with 2 values"))?; + Err(S::Error::invalid_value( + Unexpected::Seq, + &"a json array with 2 values", + ))?; } values.push(value); } if values.len() != 2 { - Err(S::Error::invalid_value(Unexpected::Seq, &"a json array with 2 values"))?; + Err(S::Error::invalid_value( + Unexpected::Seq, + &"a json array with 2 values", + ))?; } Ok(Point::new(values[0], values[1])) @@ -193,8 +213,9 @@ impl GeoPointFormat for GeoPointArray { } fn format(point: &Point, serializer: S) -> Result - where TMapping: GeoPointMapping, - S: Serializer + where + TMapping: GeoPointMapping, + S: Serializer, { [point.x(), point.y()].serialize(serializer) } @@ -246,8 +267,10 @@ mod tests { fn hash() { let point: GeoPoint> = serde_json::from_str(r#""drm3btev3e86""#).unwrap(); - assert_eq!((-71.34000012651086, 41.12000000663102), - (point.x(), point.y())); + assert_eq!( + (-71.34000012651086, 41.12000000663102), + (point.x(), point.y()) + ); let ser = serde_json::to_string(&point).unwrap(); diff --git a/src/types/src/geo/point/impls.rs b/src/types/src/geo/point/impls.rs index a598b127c5..407cf7aaf5 100644 --- a/src/types/src/geo/point/impls.rs +++ b/src/types/src/geo/point/impls.rs @@ -1,9 +1,9 @@ use std::borrow::Borrow; use std::marker::PhantomData; -use serde::{Serialize, Deserialize, Serializer, Deserializer}; -use georust::{ToGeo, Geometry as GeoEnum}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use georust::{Geometry as GeoEnum, ToGeo}; use super::mapping::{GeoPointFieldType, GeoPointMapping}; -use super::{Coordinate, Point, Geometry, GeoPointFormat}; +use super::{Coordinate, GeoPointFormat, Geometry, Point}; /** An Elasticsearch `geo_point` type with a format. @@ -44,13 +44,17 @@ println!("({},{})", - [Elasticsearch Doc](https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-point.html) */ #[derive(Debug, Clone, PartialEq)] -pub struct GeoPoint where TMapping: GeoPointMapping { +pub struct GeoPoint +where + TMapping: GeoPointMapping, +{ value: Point, _m: PhantomData, } impl GeoPoint - where TMapping: GeoPointMapping +where + TMapping: GeoPointMapping, { /** Creates a new `GeoPoint` from the given coordinate. @@ -75,7 +79,8 @@ impl GeoPoint ``` */ pub fn new(point: I) -> Self - where I: Into + where + I: Into, { GeoPoint { value: point.into(), @@ -110,21 +115,24 @@ impl GeoPoint ``` */ pub fn remap(point: GeoPoint) -> GeoPoint - where TNewMapping: GeoPointMapping + where + TNewMapping: GeoPointMapping, { GeoPoint::new(point.value) } } impl GeoPointFieldType for GeoPoint - where TMapping: GeoPointMapping +where + TMapping: GeoPointMapping, { } impl_mapping_type!(Point, GeoPoint, GeoPointMapping); impl From for GeoPoint - where TMapping: GeoPointMapping +where + TMapping: GeoPointMapping, { fn from(point: Coordinate) -> GeoPoint { GeoPoint::new(Point::new(point.x, point.y)) @@ -132,7 +140,8 @@ impl From for GeoPoint } impl ToGeo for GeoPoint - where TMapping: GeoPointMapping +where + TMapping: GeoPointMapping, { fn to_geo(&self) -> Geometry { GeoEnum::Point(self.value.clone()) @@ -140,20 +149,24 @@ impl ToGeo for GeoPoint } impl Serialize for GeoPoint - where TMapping: GeoPointMapping +where + TMapping: GeoPointMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { TMapping::Format::format::(&self.value, serializer) } } impl<'de, TMapping> Deserialize<'de> for GeoPoint - where TMapping: GeoPointMapping +where + TMapping: GeoPointMapping, { fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> + where + D: Deserializer<'de>, { let point = TMapping::Format::parse(deserializer)?; @@ -163,7 +176,7 @@ impl<'de, TMapping> Deserialize<'de> for GeoPoint #[cfg(test)] mod tests { - use georust::{Geometry, ToGeo, Point, Coordinate}; + use georust::{Coordinate, Geometry, Point, ToGeo}; use prelude::*; diff --git a/src/types/src/geo/point/mapping.rs b/src/types/src/geo/point/mapping.rs index ee216a31a4..8ab207a4d7 100644 --- a/src/types/src/geo/point/mapping.rs +++ b/src/types/src/geo/point/mapping.rs @@ -1,7 +1,7 @@ /*! Mapping for the Elasticsearch `geo_point` type. */ use std::marker::PhantomData; -use super::{GeoPointFormat, DefaultGeoPointFormat}; +use super::{DefaultGeoPointFormat, GeoPointFormat}; use geo::mapping::Distance; /** A field that will be mapped as a `geo_point`. */ @@ -89,7 +89,8 @@ impl GeoPointMapping for MyGeoPointMapping { ``` */ pub trait GeoPointMapping - where Self: Default +where + Self: Default, { /** The format used to serialise and deserialise the geo point. @@ -137,13 +138,15 @@ pub trait GeoPointMapping /** Default mapping for `geo_point`. */ #[derive(PartialEq, Debug, Default, Clone, Copy)] pub struct DefaultGeoPointMapping - where TFormat: GeoPointFormat +where + TFormat: GeoPointFormat, { _f: PhantomData, } impl GeoPointMapping for DefaultGeoPointMapping - where TFormat: GeoPointFormat +where + TFormat: GeoPointFormat, { type Format = TFormat; } @@ -151,19 +154,22 @@ impl GeoPointMapping for DefaultGeoPointMapping mod private { use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; - use private::field::{FieldType, DocumentField, FieldMapping}; + use private::field::{DocumentField, FieldMapping, FieldType}; use super::{GeoPointFieldType, GeoPointMapping}; #[derive(Default)] pub struct GeoPointPivot; impl FieldType for TField - where TField: GeoPointFieldType + Serialize, - TMapping: GeoPointMapping - { } + where + TField: GeoPointFieldType + Serialize, + TMapping: GeoPointMapping, + { + } impl FieldMapping for TMapping - where TMapping: GeoPointMapping, + where + TMapping: GeoPointMapping, { type DocumentField = DocumentField; @@ -173,10 +179,12 @@ mod private { } impl Serialize for DocumentField - where TMapping: FieldMapping + GeoPointMapping, + where + TMapping: FieldMapping + GeoPointMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 6)); @@ -228,7 +236,9 @@ mod tests { #[test] fn serialise_mapping_default() { - let ser = serde_json::to_string(&DocumentField::from(DefaultGeoPointMapping::::default())).unwrap(); + let ser = serde_json::to_string(&DocumentField::from( + DefaultGeoPointMapping::::default(), + )).unwrap(); let expected = json_str!({ "type": "geo_point" diff --git a/src/types/src/geo/point/mod.rs b/src/types/src/geo/point/mod.rs index 550b6b6886..3aef554c75 100644 --- a/src/types/src/geo/point/mod.rs +++ b/src/types/src/geo/point/mod.rs @@ -61,7 +61,7 @@ impl GeoPointFieldType> for MyGeoPointFie - [Elasticsearch Doc](https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-point.html) */ -use georust::{Coordinate as C, Point as P, Geometry as G}; +use georust::{Coordinate as C, Geometry as G, Point as P}; type Coordinate = C; type Point = P; diff --git a/src/types/src/geo/shape/impls.rs b/src/types/src/geo/shape/impls.rs index 84e424fb77..8fec986077 100644 --- a/src/types/src/geo/shape/impls.rs +++ b/src/types/src/geo/shape/impls.rs @@ -1,6 +1,6 @@ use std::borrow::Borrow; use std::marker::PhantomData; -use serde::{Serialize, Deserialize, Serializer, Deserializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use geojson::Geometry; use super::mapping::{GeoShapeFieldType, GeoShapeMapping}; @@ -25,13 +25,17 @@ let point: GeoShape = GeoShape::new( ``` */ #[derive(Debug, Clone, PartialEq)] -pub struct GeoShape where TMapping: GeoShapeMapping { +pub struct GeoShape +where + TMapping: GeoShapeMapping, +{ value: Geometry, _m: PhantomData, } impl GeoShape - where TMapping: GeoShapeMapping +where + TMapping: GeoShapeMapping, { /** Creates a new `GeoShape` from the given `Geometry`. @@ -56,7 +60,8 @@ impl GeoShape ``` */ pub fn new(geo: I) -> GeoShape - where I: Into + where + I: Into, { GeoShape { value: geo.into(), @@ -65,32 +70,41 @@ impl GeoShape } /** Change the mapping of this geo shape. */ - pub fn remap(shape: GeoShape) -> GeoShape - where TNewMapping: GeoShapeMapping + pub fn remap(shape: GeoShape) -> GeoShape + where + TNewMapping: GeoShapeMapping, { GeoShape::new(shape.value) } } -impl GeoShapeFieldType for GeoShape where TMapping: GeoShapeMapping {} +impl GeoShapeFieldType for GeoShape +where + TMapping: GeoShapeMapping, +{ +} impl_mapping_type!(Geometry, GeoShape, GeoShapeMapping); impl Serialize for GeoShape - where TMapping: GeoShapeMapping +where + TMapping: GeoShapeMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { self.value.serialize(serializer) } } impl<'de, TMapping> Deserialize<'de> for GeoShape - where TMapping: GeoShapeMapping +where + TMapping: GeoShapeMapping, { fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> + where + D: Deserializer<'de>, { let t = try!(Geometry::deserialize(deserializer)); @@ -115,21 +129,24 @@ mod tests { true } - let point: GeoShape = GeoShape::new(Geometry::new(Value::Point(vec![ 1.0, 1.0 ]))); + let point: GeoShape = GeoShape::new(Geometry::new(Value::Point(vec![1.0, 1.0]))); assert!(takes_custom_mapping(GeoShape::remap(point))); } #[test] fn serialise_elastic_geo_shape() { - let shape = GeoShape::::new(Geometry::new(Value::Point(vec![ 1.0, 1.0 ]))); + let shape = GeoShape::::new(Geometry::new(Value::Point(vec![1.0, 1.0]))); let ser = serde_json::to_string(&shape).unwrap(); - assert_eq!(json_str!({ + assert_eq!( + json_str!({ "coordinates": [ 1.0, 1.0 ], "type": "Point" - }), ser); + }), + ser + ); } #[test] @@ -137,14 +154,9 @@ mod tests { let shape: GeoShape = serde_json::from_str(&json_str!({ "coordinates": [ 1, 1 ], "type": "Point" - })) - .unwrap(); + })).unwrap(); - assert_eq!( - Geometry::new( - Value::Point(vec![ 1.0, 1.0 ])), - *shape - ); + assert_eq!(Geometry::new(Value::Point(vec![1.0, 1.0])), *shape); } } diff --git a/src/types/src/geo/shape/mapping.rs b/src/types/src/geo/shape/mapping.rs index d9233713f4..058ca3edd9 100644 --- a/src/types/src/geo/shape/mapping.rs +++ b/src/types/src/geo/shape/mapping.rs @@ -62,7 +62,8 @@ This will produce the following mapping: ``` */ pub trait GeoShapeMapping - where Self: Default +where + Self: Default, { /** Name of the PrefixTree implementation to be used: @@ -155,39 +156,37 @@ impl GeoShapeMapping for DefaultGeoShapeMapping {} /** Name of the `PrefixTree` implementation to be used. */ pub enum Tree { - /** For `GeohashPrefixTree`. */ - Geohash, - /** For `QuadPrefixTree`. */ - QuadPrefix, + /** For `GeohashPrefixTree`. */ Geohash, + /** For `QuadPrefixTree`. */ QuadPrefix, } impl Serialize for Tree { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_str(match *self { - Tree::Geohash => "geohash", - Tree::QuadPrefix => "quadtree", - }) + Tree::Geohash => "geohash", + Tree::QuadPrefix => "quadtree", + }) } } /** The strategy defines the approach for how to represent shapes at indexing and search time. */ pub enum Strategy { - /** Recursive strategy supports all shape types. */ - Recursive, - /** Term strategy supports point types only. */ - Term, + /** Recursive strategy supports all shape types. */ Recursive, + /** Term strategy supports point types only. */ Term, } impl Serialize for Strategy { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_str(match *self { - Strategy::Recursive => "recursive", - Strategy::Term => "term", - }) + Strategy::Recursive => "recursive", + Strategy::Term => "term", + }) } } @@ -200,39 +199,41 @@ The default orientation (counterclockwise) complies with the OGC standard which ring vertices in counterclockwise order with inner ring(s) vertices (holes) in clockwise order. */ pub enum Orientation { - /** For `cw`. */ - Clockwise, - /** For `ccw`. */ - CounterClockwise, + /** For `cw`. */ Clockwise, + /** For `ccw`. */ CounterClockwise, } impl Serialize for Orientation { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_str(match *self { - Orientation::Clockwise => "cw", - Orientation::CounterClockwise => "ccw", - }) + Orientation::Clockwise => "cw", + Orientation::CounterClockwise => "ccw", + }) } } mod private { use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; - use private::field::{FieldType, DocumentField, FieldMapping}; - use super::{GeoShapeMapping, GeoShapeFieldType}; + use private::field::{DocumentField, FieldMapping, FieldType}; + use super::{GeoShapeFieldType, GeoShapeMapping}; impl FieldType for TField - where TField: GeoShapeFieldType + Serialize, - TMapping: GeoShapeMapping - { } + where + TField: GeoShapeFieldType + Serialize, + TMapping: GeoShapeMapping, + { + } #[derive(Default)] pub struct GeoShapePivot; impl FieldMapping for TMapping - where TMapping: GeoShapeMapping + where + TMapping: GeoShapeMapping, { type DocumentField = DocumentField; @@ -242,10 +243,12 @@ mod private { } impl Serialize for DocumentField - where TMapping: FieldMapping + GeoShapeMapping + where + TMapping: FieldMapping + GeoShapeMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 8)); diff --git a/src/types/src/ip/impls.rs b/src/types/src/ip/impls.rs index 02f1861d64..ed9047bf5f 100644 --- a/src/types/src/ip/impls.rs +++ b/src/types/src/ip/impls.rs @@ -3,9 +3,9 @@ use std::marker::PhantomData; use std::net::Ipv4Addr; use std::str::FromStr; use std::error::Error as StdError; -use serde::{Serialize, Deserialize, Serializer, Deserializer}; -use serde::de::{Visitor, Error}; -use super::mapping::{IpFieldType, IpMapping, DefaultIpMapping}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde::de::{Error, Visitor}; +use super::mapping::{DefaultIpMapping, IpFieldType, IpMapping}; impl IpFieldType for Ipv4Addr {} @@ -27,13 +27,17 @@ let ip = Ip::::new(Ipv4Addr::new(127, 0, 0, 1)); ``` */ #[derive(Debug, Clone, PartialEq)] -pub struct Ip where TMapping: IpMapping { +pub struct Ip +where + TMapping: IpMapping, +{ value: Ipv4Addr, _m: PhantomData, } impl Ip - where TMapping: IpMapping +where + TMapping: IpMapping, { /** Creates a new `Ip` with the given mapping. @@ -51,7 +55,8 @@ impl Ip ``` */ pub fn new(ip: I) -> Ip - where I: Into + where + I: Into, { Ip { value: ip.into(), @@ -83,22 +88,29 @@ impl Ip ``` */ pub fn remap(ip: Ip) -> Ip - where TNewMapping: IpMapping + where + TNewMapping: IpMapping, { Ip::new(ip.value) } } -impl IpFieldType for Ip where TMapping: IpMapping {} +impl IpFieldType for Ip +where + TMapping: IpMapping, +{ +} impl_mapping_type!(Ipv4Addr, Ip, IpMapping); // Serialize elastic ip impl Serialize for Ip - where TMapping: IpMapping +where + TMapping: IpMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_str(&self.value.to_string()) } @@ -106,10 +118,12 @@ impl Serialize for Ip // Deserialize elastic ip impl<'de, TMapping> Deserialize<'de> for Ip - where TMapping: IpMapping +where + TMapping: IpMapping, { fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> + where + D: Deserializer<'de>, { #[derive(Default)] struct IpVisitor { @@ -117,7 +131,8 @@ impl<'de, TMapping> Deserialize<'de> for Ip } impl<'de, TMapping> Visitor<'de> for IpVisitor - where TMapping: IpMapping + where + TMapping: IpMapping, { type Value = Ip; @@ -126,7 +141,8 @@ impl<'de, TMapping> Deserialize<'de> for Ip } fn visit_string(self, v: String) -> Result, E> - where E: Error + where + E: Error, { let de = try!(Ipv4Addr::from_str(&v).map_err(|e| E::custom(e.description().to_string()))); @@ -134,7 +150,8 @@ impl<'de, TMapping> Deserialize<'de> for Ip } fn visit_str(self, v: &str) -> Result, E> - where E: Error + where + E: Error, { let de = try!(Ipv4Addr::from_str(v).map_err(|e| E::custom(e.description().to_string()))); diff --git a/src/types/src/ip/mapping.rs b/src/types/src/ip/mapping.rs index 532a5ad8e0..82c5e41f2b 100644 --- a/src/types/src/ip/mapping.rs +++ b/src/types/src/ip/mapping.rs @@ -65,7 +65,8 @@ This will produce the following mapping: ``` */ pub trait IpMapping - where Self: Default +where + Self: Default, { /** Field-level index time boosting. Accepts a floating point number, defaults to `1.0`. */ fn boost() -> Option { @@ -111,19 +112,22 @@ impl IpMapping for DefaultIpMapping {} mod private { use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; - use private::field::{FieldType, DocumentField, FieldMapping}; + use private::field::{DocumentField, FieldMapping, FieldType}; use super::{IpFieldType, IpMapping}; #[derive(Default)] pub struct IpPivot; impl FieldType for TField - where TField: IpFieldType + Serialize, - TMapping: IpMapping - { } + where + TField: IpFieldType + Serialize, + TMapping: IpMapping, + { + } impl FieldMapping for TMapping - where TMapping: IpMapping + where + TMapping: IpMapping, { type DocumentField = DocumentField; @@ -133,10 +137,12 @@ mod private { } impl Serialize for DocumentField - where TMapping: FieldMapping + IpMapping + where + TMapping: FieldMapping + IpMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 6)); @@ -159,7 +165,7 @@ mod tests { use std::net::Ipv4Addr; use prelude::*; - use private::field::{FieldType, DocumentField}; + use private::field::{DocumentField, FieldType}; #[derive(Default, Clone)] pub struct MyIpMapping; diff --git a/src/types/src/lib.rs b/src/types/src/lib.rs index 404c506817..ea6700d352 100644 --- a/src/types/src/lib.rs +++ b/src/types/src/lib.rs @@ -513,11 +513,11 @@ This is a particularly helpful feature for serialisation. extern crate geohash; #[macro_use] -extern crate serde_derive; +extern crate elastic_types_derive; extern crate serde; -extern crate serde_json; #[macro_use] -extern crate elastic_types_derive; +extern crate serde_derive; +extern crate serde_json; extern crate chrono; extern crate geo as georust; diff --git a/src/types/src/number/impls.rs b/src/types/src/number/impls.rs index e6939e5514..1fffb32fc0 100644 --- a/src/types/src/number/impls.rs +++ b/src/types/src/number/impls.rs @@ -1,6 +1,6 @@ use std::borrow::Borrow; use std::marker::PhantomData; -use serde::{Serialize, Deserialize, Serializer, Deserializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use super::mapping::*; macro_rules! number_type { @@ -103,30 +103,32 @@ mod tests { #[test] fn serialise_elastic_numbers() { - let ser = vec![{ - let num = Integer::::new(1i32); - serde_json::to_string(&num).unwrap() - }, - { - let num = Long::::new(1i64); - serde_json::to_string(&num).unwrap() - }, - { - let num = Short::::new(1i16); - serde_json::to_string(&num).unwrap() - }, - { - let num = Byte::::new(1i8); - serde_json::to_string(&num).unwrap() - }, - { - let num = Float::::new(1.01f32); - serde_json::to_string(&num).unwrap() - }, - { - let num = Double::::new(1.01f64); - serde_json::to_string(&num).unwrap() - }]; + let ser = vec![ + { + let num = Integer::::new(1i32); + serde_json::to_string(&num).unwrap() + }, + { + let num = Long::::new(1i64); + serde_json::to_string(&num).unwrap() + }, + { + let num = Short::::new(1i16); + serde_json::to_string(&num).unwrap() + }, + { + let num = Byte::::new(1i8); + serde_json::to_string(&num).unwrap() + }, + { + let num = Float::::new(1.01f32); + serde_json::to_string(&num).unwrap() + }, + { + let num = Double::::new(1.01f64); + serde_json::to_string(&num).unwrap() + }, + ]; let expected_ser = vec!["1", "1", "1", "1", "1.01", "1.01"]; @@ -150,7 +152,16 @@ mod tests { let float_de: Float = serde_json::from_str("1.01").unwrap(); let double_de: Double = serde_json::from_str("1.01").unwrap(); - assert_eq!((1i32, 1i64, 1i16, 1i8, 1.01f32, 1.01f64), - (*int_de, *long_de, *short_de, *byte_de, *float_de, *double_de)); + assert_eq!( + (1i32, 1i64, 1i16, 1i8, 1.01f32, 1.01f64), + ( + *int_de, + *long_de, + *short_de, + *byte_de, + *float_de, + *double_de + ) + ); } } diff --git a/src/types/src/number/mapping.rs b/src/types/src/number/mapping.rs index 4fe644b4f6..7f1baa27d6 100644 --- a/src/types/src/number/mapping.rs +++ b/src/types/src/number/mapping.rs @@ -156,12 +156,54 @@ macro_rules! number_mapping { ) } -number_mapping!(IntegerMapping, IntegerFormat, IntegerFieldType, "integer", i32, private_i32); -number_mapping!(LongMapping, LongFormat, LongFieldType, "long", i64, private_i64); -number_mapping!(ShortMapping, ShortFormat, ShortFieldType, "short", i16, private_i16); -number_mapping!(ByteMapping, ByteFormat, ByteFieldType, "byte", i8, private_i8); -number_mapping!(FloatMapping, FloatFormat, FloatFieldType, "float", f32, private_f32); -number_mapping!(DoubleMapping, DoubleFormat, DoubleFieldType, "double", f64, private_f64); +number_mapping!( + IntegerMapping, + IntegerFormat, + IntegerFieldType, + "integer", + i32, + private_i32 +); +number_mapping!( + LongMapping, + LongFormat, + LongFieldType, + "long", + i64, + private_i64 +); +number_mapping!( + ShortMapping, + ShortFormat, + ShortFieldType, + "short", + i16, + private_i16 +); +number_mapping!( + ByteMapping, + ByteFormat, + ByteFieldType, + "byte", + i8, + private_i8 +); +number_mapping!( + FloatMapping, + FloatFormat, + FloatFieldType, + "float", + f32, + private_f32 +); +number_mapping!( + DoubleMapping, + DoubleFormat, + DoubleFieldType, + "double", + f64, + private_f64 +); /** Default mapping for an `integer` type. */ #[derive(PartialEq, Debug, Default, Clone, Copy)] @@ -205,7 +247,7 @@ mod tests { use serde_json; use prelude::*; - use private::field::{FieldType, DocumentField}; + use private::field::{DocumentField, FieldType}; #[derive(Default, Clone)] pub struct MyIntegerMapping; diff --git a/src/types/src/private/field.rs b/src/types/src/private/field.rs index 25a8311c69..5e048c4ad7 100644 --- a/src/types/src/private/field.rs +++ b/src/types/src/private/field.rs @@ -12,8 +12,9 @@ use serde::Serialize; /** The base representation of an Elasticsearch data type. */ pub trait FieldType - where TMapping: FieldMapping, - TPivot: Default +where + TMapping: FieldMapping, + TPivot: Default, { /** Get a serialisable instance of the type mapping as a field. */ fn field_mapping() -> TMapping { @@ -23,8 +24,9 @@ pub trait FieldType /** The base representation of an Elasticsearch data type mapping. */ pub trait FieldMapping - where Self: Default, - TPivot: Default +where + Self: Default, + TPivot: Default, { /** Prevents infinite recursion when resolving `Serialize` on nested mappings. */ type DocumentField: Serialize + Default; @@ -36,8 +38,9 @@ pub trait FieldMapping /** Captures traits required for conversion between a field with mapping and a default counterpart. */ pub trait StdField - where Self: PartialEq + Deref + Borrow, - TStd: PartialEq +where + Self: PartialEq + Deref + Borrow, + TStd: PartialEq, { } @@ -51,15 +54,17 @@ Individual implementations of `Serialize` for `DocumentField` are spread through */ #[derive(Default)] pub struct DocumentField - where TMapping: FieldMapping, - TPivot: Default +where + TMapping: FieldMapping, + TPivot: Default, { _m: PhantomData<(TMapping, TPivot)>, } impl From for DocumentField - where TMapping: FieldMapping, - TPivot: Default +where + TMapping: FieldMapping, + TPivot: Default, { fn from(_: TMapping) -> Self { DocumentField::::default() diff --git a/src/types/src/private/impls.rs b/src/types/src/private/impls.rs index cbdfb64103..b89f37ec9b 100644 --- a/src/types/src/private/impls.rs +++ b/src/types/src/private/impls.rs @@ -1,24 +1,24 @@ use std::hash::Hash; use std::marker::PhantomData; -use std::collections::{HashMap, BTreeMap}; +use std::collections::{BTreeMap, HashMap}; use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; -use super::field::{DocumentField, FieldType, FieldMapping}; +use super::field::{DocumentField, FieldMapping, FieldType}; pub trait DefaultFieldType {} /** A mapping implementation for a non-core type, or anywhere it's ok for Elasticsearch to infer the mapping at index-time. */ #[derive(Debug, PartialEq, Default, Clone)] struct DefaultMapping; -impl FieldMapping<()> for DefaultMapping -{ +impl FieldMapping<()> for DefaultMapping { type DocumentField = DocumentField; } impl Serialize for DocumentField { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 1)); @@ -38,15 +38,17 @@ So the mapping for an array or optional type is just the mapping for the type it */ #[derive(Debug, Default, Clone)] pub struct WrappedMapping - where TMapping: FieldMapping, - TPivot: Default +where + TMapping: FieldMapping, + TPivot: Default, { _m: PhantomData<(TMapping, TPivot)>, } impl FieldMapping for WrappedMapping - where TMapping: FieldMapping, - TPivot: Default +where + TMapping: FieldMapping, + TPivot: Default, { type DocumentField = TMapping::DocumentField; @@ -56,46 +58,60 @@ impl FieldMapping for WrappedMapping } impl Serialize for DocumentField, TPivot> - where TMapping: FieldMapping, - TPivot: Default, +where + TMapping: FieldMapping, + TPivot: Default, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { TMapping::DocumentField::default().serialize(serializer) } } impl FieldType for TField - where TField: DefaultFieldType -{ } +where + TField: DefaultFieldType, +{ +} /** Mapping implementation for a standard binary tree map. */ impl DefaultFieldType for BTreeMap - where K: AsRef + Ord + Serialize, - V: Serialize -{ } +where + K: AsRef + Ord + Serialize, + V: Serialize, +{ +} /** Mapping implementation for a standard hash map. */ impl DefaultFieldType for HashMap - where K: AsRef + Eq + Hash + Serialize, - V: Serialize -{ } +where + K: AsRef + Eq + Hash + Serialize, + V: Serialize, +{ +} impl FieldType, TPivot> for TField - where TField: WrappedFieldType, - TMapping: FieldMapping, - TPivot: Default, -{ } +where + TField: WrappedFieldType, + TMapping: FieldMapping, + TPivot: Default, +{ +} impl WrappedFieldType for Vec - where TField: FieldType, - TMapping: FieldMapping, - TPivot: Default, -{ } +where + TField: FieldType, + TMapping: FieldMapping, + TPivot: Default, +{ +} impl WrappedFieldType for Option - where TField: FieldType, - TMapping: FieldMapping, - TPivot: Default, -{ } +where + TField: FieldType, + TMapping: FieldMapping, + TPivot: Default, +{ +} diff --git a/src/types/src/string/keyword/impls.rs b/src/types/src/string/keyword/impls.rs index 6ca53dda9f..bb22375584 100644 --- a/src/types/src/string/keyword/impls.rs +++ b/src/types/src/string/keyword/impls.rs @@ -1,7 +1,7 @@ use std::borrow::Borrow; use std::marker::PhantomData; -use serde::{Serialize, Deserialize, Serializer, Deserializer}; -use serde::de::{Visitor, Error}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde::de::{Error, Visitor}; use super::mapping::{KeywordFieldType, KeywordMapping}; /** @@ -21,13 +21,17 @@ let string = Keyword::::new("my string value"); ``` */ #[derive(Debug, Clone, Default, PartialEq)] -pub struct Keyword where TMapping: KeywordMapping { +pub struct Keyword +where + TMapping: KeywordMapping, +{ value: String, _m: PhantomData, } impl Keyword - where TMapping: KeywordMapping +where + TMapping: KeywordMapping, { /** Creates a new `Keyword` with the given mapping. @@ -44,7 +48,8 @@ impl Keyword ``` */ pub fn new(string: I) -> Keyword - where I: Into + where + I: Into, { Keyword { value: string.into(), @@ -54,7 +59,8 @@ impl Keyword /** Change the mapping of this string. */ pub fn remap(keyword: Keyword) -> Keyword - where TNewMapping: KeywordMapping + where + TNewMapping: KeywordMapping, { Keyword::new(keyword.value) } diff --git a/src/types/src/string/keyword/mapping.rs b/src/types/src/string/keyword/mapping.rs index 69465f731a..dc17c9a093 100644 --- a/src/types/src/string/keyword/mapping.rs +++ b/src/types/src/string/keyword/mapping.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; -use string::mapping::{StringField, IndexOptions}; +use string::mapping::{IndexOptions, StringField}; use private::field::FieldMapping; /** A field that will be mapped as a `keyword`. */ @@ -69,7 +69,8 @@ This will produce the following mapping: ``` */ pub trait KeywordMapping - where Self: Default +where + Self: Default, { /** The analyzer which should be used for analyzed string fields, @@ -251,12 +252,9 @@ pub struct KeywordFieldMapping { Any characters over this length will be ignored. */ pub ignore_above: Option, - /** Should the field be searchable? Accepts `true` (default) or `false`. */ - pub index: Option, - /** What information should be stored in the index, for search and highlighting purposes. Defaults to `Positions`. */ - pub index_options: Option, - /** Whether field-length should be taken into account when scoring queries. Accepts `true` (default) or `false`. */ - pub norms: Option, + /** Should the field be searchable? Accepts `true` (default) or `false`. */ pub index: Option, + /** What information should be stored in the index, for search and highlighting purposes. Defaults to `Positions`. */ pub index_options: Option, + /** Whether field-length should be taken into account when scoring queries. Accepts `true` (default) or `false`. */ pub norms: Option, /** Whether the field value should be stored and retrievable separately from the `_source` field. Accepts `true` or `false` (default). @@ -276,7 +274,8 @@ pub struct KeywordFieldMapping { impl Serialize for KeywordFieldMapping { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 12)); @@ -301,19 +300,22 @@ impl Serialize for KeywordFieldMapping { mod private { use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; - use private::field::{FieldType, DocumentField, FieldMapping}; + use private::field::{DocumentField, FieldMapping, FieldType}; use super::{KeywordFieldType, KeywordMapping}; #[derive(Default)] pub struct KeywordPivot; impl FieldType for TField - where TField: KeywordFieldType + Serialize, - TMapping: KeywordMapping - { } + where + TField: KeywordFieldType + Serialize, + TMapping: KeywordMapping, + { + } impl FieldMapping for TMapping - where TMapping: KeywordMapping + where + TMapping: KeywordMapping, { type DocumentField = DocumentField; @@ -323,10 +325,12 @@ mod private { } impl Serialize for DocumentField - where TMapping: FieldMapping + KeywordMapping + where + TMapping: FieldMapping + KeywordMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 15)); @@ -335,7 +339,11 @@ mod private { ser_field!(state, "boost", TMapping::boost()); ser_field!(state, "analyzer", TMapping::analyzer()); ser_field!(state, "doc_values", TMapping::doc_values()); - ser_field!(state, "eager_global_ordinals", TMapping::eager_global_ordinals()); + ser_field!( + state, + "eager_global_ordinals", + TMapping::eager_global_ordinals() + ); ser_field!(state, "fields", TMapping::fields()); ser_field!(state, "include_in_all", TMapping::include_in_all()); ser_field!(state, "ignore_above", TMapping::ignore_above()); diff --git a/src/types/src/string/mapping.rs b/src/types/src/string/mapping.rs index 0862d46f93..9c11084b4e 100644 --- a/src/types/src/string/mapping.rs +++ b/src/types/src/string/mapping.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; -use super::text::mapping::{TextMapping, TextFieldMapping}; +use super::text::mapping::{TextFieldMapping, TextMapping}; use super::keyword::mapping::KeywordFieldMapping; /** Default mapping for `String`. */ @@ -13,7 +13,10 @@ impl TextMapping for DefaultStringMapping { fn fields() -> Option> { let mut fields = BTreeMap::new(); - let keyword = KeywordFieldMapping { ignore_above: Some(256), ..Default::default() }; + let keyword = KeywordFieldMapping { + ignore_above: Some(256), + ..Default::default() + }; fields.insert("keyword", StringField::Keyword(keyword)); @@ -24,8 +27,7 @@ impl TextMapping for DefaultStringMapping { /** The `index_options` parameter controls what information is added to the inverted index, for search and highlighting purposes. */ #[derive(Debug, Clone, Copy)] pub enum IndexOptions { - /** Only the doc number is indexed. Can answer the question Does this term exist in this field? */ - Docs, + /** Only the doc number is indexed. Can answer the question Does this term exist in this field? */ Docs, /** Doc number and term frequencies are indexed. Term frequencies are used to score repeated terms higher than single terms. @@ -46,14 +48,15 @@ pub enum IndexOptions { impl Serialize for IndexOptions { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_str(match *self { - IndexOptions::Docs => "docs", - IndexOptions::Freqs => "freqs", - IndexOptions::Positions => "positions", - IndexOptions::Offsets => "offsets", - }) + IndexOptions::Docs => "docs", + IndexOptions::Freqs => "freqs", + IndexOptions::Positions => "positions", + IndexOptions::Offsets => "offsets", + }) } } @@ -64,19 +67,16 @@ String types can have a number of alternative field representations for differen */ #[derive(Debug, Clone, Copy)] pub enum StringField { - /** A `token_count` sub field. */ - TokenCount(ElasticTokenCountFieldMapping), - /** A `completion` suggester sub field. */ - Completion(ElasticCompletionFieldMapping), - /** A `keyword` sub field. */ - Keyword(KeywordFieldMapping), - /** A `text` sub field. */ - Text(TextFieldMapping), + /** A `token_count` sub field. */ TokenCount(ElasticTokenCountFieldMapping), + /** A `completion` suggester sub field. */ Completion(ElasticCompletionFieldMapping), + /** A `keyword` sub field. */ Keyword(KeywordFieldMapping), + /** A `text` sub field. */ Text(TextFieldMapping), } impl Serialize for StringField { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { match *self { StringField::TokenCount(m) => m.serialize(serializer), @@ -96,16 +96,14 @@ pub struct ElasticTokenCountFieldMapping { Defaults to the default index analyzer, or the `standard` analyzer. */ pub analyzer: Option<&'static str>, - /** Field-level index time boosting. Accepts a floating point number, defaults to `1.0`. */ - pub boost: Option, + /** Field-level index time boosting. Accepts a floating point number, defaults to `1.0`. */ pub boost: Option, /** Should the field be stored on disk in a column-stride fashion, so that it can later be used for sorting, aggregations, or scripting? Accepts `true` (default) or `false`. */ pub doc_values: Option, - /** Should the field be searchable? Accepts `not_analyzed` (default) and `no`. */ - pub index: Option, + /** Should the field be searchable? Accepts `not_analyzed` (default) and `no`. */ pub index: Option, /** Whether or not the field value should be included in the `_all` field? Accepts true or false. @@ -127,7 +125,8 @@ pub struct ElasticTokenCountFieldMapping { impl Serialize for ElasticTokenCountFieldMapping { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 8)); @@ -154,10 +153,8 @@ pub struct ElasticCompletionFieldMapping { Defaults to the default index analyzer, or the `standard` analyzer. */ pub analyzer: Option<&'static str>, - /** The search analyzer to use, defaults to value of analyzer. */ - pub search_analyzer: Option<&'static str>, - /** Enables the storing of payloads, defaults to `false`. */ - pub payloads: Option, + /** The search analyzer to use, defaults to value of analyzer. */ pub search_analyzer: Option<&'static str>, + /** Enables the storing of payloads, defaults to `false`. */ pub payloads: Option, /** Preserves the separators, defaults to `true`. If disabled, you could find a field starting with Foo Fighters, @@ -185,7 +182,8 @@ pub struct ElasticCompletionFieldMapping { impl Serialize for ElasticCompletionFieldMapping { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 7)); @@ -195,9 +193,11 @@ impl Serialize for ElasticCompletionFieldMapping { ser_field!(state, "search_analyzer", self.search_analyzer); ser_field!(state, "payloads", self.payloads); ser_field!(state, "preserve_separators", self.preserve_separators); - ser_field!(state, - "preserve_position_increments", - self.preserve_position_increments); + ser_field!( + state, + "preserve_position_increments", + self.preserve_position_increments + ); ser_field!(state, "max_input_length", self.max_input_length); state.end() @@ -222,19 +222,19 @@ pub enum IndexAnalysis { `not_analyzed` fields are usually used with term-level queries for structured search. */ NotAnalyzed, - /** Do not add this field value to the index. With this setting, the field will not be queryable. */ - No, + /** Do not add this field value to the index. With this setting, the field will not be queryable. */ No, } impl Serialize for IndexAnalysis { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_str(match *self { - IndexAnalysis::Analyzed => "analyzed", - IndexAnalysis::NotAnalyzed => "not_analyzed", - IndexAnalysis::No => "no", - }) + IndexAnalysis::Analyzed => "analyzed", + IndexAnalysis::NotAnalyzed => "not_analyzed", + IndexAnalysis::No => "no", + }) } } @@ -244,7 +244,7 @@ mod tests { use std::collections::BTreeMap; use prelude::*; - use private::field::{FieldType, DocumentField}; + use private::field::{DocumentField, FieldType}; #[derive(Default, Clone)] pub struct MyTextMapping; @@ -252,26 +252,32 @@ mod tests { fn fields() -> Option> { let mut fields = BTreeMap::new(); - fields.insert("raw", - StringField::Keyword(KeywordFieldMapping { - analyzer: Some("my_analyzer"), - ..Default::default() - })); + fields.insert( + "raw", + StringField::Keyword(KeywordFieldMapping { + analyzer: Some("my_analyzer"), + ..Default::default() + }), + ); - fields.insert("count", - StringField::TokenCount(ElasticTokenCountFieldMapping::default())); + fields.insert( + "count", + StringField::TokenCount(ElasticTokenCountFieldMapping::default()), + ); - fields.insert("comp", - StringField::Completion(ElasticCompletionFieldMapping::default())); + fields.insert( + "comp", + StringField::Completion(ElasticCompletionFieldMapping::default()), + ); Some(fields) } fn fielddata_frequency_filter() -> Option { Some(FieldDataFrequencyFilter { - min: Some(0.0), - ..Default::default() - }) + min: Some(0.0), + ..Default::default() + }) } fn analyzer() -> Option<&'static str> { @@ -341,17 +347,23 @@ mod tests { fn fields() -> Option> { let mut fields = BTreeMap::new(); - fields.insert("text", - StringField::Text(TextFieldMapping { - analyzer: Some("my_analyzer"), - ..Default::default() - })); + fields.insert( + "text", + StringField::Text(TextFieldMapping { + analyzer: Some("my_analyzer"), + ..Default::default() + }), + ); - fields.insert("count", - StringField::TokenCount(ElasticTokenCountFieldMapping::default())); + fields.insert( + "count", + StringField::TokenCount(ElasticTokenCountFieldMapping::default()), + ); - fields.insert("comp", - StringField::Completion(ElasticCompletionFieldMapping::default())); + fields.insert( + "comp", + StringField::Completion(ElasticCompletionFieldMapping::default()), + ); Some(fields) } @@ -555,18 +567,12 @@ mod tests { IndexOptions::Docs, IndexOptions::Freqs, IndexOptions::Positions, - IndexOptions::Offsets - ] - .iter() - .map(|i| serde_json::to_string(i).unwrap()) - .collect(); + IndexOptions::Offsets, + ].iter() + .map(|i| serde_json::to_string(i).unwrap()) + .collect(); - let expected_opts = vec![ - r#""docs""#, - r#""freqs""#, - r#""positions""#, - r#""offsets""# - ]; + let expected_opts = vec![r#""docs""#, r#""freqs""#, r#""positions""#, r#""offsets""#]; let mut success = true; for i in 0..io_opts.len() { @@ -586,18 +592,17 @@ mod tests { TermVector::Yes, TermVector::WithPositions, TermVector::WithOffsets, - TermVector::WithPositionsOffsets - ] - .iter() - .map(|i| serde_json::to_string(i).unwrap()) - .collect(); + TermVector::WithPositionsOffsets, + ].iter() + .map(|i| serde_json::to_string(i).unwrap()) + .collect(); let expected_opts = vec![ r#""no""#, r#""yes""#, r#""with_positions""#, r#""with_offsets""#, - r#""with_positions_offsets""# + r#""with_positions_offsets""#, ]; let mut success = true; @@ -614,18 +619,18 @@ mod tests { #[test] fn serialise_mapping_keyword_field() { let mapping = StringField::Keyword(KeywordFieldMapping { - analyzer: Some("my_analyzer"), - doc_values: Some(true), - eager_global_ordinals: Some(false), - include_in_all: Some(true), - ignore_above: Some(256), - index: Some(false), - index_options: Some(IndexOptions::Docs), - norms: Some(true), - store: Some(true), - search_analyzer: Some("my_analyzer"), - similarity: Some("my_analyzer"), - }); + analyzer: Some("my_analyzer"), + doc_values: Some(true), + eager_global_ordinals: Some(false), + include_in_all: Some(true), + ignore_above: Some(256), + index: Some(false), + index_options: Some(IndexOptions::Docs), + norms: Some(true), + store: Some(true), + search_analyzer: Some("my_analyzer"), + similarity: Some("my_analyzer"), + }); let ser = serde_json::to_string(&mapping).unwrap(); let expected = json_str!({ @@ -649,25 +654,25 @@ mod tests { #[test] fn serialise_mapping_text_field() { let mapping = StringField::Text(TextFieldMapping { - fielddata_frequency_filter: Some(FieldDataFrequencyFilter { - min: Some(0.0), - ..Default::default() - }), - analyzer: Some("my_analyzer"), - eager_global_ordinals: Some(true), - fielddata: Some(false), - include_in_all: Some(false), - ignore_above: Some(512), - index: Some(true), - index_options: Some(IndexOptions::Freqs), - norms: Some(true), - position_increment_gap: Some(1), - store: Some(false), - search_analyzer: Some("my_analyzer"), - search_quote_analyzer: Some("my_analyzer"), - similarity: Some("BM25"), - term_vector: Some(TermVector::No), - }); + fielddata_frequency_filter: Some(FieldDataFrequencyFilter { + min: Some(0.0), + ..Default::default() + }), + analyzer: Some("my_analyzer"), + eager_global_ordinals: Some(true), + fielddata: Some(false), + include_in_all: Some(false), + ignore_above: Some(512), + index: Some(true), + index_options: Some(IndexOptions::Freqs), + norms: Some(true), + position_increment_gap: Some(1), + store: Some(false), + search_analyzer: Some("my_analyzer"), + search_quote_analyzer: Some("my_analyzer"), + similarity: Some("BM25"), + term_vector: Some(TermVector::No), + }); let ser = serde_json::to_string(&mapping).unwrap(); let expected = json_str!({ @@ -697,14 +702,14 @@ mod tests { #[test] fn serialise_mapping_token_count_field() { let mapping = StringField::TokenCount(ElasticTokenCountFieldMapping { - analyzer: Some("my_analyzer"), - boost: Some(1.3), - doc_values: Some(false), - index: Some(IndexAnalysis::No), - include_in_all: Some(true), - precision_step: Some(15), - store: Some(true), - }); + analyzer: Some("my_analyzer"), + boost: Some(1.3), + doc_values: Some(false), + index: Some(IndexAnalysis::No), + include_in_all: Some(true), + precision_step: Some(15), + store: Some(true), + }); let ser = serde_json::to_string(&mapping).unwrap(); let expected = json_str!({ @@ -724,13 +729,13 @@ mod tests { #[test] fn serialise_mapping_completion_field() { let mapping = StringField::Completion(ElasticCompletionFieldMapping { - analyzer: Some("my_analyzer"), - search_analyzer: Some("my_analyzer"), - payloads: Some(true), - preserve_separators: Some(false), - preserve_position_increments: Some(true), - max_input_length: Some(512), - }); + analyzer: Some("my_analyzer"), + search_analyzer: Some("my_analyzer"), + payloads: Some(true), + preserve_separators: Some(false), + preserve_position_increments: Some(true), + max_input_length: Some(512), + }); let ser = serde_json::to_string(&mapping).unwrap(); let expected = json_str!({ diff --git a/src/types/src/string/text/impls.rs b/src/types/src/string/text/impls.rs index 0d929bcf1a..3af8f4ec96 100644 --- a/src/types/src/string/text/impls.rs +++ b/src/types/src/string/text/impls.rs @@ -1,7 +1,7 @@ use std::borrow::Borrow; use std::marker::PhantomData; -use serde::{Serialize, Deserialize, Serializer, Deserializer}; -use serde::de::{Visitor, Error}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde::de::{Error, Visitor}; use super::mapping::{TextFieldType, TextMapping}; use string::mapping::DefaultStringMapping; @@ -25,13 +25,17 @@ let string = Text::::new("my string value"); ``` */ #[derive(Debug, Clone, Default, PartialEq)] -pub struct Text where TMapping: TextMapping { +pub struct Text +where + TMapping: TextMapping, +{ value: String, _m: PhantomData, } impl Text - where TMapping: TextMapping +where + TMapping: TextMapping, { /** Creates a new `Text` with the given mapping. @@ -48,7 +52,8 @@ impl Text ``` */ pub fn new(string: I) -> Text - where I: Into + where + I: Into, { Text { value: string.into(), @@ -58,7 +63,8 @@ impl Text /** Change the mapping of this string. */ pub fn remap(text: Text) -> Text - where TNewMapping: TextMapping + where + TNewMapping: TextMapping, { Text::new(text.value) } diff --git a/src/types/src/string/text/mapping.rs b/src/types/src/string/text/mapping.rs index 6b1592e6f3..ed9e970838 100644 --- a/src/types/src/string/text/mapping.rs +++ b/src/types/src/string/text/mapping.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; -use string::mapping::{StringField, IndexOptions}; +use string::mapping::{IndexOptions, StringField}; use private::field::FieldMapping; /** A field that will be mapped as `text`. */ @@ -69,7 +69,8 @@ This will produce the following mapping: ``` */ pub trait TextMapping - where Self: Default +where + Self: Default, { /** The analyzer which should be used for analyzed string fields, @@ -244,46 +245,40 @@ impl TextMapping for DefaultTextMapping {} /** Term vectors contain information about the terms produced by the analysis process. */ #[derive(Debug, Clone, Copy)] pub enum TermVector { - /** No term vectors are stored. (default) */ - No, - /** Just the terms in the field are stored. */ - Yes, - /** Terms and positions are stored. */ - WithPositions, - /** Terms and character offsets are stored. */ - WithOffsets, - /** Terms, positions, and character offsets are stored. */ - WithPositionsOffsets, + /** No term vectors are stored. (default) */ No, + /** Just the terms in the field are stored. */ Yes, + /** Terms and positions are stored. */ WithPositions, + /** Terms and character offsets are stored. */ WithOffsets, + /** Terms, positions, and character offsets are stored. */ WithPositionsOffsets, } impl Serialize for TermVector { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_str(match *self { - TermVector::No => "no", - TermVector::Yes => "yes", - TermVector::WithPositions => "with_positions", - TermVector::WithOffsets => "with_offsets", - TermVector::WithPositionsOffsets => "with_positions_offsets", - }) + TermVector::No => "no", + TermVector::Yes => "yes", + TermVector::WithPositions => "with_positions", + TermVector::WithOffsets => "with_offsets", + TermVector::WithPositionsOffsets => "with_positions_offsets", + }) } } /** Fielddata for term frequency as a percentage range. */ #[derive(Debug, Default, PartialEq, Clone, Copy)] pub struct FieldDataFrequencyFilter { - /** The min frequency percentage. */ - pub min: Option, - /** The max frequency percentage. */ - pub max: Option, - /** The minimum number of docs a segment should contain. */ - pub min_segment_size: Option, + /** The min frequency percentage. */ pub min: Option, + /** The max frequency percentage. */ pub max: Option, + /** The minimum number of docs a segment should contain. */ pub min_segment_size: Option, } impl Serialize for FieldDataFrequencyFilter { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 3)); @@ -332,12 +327,9 @@ pub struct TextFieldMapping { Any characters over this length will be ignored. */ pub ignore_above: Option, - /** Should the field be searchable? Accepts `true` (default) or `false`. */ - pub index: Option, - /** What information should be stored in the index, for search and highlighting purposes. Defaults to `Positions`. */ - pub index_options: Option, - /** Whether field-length should be taken into account when scoring queries. Accepts `true` (default) or `false`. */ - pub norms: Option, + /** Should the field be searchable? Accepts `true` (default) or `false`. */ pub index: Option, + /** What information should be stored in the index, for search and highlighting purposes. Defaults to `Positions`. */ pub index_options: Option, + /** Whether field-length should be taken into account when scoring queries. Accepts `true` (default) or `false`. */ pub norms: Option, /** The number of fake term position which should be inserted between each element of an array of strings. Defaults to the `position_increment_gap` configured on the analyzer which defaults to `100`. @@ -374,7 +366,8 @@ pub struct TextFieldMapping { impl Serialize for TextFieldMapping { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 16)); @@ -383,9 +376,11 @@ impl Serialize for TextFieldMapping { ser_field!(state, "analyzer", self.analyzer); ser_field!(state, "eager_global_ordinals", self.eager_global_ordinals); ser_field!(state, "fielddata", self.fielddata); - ser_field!(state, - "fielddata_frequency_filter", - self.fielddata_frequency_filter); + ser_field!( + state, + "fielddata_frequency_filter", + self.fielddata_frequency_filter + ); ser_field!(state, "include_in_all", self.include_in_all); ser_field!(state, "ignore_above", self.ignore_above); ser_field!(state, "index", self.index); @@ -405,19 +400,22 @@ impl Serialize for TextFieldMapping { mod private { use serde::{Serialize, Serializer}; use serde::ser::SerializeStruct; - use private::field::{FieldType, DocumentField, FieldMapping}; + use private::field::{DocumentField, FieldMapping, FieldType}; use super::{TextFieldType, TextMapping}; #[derive(Default)] pub struct TextPivot; impl FieldType for TField - where TField: TextFieldType + Serialize, - TMapping: TextMapping - { } + where + TField: TextFieldType + Serialize, + TMapping: TextMapping, + { + } impl FieldMapping for TMapping - where TMapping: TextMapping + where + TMapping: TextMapping, { type DocumentField = DocumentField; @@ -427,10 +425,12 @@ mod private { } impl Serialize for DocumentField - where TMapping: FieldMapping + TextMapping + where + TMapping: FieldMapping + TextMapping, { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { let mut state = try!(serializer.serialize_struct("mapping", 18)); @@ -438,21 +438,35 @@ mod private { ser_field!(state, "boost", TMapping::boost()); ser_field!(state, "analyzer", TMapping::analyzer()); - ser_field!(state, "eager_global_ordinals", TMapping::eager_global_ordinals()); + ser_field!( + state, + "eager_global_ordinals", + TMapping::eager_global_ordinals() + ); ser_field!(state, "fielddata", TMapping::fielddata()); - ser_field!(state, - "fielddata_frequency_filter", - TMapping::fielddata_frequency_filter()); + ser_field!( + state, + "fielddata_frequency_filter", + TMapping::fielddata_frequency_filter() + ); ser_field!(state, "fields", TMapping::fields()); ser_field!(state, "include_in_all", TMapping::include_in_all()); ser_field!(state, "ignore_above", TMapping::ignore_above()); ser_field!(state, "index", TMapping::index()); ser_field!(state, "index_options", TMapping::index_options()); ser_field!(state, "norms", TMapping::norms()); - ser_field!(state, "position_increment_gap", TMapping::position_increment_gap()); + ser_field!( + state, + "position_increment_gap", + TMapping::position_increment_gap() + ); ser_field!(state, "store", TMapping::store()); ser_field!(state, "search_analyzer", TMapping::search_analyzer()); - ser_field!(state, "search_quote_analyzer", TMapping::search_quote_analyzer()); + ser_field!( + state, + "search_quote_analyzer", + TMapping::search_quote_analyzer() + ); ser_field!(state, "similarity", TMapping::similarity()); ser_field!(state, "term_vector", TMapping::term_vector()); diff --git a/src/types_derive/src/lib.rs b/src/types_derive/src/lib.rs index 921a1f5d3d..006aeceed6 100644 --- a/src/types_derive/src/lib.rs +++ b/src/types_derive/src/lib.rs @@ -10,12 +10,12 @@ Elasticsearch Core Types Codegen extern crate proc_macro; -extern crate syn; +extern crate elastic_types_derive_internals as internals; #[macro_use] extern crate quote; -extern crate elastic_types_derive_internals as internals; +extern crate syn; -use internals::{elastic_type, date_format}; +use internals::{date_format, elastic_type}; #[proc_macro_derive(ElasticType, attributes(elastic))] pub fn derive_elastic_type(input: proc_macro::TokenStream) -> proc_macro::TokenStream { @@ -27,8 +27,8 @@ pub fn derive_elastic_type(input: proc_macro::TokenStream) -> proc_macro::TokenS expanded.append_all(genned); expanded.to_string().parse().unwrap() - }, - Err(e) => panic!("{}", e) + } + Err(e) => panic!("{}", e), } } @@ -42,7 +42,7 @@ pub fn derive_date_format(input: proc_macro::TokenStream) -> proc_macro::TokenSt expanded.append_all(genned); expanded.to_string().parse().unwrap() - }, - Err(e) => panic!("{}", e) + } + Err(e) => panic!("{}", e), } } diff --git a/src/types_derive_internals/src/date_format/mod.rs b/src/types_derive_internals/src/date_format/mod.rs index 65b1dd5da4..0ca03b0b4e 100644 --- a/src/types_derive_internals/src/date_format/mod.rs +++ b/src/types_derive_internals/src/date_format/mod.rs @@ -13,17 +13,13 @@ The input must satisfy the following rules: - It must be a unit struct. - It must have an `#[elastic(date_format="")]` attribute. */ -pub fn expand_derive(crate_root: Tokens, - input: &syn::MacroInput) - -> Result, DeriveDateFormatError> { +pub fn expand_derive(crate_root: Tokens, input: &syn::MacroInput) -> Result, DeriveDateFormatError> { // Annotatable item for a unit struct match input.body { - syn::Body::Struct(ref data) => { - match *data { - syn::VariantData::Unit => Ok(()), - _ => Err(DeriveDateFormatError::InvalidInput), - } - } + syn::Body::Struct(ref data) => match *data { + syn::VariantData::Unit => Ok(()), + _ => Err(DeriveDateFormatError::InvalidInput), + }, _ => Err(DeriveDateFormatError::InvalidInput), }?; @@ -31,8 +27,7 @@ pub fn expand_derive(crate_root: Tokens, let name = get_name_from_attr(input).unwrap_or(format); - let tokens: Vec = parse::to_tokens(format) - ? + let tokens: Vec = parse::to_tokens(format)? .into_iter() .map(|t| t.into_tokens(&crate_root)) .collect(); @@ -43,11 +38,7 @@ pub fn expand_derive(crate_root: Tokens, } // Implement DateFormat for the type being derived with the mapping -fn impl_date_format(crate_root: Tokens, - item: &syn::MacroInput, - name: &str, - format: &[Tokens]) - -> Tokens { +fn impl_date_format(crate_root: Tokens, item: &syn::MacroInput, name: &str, format: &[Tokens]) -> Tokens { let ty = &item.ident; let parse_fn = quote!( @@ -109,9 +100,7 @@ impl<'a> parse::DateFormatToken<'a> { Hour => quote!(#crate_root::derive::Item::Numeric(#crate_root::derive::Numeric::Hour, #crate_root::derive::Pad::Zero)), Minute => quote!(#crate_root::derive::Item::Numeric(#crate_root::derive::Numeric::Minute, #crate_root::derive::Pad::Zero)), Second => quote!(#crate_root::derive::Item::Numeric(#crate_root::derive::Numeric::Second, #crate_root::derive::Pad::Zero)), - Millisecond => { - quote!(#crate_root::derive::Item::Fixed(#crate_root::derive::Fixed::Nanosecond3)) - } + Millisecond => quote!(#crate_root::derive::Item::Fixed(#crate_root::derive::Fixed::Nanosecond3)), Utc => quote!(#crate_root::derive::Item::Literal("Z")), Delim(s) => quote!(#crate_root::derive::Item::Literal(#s)), Escaped(s) => quote!(#crate_root::derive::Item::Literal(#s)), diff --git a/src/types_derive_internals/src/date_format/parse.rs b/src/types_derive_internals/src/date_format/parse.rs index c3e1c77342..f2a8eac85d 100644 --- a/src/types_derive_internals/src/date_format/parse.rs +++ b/src/types_derive_internals/src/date_format/parse.rs @@ -155,22 +155,37 @@ mod tests { #[test] fn parse_basic_date_time() { - assert_parse(b"yyyyMMdd'T'HHmmss.SSSZ", - vec![Year, - Month, - DayOfMonth, - Escaped("T"), - Hour, - Minute, - Second, - Millisecond, - Utc]); + assert_parse( + b"yyyyMMdd'T'HHmmss.SSSZ", + vec![ + Year, + Month, + DayOfMonth, + Escaped("T"), + Hour, + Minute, + Second, + Millisecond, + Utc, + ], + ); } #[test] fn parse_basic_date_time_no_millis() { - assert_parse(b"yyyyMMdd'T'HHmmssZ", - vec![Year, Month, DayOfMonth, Escaped("T"), Hour, Minute, Second, Utc]); + assert_parse( + b"yyyyMMdd'T'HHmmssZ", + vec![ + Year, + Month, + DayOfMonth, + Escaped("T"), + Hour, + Minute, + Second, + Utc, + ], + ); } #[test] @@ -180,18 +195,22 @@ mod tests { #[test] fn parse_date_hour_minute_second_millis() { - assert_parse(b"yyyy-MM-dd'T'HH:mm:ss.SSS", - vec![Year, - Delim("-"), - Month, - Delim("-"), - DayOfMonth, - Escaped("T"), - Hour, - Delim(":"), - Minute, - Delim(":"), - Second, - Millisecond]); + assert_parse( + b"yyyy-MM-dd'T'HH:mm:ss.SSS", + vec![ + Year, + Delim("-"), + Month, + Delim("-"), + DayOfMonth, + Escaped("T"), + Hour, + Delim(":"), + Minute, + Delim(":"), + Second, + Millisecond, + ], + ); } } diff --git a/src/types_derive_internals/src/elastic_type/mod.rs b/src/types_derive_internals/src/elastic_type/mod.rs index 33eb84e246..74178770bd 100644 --- a/src/types_derive_internals/src/elastic_type/mod.rs +++ b/src/types_derive_internals/src/elastic_type/mod.rs @@ -13,24 +13,21 @@ The input must satisfy the following rules: - A mapping type supplied by `#[elastic(mapping="")]` must implement `DocumentMapping`, but not `PropertiesMapping`. */ -pub fn expand_derive(crate_root: Tokens, - input: &syn::MacroInput) - -> Result, DeriveElasticTypeError> { +pub fn expand_derive(crate_root: Tokens, input: &syn::MacroInput) -> Result, DeriveElasticTypeError> { // Annotatable item for a struct with struct fields let fields = match input.body { - syn::Body::Struct(ref data) => { - match *data { - syn::VariantData::Struct(ref fields) => Some(fields), - _ => None, - } - } + syn::Body::Struct(ref data) => match *data { + syn::VariantData::Struct(ref fields) => Some(fields), + _ => None, + }, _ => None, }; let fields = fields.ok_or(DeriveElasticTypeError::InvalidInput)?; // Get the serializable fields - let fields: Vec<(syn::Ident, &syn::Field)> = fields.iter() + let fields: Vec<(syn::Ident, &syn::Field)> = fields + .iter() .map(|f| get_ser_field(f)) .filter(|f| f.is_some()) .map(|f| f.unwrap()) @@ -54,13 +51,16 @@ pub fn expand_derive(crate_root: Tokens, }; let impl_elastic_ty = impl_elastic_ty(crate_root.clone(), input, &mapping_ty); - let impl_props_mapping = impl_props_mapping(crate_root.clone(), - &mapping_ty, - get_props_ser_stmts(crate_root.clone(), &fields)); + let impl_props_mapping = impl_props_mapping( + crate_root.clone(), + &mapping_ty, + get_props_ser_stmts(crate_root.clone(), &fields), + ); let dummy_wrapper = syn::Ident::new(format!("_IMPL_EASTIC_TYPE_FOR_{}", input.ident)); - Ok(vec![quote!( + Ok(vec![ + quote!( #define_mapping #[allow(non_upper_case_globals, dead_code, unused_variables)] @@ -71,7 +71,8 @@ pub fn expand_derive(crate_root: Tokens, #impl_props_mapping }; - )]) + ), + ]) } // Define a struct for the mapping with a few defaults @@ -103,10 +104,7 @@ fn impl_object_mapping(crate_root: Tokens, mapping: &syn::Ident, es_ty: &syn::Li } // Implement PropertiesMapping for the mapping -fn impl_props_mapping(crate_root: Tokens, - mapping: &syn::Ident, - prop_ser_stmts: Vec) - -> Tokens { +fn impl_props_mapping(crate_root: Tokens, mapping: &syn::Ident, prop_ser_stmts: Vec) -> Tokens { let stmts_len = prop_ser_stmts.len(); let stmts = prop_ser_stmts; @@ -125,7 +123,8 @@ fn impl_props_mapping(crate_root: Tokens, // Get the serde serialisation statements for each of the fields on the type being derived fn get_props_ser_stmts(crate_root: Tokens, fields: &[(syn::Ident, &syn::Field)]) -> Vec { - let fields: Vec = fields.iter() + let fields: Vec = fields + .iter() .cloned() .map(|(name, field)| { let lit = syn::Lit::Str(name.as_ref().to_string(), syn::StrStyle::Cooked); @@ -154,8 +153,10 @@ fn get_default_mapping(item: &syn::MacroInput) -> syn::Ident { // Get the default name for the indexed elasticsearch type name fn get_elastic_type_name(item: &syn::MacroInput) -> syn::Lit { - syn::Lit::Str(format!("{}", item.ident).to_lowercase(), - syn::StrStyle::Cooked) + syn::Lit::Str( + format!("{}", item.ident).to_lowercase(), + syn::StrStyle::Cooked, + ) } fn get_ser_field(field: &syn::Field) -> Option<(syn::Ident, &syn::Field)> { @@ -173,7 +174,10 @@ fn get_ser_field(field: &syn::Field) -> Option<(syn::Ident, &syn::Field)> { return None; } - Some((syn::Ident::from(serde_field.name().serialize_name().as_ref()), field)) + Some(( + syn::Ident::from(serde_field.name().serialize_name().as_ref()), + field, + )) } quick_error! { diff --git a/src/types_derive_internals/src/lib.rs b/src/types_derive_internals/src/lib.rs index fccc202a2f..4bd00483d8 100644 --- a/src/types_derive_internals/src/lib.rs +++ b/src/types_derive_internals/src/lib.rs @@ -4,7 +4,7 @@ Elasticsearch Core Types Codegen This crate contains the internals for `elastic_types`-related codegen. */ -#![recursion_limit="128"] +#![recursion_limit = "128"] #[macro_use] extern crate quote; @@ -17,8 +17,8 @@ extern crate quick_error; extern crate nom; extern crate serde; -extern crate serde_json; extern crate serde_derive_internals; +extern crate serde_json; extern crate chrono; @@ -39,8 +39,7 @@ fn get_elastic_attr_name_value<'a>(name: &str, item: &'a syn::MacroInput) -> Opt for meta_item in meta_items { match *meta_item { // Parse `#[elastic({name}="foo")]` - syn::NestedMetaItem::MetaItem(syn::MetaItem::NameValue(ref key, ref lit)) - if key == name => { + syn::NestedMetaItem::MetaItem(syn::MetaItem::NameValue(ref key, ref lit)) if key == name => { return Some(lit); } _ => (), diff --git a/tests/run/src/build_client.rs b/tests/run/src/build_client.rs index 315925aac5..c03c756646 100644 --- a/tests/run/src/build_client.rs +++ b/tests/run/src/build_client.rs @@ -5,6 +5,6 @@ use elastic::Error; pub fn call(handle: &Handle, run: &str) -> Result { match run { // Get a default client - _ => AsyncClientBuilder::new().build(handle) + _ => AsyncClientBuilder::new().build(handle), } } diff --git a/tests/run/src/build_container.rs b/tests/run/src/build_container.rs index a72e22e66a..41fdfaaa21 100644 --- a/tests/run/src/build_container.rs +++ b/tests/run/src/build_container.rs @@ -31,14 +31,29 @@ pub fn start(run: &str) -> Result<(), Box> { // Build the container Command::new("docker") - .args(&["build", "-f", &names.build_path, "-t", &names.build_name, "."]) + .args(&[ + "build", + "-f", + &names.build_path, + "-t", + &names.build_name, + ".", + ]) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .output()?; // Start the container Command::new("docker") - .args(&["run", "-itd", "-p", "9200:9200", "--name", &names.container_name, &names.build_name]) + .args(&[ + "run", + "-itd", + "-p", + "9200:9200", + "--name", + &names.container_name, + &names.build_name, + ]) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .output()?; @@ -60,6 +75,6 @@ pub fn kill(run: &str) -> Result<(), Box> { .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .output()?; - + Ok(()) } diff --git a/tests/run/src/main.rs b/tests/run/src/main.rs index 313c345ad0..1202dd6e22 100644 --- a/tests/run/src/main.rs +++ b/tests/run/src/main.rs @@ -6,13 +6,13 @@ They should ensure that `elastic` behaves as expected when making requests, inde They should also provide a way to inspect how the client behaves under load and where memory is being allocated. */ -extern crate term_painter; +extern crate elastic; extern crate futures; +extern crate serde; +extern crate serde_json; +extern crate term_painter; extern crate tokio_core; extern crate tokio_timer; -extern crate serde_json; -extern crate serde; -extern crate elastic; use std::process; use term_painter::ToStyle; @@ -33,20 +33,34 @@ fn main() { build_container::start(run).unwrap(); // Wait until the container is ready - core.run(wait_until_ready::call(client.clone(), 60)).unwrap(); + core.run(wait_until_ready::call(client.clone(), 60)) + .unwrap(); // Run the integration tests let results = core.run(run_tests::call(client, 8)).unwrap(); - let failed: Vec<_> = results.iter().filter(|success| **success == false).collect(); + let failed: Vec<_> = results + .iter() + .filter(|success| **success == false) + .collect(); // Kill the container build_container::kill(run).unwrap(); if failed.len() > 0 { - println!("{}", Red.bold().paint(format!("{} of {} tests failed", failed.len(), results.len()))); + println!( + "{}", + Red.bold().paint(format!( + "{} of {} tests failed", + failed.len(), + results.len() + )) + ); process::exit(1); } else { - println!("{}", Green.paint(format!("all {} tests passed", results.len()))); + println!( + "{}", + Green.paint(format!("all {} tests passed", results.len())) + ); process::exit(0); } } diff --git a/tests/run/src/run_tests.rs b/tests/run/src/run_tests.rs index 8dcb23ef93..db7f2bccfb 100644 --- a/tests/run/src/run_tests.rs +++ b/tests/run/src/run_tests.rs @@ -37,8 +37,9 @@ pub trait IntegrationTest: Debug { } } -pub fn test(client: AsyncClient, test: T) -> Box> - where T: IntegrationTest + Send + 'static +pub fn test(client: AsyncClient, test: T) -> Box> +where + T: IntegrationTest + Send + 'static, { let prefix = format!("{}: {} ({:?}):", T::kind(), T::name(), test); @@ -47,41 +48,33 @@ pub fn test(client: AsyncClient, test: T) -> Box { - println!("{} {:?}", Red.bold().paint(prep_failed), e); - Err(()) - }, - _ => Ok(test) + let fut = test.prepare(client.clone()) + .then(move |prep| match prep { + Err(ref e) if !test.prepare_err(e) => { + println!("{} {:?}", Red.bold().paint(prep_failed), e); + Err(()) } + _ => Ok(test), }) .and_then(move |test| { - test.request(client.clone()) - .then(move |res| { - match res { - Ok(ref res) if !test.assert_ok(res) => { - println!("{} {:?}", Red.bold().paint(assert_ok_failed), res); - Err(()) - }, - Err(ref e) if !test.assert_err(e) => { - println!("{} {:?}", Red.bold().paint(assert_err_failed), e); - Err(()) - }, - _ => { - println!("{}", Green.paint(ok)); - Ok(true) - } - } - }) + test.request(client.clone()).then(move |res| match res { + Ok(ref res) if !test.assert_ok(res) => { + println!("{} {:?}", Red.bold().paint(assert_ok_failed), res); + Err(()) + } + Err(ref e) if !test.assert_err(e) => { + println!("{} {:?}", Red.bold().paint(assert_err_failed), e); + Err(()) + } + _ => { + println!("{}", Green.paint(ok)); + Ok(true) + } + }) }) - .then(|outcome| { - match outcome { - Err(_) => Ok(false), - outcome => outcome - } + .then(|outcome| match outcome { + Err(_) => Ok(false), + outcome => outcome, }); Box::new(fut) @@ -90,10 +83,8 @@ pub fn test(client: AsyncClient, test: T) -> Box Box, Error = ()>> { use search; - let search_tests = search::tests() - .into_iter() - .map(move |t| t(client.clone())); - + let search_tests = search::tests().into_iter().map(move |t| t(client.clone())); + let test_stream = stream::futures_unordered(search_tests) .map(|r| Ok(r)) .buffer_unordered(max_concurrent_tests); diff --git a/tests/run/src/search/mod.rs b/tests/run/src/search/mod.rs index e57663c1b7..95d1812396 100644 --- a/tests/run/src/search/mod.rs +++ b/tests/run/src/search/mod.rs @@ -3,7 +3,5 @@ use run_tests::{test, Test}; mod no_index; pub fn tests() -> Vec { - vec![ - Box::new(|client| test(client, no_index::NoIndex)) - ] + vec![Box::new(|client| test(client, no_index::NoIndex))] } diff --git a/tests/run/src/search/no_index.rs b/tests/run/src/search/no_index.rs index e6c2033992..4806f284c8 100644 --- a/tests/run/src/search/no_index.rs +++ b/tests/run/src/search/no_index.rs @@ -1,7 +1,7 @@ use serde_json::Value; use futures::Future; use elastic::prelude::*; -use elastic::error::{Error, ApiError}; +use elastic::error::{ApiError, Error}; use run_tests::IntegrationTest; #[derive(Debug, Clone, Copy)] @@ -10,25 +10,31 @@ pub struct NoIndex; impl IntegrationTest for NoIndex { type Response = SearchResponse; - fn kind() -> &'static str { "search" } - fn name() -> &'static str { "no_index" } + fn kind() -> &'static str { + "search" + } + fn name() -> &'static str { + "no_index" + } // Ensure the index doesn't exist fn prepare(&self, client: AsyncClient) -> Box> { - let req = client.request(IndicesDeleteRequest::for_index("no_index_idx")) - .send() - .map(|_| ()); - + let req = client + .request(IndicesDeleteRequest::for_index("no_index_idx")) + .send() + .map(|_| ()); + Box::new(req) } // Execute a search request against that index fn request(&self, client: AsyncClient) -> Box> { - let res = client.search() - .index("no_index_idx") - .ty(Some("no_index_ty")) - .send(); - + let res = client + .search() + .index("no_index_idx") + .ty(Some("no_index_ty")) + .send(); + Box::new(res) } @@ -36,7 +42,7 @@ impl IntegrationTest for NoIndex { fn assert_err(&self, err: &Error) -> bool { match *err { Error::Api(ApiError::IndexNotFound { .. }) => true, - _ => false + _ => false, } } } diff --git a/tests/run/src/wait_until_ready.rs b/tests/run/src/wait_until_ready.rs index d58682c956..7e118fbc3b 100644 --- a/tests/run/src/wait_until_ready.rs +++ b/tests/run/src/wait_until_ready.rs @@ -12,11 +12,14 @@ struct Ping { impl Ping { fn is_not_ready(&self) -> Box>> { - let request = self.client.request(PingRequest::new()).send().map_err(|e| e.into()); + let request = self.client + .request(PingRequest::new()) + .send() + .map_err(|e| e.into()); let check = request.then(|res: Result| match res { Ok(_) => Ok(false), - _ => Ok(true) + _ => Ok(true), }); Box::new(check) @@ -24,7 +27,10 @@ impl Ping { } pub fn call(client: AsyncClient, timeout_secs: u64) -> Box>> { - println!("waiting up to {}s until the cluster is ready...", timeout_secs); + println!( + "waiting up to {}s until the cluster is ready...", + timeout_secs + ); let timer = Timer::default(); let stream = stream::repeat(Ping { client: client });