Skip to content

Add a slim builder that doesn't call to_string right away #12

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

Merged
merged 3 commits into from
Jun 7, 2024
Merged
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions .codespellrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[codespell]
ignore-words-list = crate
skip = .git,*.lock
19 changes: 19 additions & 0 deletions .github/workflows/codespell.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
name: Codespell

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
codespell:
name: Check for spelling errors
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v4
- name: Codespell
uses: codespell-project/actions-codespell@v2
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
This project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

### Added

- The `QueryString::simple` function was added to construct the new `QueryStringSimple` type.
This type reduces string allocations, defers rendering and can keep references
but at the cost of a complex type signature slightly more rigid handling.

### Changed

- The `QueryString::new` function was renamed to `QueryString::dynamic`.

## [0.5.1] - 2024-05-24

[0.5.1]: https://github.com/sunsided/query-string-builder/releases/tag/v0.5.1
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,7 @@ criterion = "0.5.1"
[[bench]]
name = "bench"
harness = false

[[bench]]
name = "bench_slim"
harness = false
8 changes: 4 additions & 4 deletions benches/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
// `with_value` method benchmark
c.bench_function("with_value", |b| {
b.iter(|| {
let qs = QueryString::new()
let qs = QueryString::dynamic()
.with_value("q", "apple???")
.with_value("category", "fruits and vegetables");
format!("{qs}")
Expand All @@ -16,7 +16,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
// `with_opt_value` method benchmark
c.bench_function("with_opt_value", |b| {
b.iter(|| {
let qs = QueryString::new()
let qs = QueryString::dynamic()
.with_value("q", "celery")
.with_opt_value("taste", None::<String>)
.with_opt_value("category", Some("fruits and vegetables"))
Expand All @@ -29,12 +29,12 @@ pub fn criterion_benchmark(c: &mut Criterion) {
// Full test including creating, pushing and appending
c.bench_function("push_opt_and_append", |b| {
b.iter(|| {
let mut qs = QueryString::new();
let mut qs = QueryString::dynamic();
qs.push("a", "apple");
qs.push_opt("b", None::<String>);
qs.push_opt("c", Some("🍎 apple"));

let more = QueryString::new().with_value("q", "pear");
let more = QueryString::dynamic().with_value("q", "pear");
let qs = qs.append_into(more);

format!("{qs}")
Expand Down
31 changes: 31 additions & 0 deletions benches/bench_slim.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use criterion::{criterion_group, criterion_main, Criterion};

use query_string_builder::QueryString;

pub fn criterion_benchmark(c: &mut Criterion) {
// `with_value` method benchmark
c.bench_function("with_value (slim)", |b| {
b.iter(|| {
let qs = QueryString::simple()
.with_value("q", "apple???")
.with_value("category", "fruits and vegetables");
format!("{qs}")
})
});

// `with_opt_value` method benchmark
c.bench_function("with_opt_value (slim)", |b| {
b.iter(|| {
let qs = QueryString::simple()
.with_value("q", "celery")
.with_opt_value("taste", None::<String>)
.with_opt_value("category", Some("fruits and vegetables"))
.with_opt_value("tasty", Some(true))
.with_opt_value("weight", Some(99.9));
format!("{qs}")
})
});
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
75 changes: 51 additions & 24 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
//! ```
//! use query_string_builder::QueryString;
//!
//! let qs = QueryString::new()
//! let qs = QueryString::dynamic()
//! .with_value("q", "🍎 apple")
//! .with_value("tasty", true)
//! .with_opt_value("color", None::<String>)
Expand All @@ -22,12 +22,15 @@

#![deny(unsafe_code)]

use std::fmt::{Debug, Display, Formatter, Write};
mod slim;

use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
use std::fmt::{Debug, Display, Formatter, Write};

pub use slim::{QueryStringSimple, WrappedQueryString};

/// https://url.spec.whatwg.org/#query-percent-encode-set
const QUERY: &AsciiSet = &CONTROLS
pub(crate) const QUERY: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
Expand All @@ -50,7 +53,7 @@ const QUERY: &AsciiSet = &CONTROLS
/// ```
/// use query_string_builder::QueryString;
///
/// let qs = QueryString::new()
/// let qs = QueryString::dynamic()
/// .with_value("q", "apple")
/// .with_value("category", "fruits and vegetables");
///
Expand All @@ -59,14 +62,38 @@ const QUERY: &AsciiSet = &CONTROLS
/// "https://example.com/?q=apple&category=fruits%20and%20vegetables"
/// );
/// ```
#[derive(Debug, Default, Clone)]
#[derive(Debug, Clone)]
pub struct QueryString {
pairs: Vec<Kvp>,
}

impl QueryString {
/// Creates a new, empty query string builder.
pub fn new() -> Self {
///
/// ## Example
///
/// ```
/// use query_string_builder::QueryString;
///
/// let weight: &f32 = &99.9;
///
/// let qs = QueryString::simple()
/// .with_value("q", "apple")
/// .with_value("category", "fruits and vegetables")
/// .with_opt_value("weight", Some(weight));
///
/// assert_eq!(
/// format!("https://example.com/{qs}"),
/// "https://example.com/?q=apple&category=fruits%20and%20vegetables&weight=99.9"
/// );
/// ```
#[allow(clippy::new_ret_no_self)]
pub fn simple() -> QueryStringSimple {
QueryStringSimple::default()
}

/// Creates a new, empty query string builder.
pub fn dynamic() -> Self {
Self {
pairs: Vec::default(),
}
Expand All @@ -79,7 +106,7 @@ impl QueryString {
/// ```
/// use query_string_builder::QueryString;
///
/// let qs = QueryString::new()
/// let qs = QueryString::dynamic()
/// .with_value("q", "🍎 apple")
/// .with_value("category", "fruits and vegetables")
/// .with_value("answer", 42);
Expand All @@ -104,7 +131,7 @@ impl QueryString {
/// ```
/// use query_string_builder::QueryString;
///
/// let qs = QueryString::new()
/// let qs = QueryString::dynamic()
/// .with_opt_value("q", Some("🍎 apple"))
/// .with_opt_value("f", None::<String>)
/// .with_opt_value("category", Some("fruits and vegetables"))
Expand All @@ -130,7 +157,7 @@ impl QueryString {
/// ```
/// use query_string_builder::QueryString;
///
/// let mut qs = QueryString::new();
/// let mut qs = QueryString::dynamic();
/// qs.push("q", "apple");
/// qs.push("category", "fruits and vegetables");
///
Expand All @@ -154,7 +181,7 @@ impl QueryString {
/// ```
/// use query_string_builder::QueryString;
///
/// let mut qs = QueryString::new();
/// let mut qs = QueryString::dynamic();
/// qs.push_opt("q", None::<String>);
/// qs.push_opt("q", Some("🍎 apple"));
///
Expand Down Expand Up @@ -188,8 +215,8 @@ impl QueryString {
/// ```
/// use query_string_builder::QueryString;
///
/// let mut qs = QueryString::new().with_value("q", "apple");
/// let more = QueryString::new().with_value("q", "pear");
/// let mut qs = QueryString::dynamic().with_value("q", "apple");
/// let more = QueryString::dynamic().with_value("q", "pear");
///
/// qs.append(more);
///
Expand All @@ -209,8 +236,8 @@ impl QueryString {
/// ```
/// use query_string_builder::QueryString;
///
/// let qs = QueryString::new().with_value("q", "apple");
/// let more = QueryString::new().with_value("q", "pear");
/// let qs = QueryString::dynamic().with_value("q", "apple");
/// let more = QueryString::dynamic().with_value("q", "pear");
///
/// let qs = qs.append_into(more);
///
Expand Down Expand Up @@ -257,15 +284,15 @@ mod tests {

#[test]
fn test_empty() {
let qs = QueryString::new();
let qs = QueryStringSimple::default();
assert_eq!(qs.to_string(), "");
assert_eq!(qs.len(), 0);
assert!(qs.is_empty());
}

#[test]
fn test_simple() {
let qs = QueryString::new()
let qs = QueryString::dynamic()
.with_value("q", "apple???")
.with_value("category", "fruits and vegetables")
.with_value("tasty", true)
Expand All @@ -280,15 +307,15 @@ mod tests {

#[test]
fn test_encoding() {
let qs = QueryString::new()
let qs = QueryString::dynamic()
.with_value("q", "Grünkohl")
.with_value("category", "Gemüse");
assert_eq!(qs.to_string(), "?q=Gr%C3%BCnkohl&category=Gem%C3%BCse");
}

#[test]
fn test_emoji() {
let qs = QueryString::new()
let qs = QueryString::dynamic()
.with_value("q", "🥦")
.with_value("🍽️", "🍔🍕");
assert_eq!(
Expand All @@ -299,7 +326,7 @@ mod tests {

#[test]
fn test_optional() {
let qs = QueryString::new()
let qs = QueryString::dynamic()
.with_value("q", "celery")
.with_opt_value("taste", None::<String>)
.with_opt_value("category", Some("fruits and vegetables"))
Expand All @@ -314,7 +341,7 @@ mod tests {

#[test]
fn test_push_optional() {
let mut qs = QueryString::new();
let mut qs = QueryString::dynamic();
qs.push("a", "apple");
qs.push_opt("b", None::<String>);
qs.push_opt("c", Some("🍎 apple"));
Expand All @@ -327,11 +354,11 @@ mod tests {

#[test]
fn test_append() {
let qs = QueryString::new().with_value("q", "apple");
let more = QueryString::new().with_value("q", "pear");
let qs = QueryString::dynamic().with_value("q", "apple");
let more = QueryString::dynamic().with_value("q", "pear");

let mut qs = qs.append_into(more);
qs.append(QueryString::new().with_value("answer", "42"));
qs.append(QueryString::dynamic().with_value("answer", "42"));

assert_eq!(
format!("https://example.com/{qs}"),
Expand Down Expand Up @@ -371,7 +398,7 @@ mod tests {
("right_curly", "}", "}"),
];

let mut qs = QueryString::new();
let mut qs = QueryString::dynamic();
for (key, value, _) in &tests {
qs.push(key.to_string(), value.to_string());
}
Expand Down
Loading