Skip to content

Commit

Permalink
feat: add SecWebsocketKey random constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
tottoto committed Apr 2, 2024
1 parent 2ffcd7a commit 4222e1e
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
5 changes: 3 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ jobs:
toolchain: ${{ matrix.rust }}
components: rustfmt
- run: cargo test --workspace
- run: cargo test --workspace --features full
- if: matrix.rust == 'nightly'
run: cargo test --benches

Expand All @@ -38,12 +39,12 @@ jobs:
- uses: dtolnay/rust-toolchain@stable
- uses: taiki-e/install-action@cargo-hack
- uses: taiki-e/install-action@cargo-minimal-versions
- run: cargo minimal-versions check --workspace
- run: cargo minimal-versions check --workspace --all-features

MSRV:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- uses: taiki-e/install-action@cargo-hack
- run: cargo hack --rust-version --no-dev-deps check --workspace
- run: cargo hack --rust-version --no-dev-deps check --workspace --all-features
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ bytes = "1"
mime = "0.3.14"
sha1 = "0.10"
httpdate = "1"
rand = { version = "0.8", optional = true }

[features]
full = ["rand"]
nightly = []
32 changes: 31 additions & 1 deletion src/common/sec_websocket_key.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,38 @@
use http::HeaderValue;

/// The `Sec-Websocket-Key` header.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SecWebsocketKey(pub(super) http::HeaderValue);
pub struct SecWebsocketKey(pub(super) HeaderValue);

derive_header! {
SecWebsocketKey(_),
name: SEC_WEBSOCKET_KEY
}

impl SecWebsocketKey {
/// Create a random `SecWebsocketKey`.
#[cfg(feature = "rand")]
#[cfg_attr(docsrs, cfg(feature = "rand"))]
pub fn random() -> Self {
use base64::{engine::general_purpose::STANDARD, Engine};

let bytes: [u8; 16] = rand::random();
let mut value = HeaderValue::from_str(&STANDARD.encode(bytes)).unwrap();

value.set_sensitive(true);

Self(value)
}
}

#[cfg(test)]
mod tests {
#[cfg(feature = "rand")]
use super::SecWebsocketKey;

#[cfg(feature = "rand")]
#[test]
fn random() {
let _ = SecWebsocketKey::random();
}
}

0 comments on commit 4222e1e

Please sign in to comment.