Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shrink query_opt/query_one codegen size very slightly #1101

Merged
merged 1 commit into from
Mar 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 16 additions & 20 deletions tokio-postgres/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,19 +274,9 @@ impl Client {
where
T: ?Sized + ToStatement,
{
let stream = self.query_raw(statement, slice_iter(params)).await?;
pin_mut!(stream);

let row = match stream.try_next().await? {
Some(row) => row,
None => return Err(Error::row_count()),
};

if stream.try_next().await?.is_some() {
return Err(Error::row_count());
}

Ok(row)
self.query_opt(statement, params)
.await
.and_then(|res| res.ok_or_else(Error::row_count))
}

/// Executes a statements which returns zero or one rows, returning it.
Expand All @@ -310,16 +300,22 @@ impl Client {
let stream = self.query_raw(statement, slice_iter(params)).await?;
pin_mut!(stream);

let row = match stream.try_next().await? {
Some(row) => row,
None => return Ok(None),
};
let mut first = None;

// Originally this was two calls to `try_next().await?`,
// once for the first element, and second to error if more than one.
//
// However, this new form with only one .await in a loop generates
// slightly smaller codegen/stack usage for the resulting future.
while let Some(row) = stream.try_next().await? {
novacrazy marked this conversation as resolved.
Show resolved Hide resolved
if first.is_some() {
return Err(Error::row_count());
}

if stream.try_next().await?.is_some() {
return Err(Error::row_count());
first = Some(row);
}

Ok(Some(row))
Ok(first)
}

/// The maximally flexible version of [`query`].
Expand Down
Loading