Skip to content

Commit 01cc7e4

Browse files
committed
Clean up derived code
1 parent e62fe3d commit 01cc7e4

File tree

9 files changed

+113
-114
lines changed

9 files changed

+113
-114
lines changed

postgres-derive/src/fromsql.rs

Lines changed: 23 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -59,16 +59,16 @@ pub fn expand_derive_fromsql(input: DeriveInput) -> Result<TokenStream, Error> {
5959

6060
let ident = &input.ident;
6161
let out = quote! {
62-
impl<'a> ::postgres_types::FromSql<'a> for #ident {
63-
fn from_sql(_type: &::postgres_types::Type, buf: &'a [u8])
64-
-> ::std::result::Result<#ident,
65-
::std::boxed::Box<::std::error::Error +
66-
::std::marker::Sync +
67-
::std::marker::Send>> {
62+
impl<'a> postgres_types::FromSql<'a> for #ident {
63+
fn from_sql(_type: &postgres_types::Type, buf: &'a [u8])
64+
-> std::result::Result<#ident,
65+
std::boxed::Box<dyn std::error::Error +
66+
std::marker::Sync +
67+
std::marker::Send>> {
6868
#to_sql_body
6969
}
7070

71-
fn accepts(type_: &::postgres_types::Type) -> bool {
71+
fn accepts(type_: &postgres_types::Type) -> bool {
7272
#accepts_body
7373
}
7474
}
@@ -83,13 +83,13 @@ fn enum_body(ident: &Ident, variants: &[Variant]) -> TokenStream {
8383
let variant_idents = variants.iter().map(|v| &v.ident);
8484

8585
quote! {
86-
match ::std::str::from_utf8(buf)? {
86+
match std::str::from_utf8(buf)? {
8787
#(
88-
#variant_names => ::std::result::Result::Ok(#idents::#variant_idents),
88+
#variant_names => std::result::Result::Ok(#idents::#variant_idents),
8989
)*
9090
s => {
91-
::std::result::Result::Err(
92-
::std::convert::Into::into(format!("invalid variant `{}`", s)))
91+
std::result::Result::Err(
92+
std::convert::Into::into(format!("invalid variant `{}`", s)))
9393
}
9494
}
9595
}
@@ -101,7 +101,7 @@ fn domain_accepts_body(name: &str, field: &syn::Field) -> TokenStream {
101101
let normal_body = accepts::domain_body(name, field);
102102

103103
quote! {
104-
if <#ty as ::postgres_types::FromSql>::accepts(type_) {
104+
if <#ty as postgres_types::FromSql>::accepts(type_) {
105105
return true;
106106
}
107107

@@ -112,7 +112,7 @@ fn domain_accepts_body(name: &str, field: &syn::Field) -> TokenStream {
112112
fn domain_body(ident: &Ident, field: &syn::Field) -> TokenStream {
113113
let ty = &field.ty;
114114
quote! {
115-
<#ty as ::postgres_types::FromSql>::from_sql(_type, buf).map(#ident)
115+
<#ty as postgres_types::FromSql>::from_sql(_type, buf).map(#ident)
116116
}
117117
}
118118

@@ -125,74 +125,40 @@ fn composite_body(ident: &Ident, fields: &[Field]) -> TokenStream {
125125
let field_idents = &fields.iter().map(|f| &f.ident).collect::<Vec<_>>();
126126

127127
quote! {
128-
fn read_be_i32(buf: &mut &[u8]) -> ::std::io::Result<i32> {
129-
let mut bytes = [0; 4];
130-
::std::io::Read::read_exact(buf, &mut bytes)?;
131-
let num = ((bytes[0] as i32) << 24) |
132-
((bytes[1] as i32) << 16) |
133-
((bytes[2] as i32) << 8) |
134-
(bytes[3] as i32);
135-
::std::result::Result::Ok(num)
136-
}
137-
138-
fn read_value<'a, T>(type_: &::postgres_types::Type,
139-
buf: &mut &'a [u8])
140-
-> ::std::result::Result<T,
141-
::std::boxed::Box<::std::error::Error +
142-
::std::marker::Sync +
143-
::std::marker::Send>>
144-
where T: ::postgres_types::FromSql<'a>
145-
{
146-
let len = read_be_i32(buf)?;
147-
let value = if len < 0 {
148-
::std::option::Option::None
149-
} else {
150-
if len as usize > buf.len() {
151-
return ::std::result::Result::Err(
152-
::std::convert::Into::into("invalid buffer size"));
153-
}
154-
let (head, tail) = buf.split_at(len as usize);
155-
*buf = tail;
156-
::std::option::Option::Some(&head[..])
157-
};
158-
::postgres_types::FromSql::from_sql_nullable(type_, value)
159-
}
160-
161128
let fields = match *_type.kind() {
162-
::postgres_types::Kind::Composite(ref fields) => fields,
129+
postgres_types::Kind::Composite(ref fields) => fields,
163130
_ => unreachable!(),
164131
};
165132

166133
let mut buf = buf;
167-
let num_fields = read_be_i32(&mut buf)?;
134+
let num_fields = postgres_types::private::read_be_i32(&mut buf)?;
168135
if num_fields as usize != fields.len() {
169-
return ::std::result::Result::Err(
170-
::std::convert::Into::into(format!("invalid field count: {} vs {}", num_fields,
171-
fields.len())));
136+
return std::result::Result::Err(
137+
std::convert::Into::into(format!("invalid field count: {} vs {}", num_fields, fields.len())));
172138
}
173139

174140
#(
175-
let mut #temp_vars = ::std::option::Option::None;
141+
let mut #temp_vars = std::option::Option::None;
176142
)*
177143

178144
for field in fields {
179-
let oid = read_be_i32(&mut buf)? as u32;
145+
let oid = postgres_types::private::read_be_i32(&mut buf)? as u32;
180146
if oid != field.type_().oid() {
181-
return ::std::result::Result::Err(::std::convert::Into::into("unexpected OID"));
147+
return std::result::Result::Err(std::convert::Into::into("unexpected OID"));
182148
}
183149

184150
match field.name() {
185151
#(
186152
#field_names => {
187-
#temp_vars = ::std::option::Option::Some(
188-
read_value(field.type_(), &mut buf)?);
153+
#temp_vars = std::option::Option::Some(
154+
postgres_types::private::read_value(field.type_(), &mut buf)?);
189155
}
190156
)*
191157
_ => unreachable!(),
192158
}
193159
}
194160

195-
::std::result::Result::Ok(#ident {
161+
std::result::Result::Ok(#ident {
196162
#(
197163
#field_idents: #temp_vars.unwrap(),
198164
)*

postgres-derive/src/tosql.rs

Lines changed: 23 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -56,22 +56,22 @@ pub fn expand_derive_tosql(input: DeriveInput) -> Result<TokenStream, Error> {
5656

5757
let ident = &input.ident;
5858
let out = quote! {
59-
impl ::postgres_types::ToSql for #ident {
59+
impl postgres_types::ToSql for #ident {
6060
fn to_sql(&self,
61-
_type: &::postgres_types::Type,
62-
buf: &mut ::std::vec::Vec<u8>)
63-
-> ::std::result::Result<::postgres_types::IsNull,
64-
::std::boxed::Box<::std::error::Error +
65-
::std::marker::Sync +
66-
::std::marker::Send>> {
61+
_type: &postgres_types::Type,
62+
buf: &mut std::vec::Vec<u8>)
63+
-> std::result::Result<postgres_types::IsNull,
64+
std::boxed::Box<std::error::Error +
65+
std::marker::Sync +
66+
std::marker::Send>> {
6767
#to_sql_body
6868
}
6969

70-
fn accepts(type_: &::postgres_types::Type) -> bool {
70+
fn accepts(type_: &postgres_types::Type) -> bool {
7171
#accepts_body
7272
}
7373

74-
::postgres_types::to_sql_checked!();
74+
postgres_types::to_sql_checked!();
7575
}
7676
};
7777

@@ -91,18 +91,18 @@ fn enum_body(ident: &Ident, variants: &[Variant]) -> TokenStream {
9191
};
9292

9393
buf.extend_from_slice(s.as_bytes());
94-
::std::result::Result::Ok(::postgres_types::IsNull::No)
94+
std::result::Result::Ok(postgres_types::IsNull::No)
9595
}
9696
}
9797

9898
fn domain_body() -> TokenStream {
9999
quote! {
100100
let type_ = match *_type.kind() {
101-
::postgres_types::Kind::Domain(ref type_) => type_,
101+
postgres_types::Kind::Domain(ref type_) => type_,
102102
_ => unreachable!(),
103103
};
104104

105-
::postgres_types::ToSql::to_sql(&self.0, type_, buf)
105+
postgres_types::ToSql::to_sql(&self.0, type_, buf)
106106
}
107107
}
108108

@@ -111,51 +111,40 @@ fn composite_body(fields: &[Field]) -> TokenStream {
111111
let field_idents = fields.iter().map(|f| &f.ident);
112112

113113
quote! {
114-
fn write_be_i32<W>(buf: &mut W, n: i32) -> ::std::io::Result<()>
115-
where W: ::std::io::Write
116-
{
117-
let be = [(n >> 24) as u8, (n >> 16) as u8, (n >> 8) as u8, n as u8];
118-
buf.write_all(&be)
119-
}
120-
121114
let fields = match *_type.kind() {
122-
::postgres_types::Kind::Composite(ref fields) => fields,
115+
postgres_types::Kind::Composite(ref fields) => fields,
123116
_ => unreachable!(),
124117
};
125118

126-
write_be_i32(buf, fields.len() as i32)?;
119+
buf.extend_from_slice(&(fields.len() as i32).to_be_bytes());
127120

128121
for field in fields {
129-
write_be_i32(buf, field.type_().oid() as i32)?;
122+
buf.extend_from_slice(&field.type_().oid().to_be_bytes());
130123

131124
let base = buf.len();
132-
write_be_i32(buf, 0)?;
125+
buf.extend_from_slice(&[0; 4]);
133126
let r = match field.name() {
134127
#(
135-
#field_names => {
136-
::postgres_types::ToSql::to_sql(&self.#field_idents,
137-
field.type_(),
138-
buf)
139-
}
128+
#field_names => postgres_types::ToSql::to_sql(&self.#field_idents, field.type_(), buf),
140129
)*
141130
_ => unreachable!(),
142131
};
143132

144133
let count = match r? {
145-
::postgres_types::IsNull::Yes => -1,
146-
::postgres_types::IsNull::No => {
134+
postgres_types::IsNull::Yes => -1,
135+
postgres_types::IsNull::No => {
147136
let len = buf.len() - base - 4;
148137
if len > i32::max_value() as usize {
149-
return ::std::result::Result::Err(
150-
::std::convert::Into::into("value too large to transmit"));
138+
return std::result::Result::Err(
139+
std::convert::Into::into("value too large to transmit"));
151140
}
152141
len as i32
153142
}
154143
};
155144

156-
write_be_i32(&mut &mut buf[base..base + 4], count)?;
145+
buf[base..base + 4].copy_from_slice(&count.to_be_bytes());
157146
}
158147

159-
::std::result::Result::Ok(::postgres_types::IsNull::No)
148+
std::result::Result::Ok(postgres_types::IsNull::No)
160149
}
161150
}

postgres-types/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,9 @@ mod serde_json_1;
9696
#[cfg(feature = "with-uuid-0_7")]
9797
mod uuid_07;
9898

99+
#[cfg(feature = "derive")]
100+
#[doc(hidden)]
101+
pub mod private;
99102
mod special;
100103
mod type_gen;
101104

postgres-types/src/private.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
use crate::{FromSql, Type};
2+
use std::error::Error;
3+
4+
pub fn read_be_i32(buf: &mut &[u8]) -> Result<i32, Box<dyn Error + Sync + Send>> {
5+
if buf.len() < 4 {
6+
return Err("invalid buffer size".into());
7+
}
8+
let mut bytes = [0; 4];
9+
bytes.copy_from_slice(&buf[..4]);
10+
*buf = &buf[4..];
11+
Ok(i32::from_be_bytes(bytes))
12+
}
13+
14+
pub fn read_value<'a, T>(
15+
type_: &Type,
16+
buf: &mut &'a [u8],
17+
) -> Result<T, Box<dyn Error + Sync + Send>>
18+
where
19+
T: FromSql<'a>,
20+
{
21+
let len = read_be_i32(buf)?;
22+
let value = if len < 0 {
23+
None
24+
} else {
25+
if len as usize > buf.len() {
26+
return Err("invalid buffer size".into());
27+
}
28+
let (head, tail) = buf.split_at(len as usize);
29+
*buf = tail;
30+
Some(head)
31+
};
32+
T::from_sql_nullable(type_, value)
33+
}

tokio-postgres/src/client.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@ use crate::cancel_query;
33
use crate::codec::BackendMessages;
44
use crate::config::{Host, SslMode};
55
use crate::connection::{Request, RequestMessages};
6-
use crate::simple_query::SimpleQueryStream;
76
use crate::copy_out::CopyStream;
87
use crate::query::RowStream;
8+
use crate::simple_query::SimpleQueryStream;
99
use crate::slice_iter;
1010
#[cfg(feature = "runtime")]
1111
use crate::tls::MakeTlsConnect;
12-
use pin_utils::pin_mut;
1312
use crate::tls::TlsConnect;
1413
use crate::to_statement::ToStatement;
1514
use crate::types::{Oid, ToSql, Type};
@@ -25,6 +24,7 @@ use futures::channel::mpsc;
2524
use futures::{future, TryStream, TryStreamExt};
2625
use futures::{ready, StreamExt};
2726
use parking_lot::Mutex;
27+
use pin_utils::pin_mut;
2828
use postgres_protocol::message::backend::Message;
2929
use std::collections::HashMap;
3030
use std::error;
@@ -240,7 +240,7 @@ impl Client {
240240
params: &[&(dyn ToSql + Sync)],
241241
) -> Result<Row, Error>
242242
where
243-
T: ?Sized + ToStatement
243+
T: ?Sized + ToStatement,
244244
{
245245
let stream = self.query_raw(statement, slice_iter(params)).await?;
246246
pin_mut!(stream);
@@ -387,10 +387,7 @@ impl Client {
387387
/// Prepared statements should be use for any query which contains user-specified data, as they provided the
388388
/// functionality to safely embed that data in the request. Do not form statements via string concatenation and pass
389389
/// them to this method!
390-
pub async fn simple_query(
391-
&self,
392-
query: &str,
393-
) -> Result<Vec<SimpleQueryMessage>, Error> {
390+
pub async fn simple_query(&self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
394391
self.simple_query_raw(query).await?.try_collect().await
395392
}
396393

tokio-postgres/src/connect.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,8 @@ where
8282
}
8383

8484
rows.as_mut().poll(cx)
85-
}).await?;
85+
})
86+
.await?;
8687
pin_mut!(rows);
8788

8889
loop {

tokio-postgres/src/simple_query.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,7 @@ use std::pin::Pin;
1010
use std::sync::Arc;
1111
use std::task::{Context, Poll};
1212

13-
pub async fn simple_query(
14-
client: &InnerClient,
15-
query: &str,
16-
) -> Result<SimpleQueryStream, Error> {
13+
pub async fn simple_query(client: &InnerClient, query: &str) -> Result<SimpleQueryStream, Error> {
1714
let buf = encode(query)?;
1815
let responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
1916

tokio-postgres/src/transaction.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,8 @@ impl<'a> Transaction<'a> {
112112
statement: &T,
113113
params: &[&(dyn ToSql + Sync)],
114114
) -> Result<Row, Error>
115-
where
116-
T: ?Sized + ToStatement,
115+
where
116+
T: ?Sized + ToStatement,
117117
{
118118
self.client.query_one(statement, params).await
119119
}
@@ -236,10 +236,7 @@ impl<'a> Transaction<'a> {
236236
}
237237

238238
/// Like `Client::simple_query`.
239-
pub async fn simple_query(
240-
&self,
241-
query: &str,
242-
) -> Result<Vec<SimpleQueryMessage>, Error> {
239+
pub async fn simple_query(&self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
243240
self.client.simple_query(query).await
244241
}
245242

0 commit comments

Comments
 (0)