Skip to content

Commit

Permalink
switch EMPTY_DICT_BYTES to lazy_static, closes #2
Browse files Browse the repository at this point in the history
  • Loading branch information
Kafonek committed Nov 27, 2023
1 parent 94d2704 commit 74d37a7
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 8 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ async-trait = "0.1.74"
bytes = { version = "1.5.0", features = ["serde"] }
chrono = { version = "0.4.31", features = ["serde"] }
hex = "0.4.3"
lazy_static = "1.4.0"
ring = "0.17.5"
serde = { version = "1.0.190", features = ["derive"] }
serde_json = "1.0.108"
Expand Down
11 changes: 11 additions & 0 deletions src/jupyter/constants.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use bytes::Bytes;
use lazy_static::lazy_static;
use serde_json::{self, Value};

lazy_static! {
pub static ref EMPTY_DICT_BYTES: Bytes = {
let empty_dict: Value = serde_json::json!({});
let empty_dict_bytes = serde_json::to_vec(&empty_dict).unwrap();
Bytes::from(empty_dict_bytes)
};
}
1 change: 1 addition & 0 deletions src/jupyter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod message_content;
pub mod metadata;
pub mod wire_protocol;

pub mod constants;
pub mod message;
pub mod request;
pub mod response;
11 changes: 3 additions & 8 deletions src/jupyter/wire_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ that I wanted to use here, so WireProtocol serialization and deserialization is
Ref: https://jupyter-client.readthedocs.io/en/latest/messaging.html#the-wire-protocol
*/
use crate::jupyter::constants::EMPTY_DICT_BYTES;
use crate::jupyter::header::Header;
use bytes::Bytes;
use ring::hmac;
Expand All @@ -22,19 +23,13 @@ pub struct WireProtocol {
pub content: Bytes,
}

fn empty_dict_as_bytes() -> Bytes {
let empty_dict = serde_json::json!({});
let empty_dict = serde_json::to_vec(&empty_dict).unwrap();
Bytes::from(empty_dict)
}

impl WireProtocol {
pub fn new<T: Serialize>(header: Header, content: T, hmac_signing_key: &str) -> Self {
// Serialize header to JSON then bytes
let header = Bytes::from(serde_json::to_vec(&header).expect("Failed to serialize header"));
// Make parent_header and metadata both empty dicts serialized to json and then bytes
let parent_header = empty_dict_as_bytes();
let metadata = empty_dict_as_bytes();
let parent_header = EMPTY_DICT_BYTES.clone();
let metadata = EMPTY_DICT_BYTES.clone();

// If content is passed in, serialize and turn into bytes. Otherwise same as parent_header
let content =
Expand Down

0 comments on commit 74d37a7

Please sign in to comment.