Skip to content

Commit

Permalink
Prefer &str over String where possible.
Browse files Browse the repository at this point in the history
  • Loading branch information
bitfl0wer committed Aug 26, 2024
1 parent f0dbd34 commit 2cc0a75
Show file tree
Hide file tree
Showing 16 changed files with 64 additions and 66 deletions.
2 changes: 1 addition & 1 deletion examples/gateway_observers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl Subscriber<GatewayReady> for ExampleObserver {

#[tokio::main(flavor = "current_thread")]
async fn main() {
let gateway_websocket_url = GATEWAY_URL.to_string();
let gateway_websocket_url = GATEWAY_URL;

// These options specify the encoding format, compression, etc
//
Expand Down
8 changes: 5 additions & 3 deletions examples/gateway_simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,18 @@ use wasmtimer::tokio::sleep;
/// This example creates a simple gateway connection and a session with an Identify event
#[tokio::main(flavor = "current_thread")]
async fn main() {
let gateway_websocket_url = GATEWAY_URL.to_string();
let gateway_websocket_url = GATEWAY_URL;

// These options specify the encoding format, compression, etc
//
// For most cases the defaults should work, though some implementations
// might only support some formats or not support compression
let options = GatewayOptions::default();

// Initiate the gateway connection, starting a listener in one thread and a heartbeat handler in another
let gateway = Gateway::spawn(gateway_websocket_url, options).await.unwrap();
let gateway = Gateway::spawn(gateway_websocket_url, options)
.await
.unwrap();

// At this point, we are connected to the server and are sending heartbeats, however we still haven't authenticated

Expand Down
7 changes: 3 additions & 4 deletions src/api/auth/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,12 @@ impl Instance {
// We do not have a user yet, and the UserRateLimits will not be affected by a login
// request (since login is an instance wide limit), which is why we are just cloning the
// instances' limits to pass them on as user_rate_limits later.
let mut user =
ChorusUser::shell(Arc::new(RwLock::new(self.clone())), "None".to_string()).await;

let mut user = ChorusUser::shell(Arc::new(RwLock::new(self.clone())), "None").await;

let login_result = chorus_request
.deserialize_response::<LoginResult>(&mut user)
.await?;
user.set_token(login_result.token);
user.set_token(&login_result.token);
user.settings = login_result.settings;

let object = User::get(&mut user, None).await?;
Expand Down
5 changes: 2 additions & 3 deletions src/api/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ pub mod register;

impl Instance {
/// Logs into an existing account on the spacebar server, using only a token.
pub async fn login_with_token(&mut self, token: String) -> ChorusResult<ChorusUser> {
let mut user =
ChorusUser::shell(Arc::new(RwLock::new(self.clone())), token).await;
pub async fn login_with_token(&mut self, token: &str) -> ChorusResult<ChorusUser> {
let mut user = ChorusUser::shell(Arc::new(RwLock::new(self.clone())), token).await;

let object = User::get(&mut user, None).await?;
let settings = User::get_settings(&mut user).await?;
Expand Down
7 changes: 3 additions & 4 deletions src/api/auth/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,13 @@ impl Instance {
// We do not have a user yet, and the UserRateLimits will not be affected by a login
// request (since register is an instance wide limit), which is why we are just cloning
// the instances' limits to pass them on as user_rate_limits later.
let mut user =
ChorusUser::shell(Arc::new(RwLock::new(self.clone())), "None".to_string()).await;

let mut user = ChorusUser::shell(Arc::new(RwLock::new(self.clone())), "None").await;

let token = chorus_request
.deserialize_response::<Token>(&mut user)
.await?
.token;
user.set_token(token);
user.set_token(&token);

let object = User::get(&mut user, None).await?;
let settings = User::get_settings(&mut user).await?;
Expand Down
6 changes: 3 additions & 3 deletions src/api/channels/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ impl Message {
let result = request.send_request(user).await?;
let result_json = result.json::<Value>().await.unwrap();
if !result_json.is_object() {
return Err(search_error(result_json.to_string()));
return Err(search_error(result_json.to_string().as_str()));
}
let value_map = result_json.as_object().unwrap();
if let Some(messages) = value_map.get("messages") {
Expand All @@ -123,7 +123,7 @@ impl Message {
}
// The code below might be incorrect. We'll cross that bridge when we come to it
if !value_map.contains_key("code") || !value_map.contains_key("retry_after") {
return Err(search_error(result_json.to_string()));
return Err(search_error(result_json.to_string().as_str()));
}
let code = value_map.get("code").unwrap().as_u64().unwrap();
let retry_after = value_map.get("retry_after").unwrap().as_u64().unwrap();
Expand Down Expand Up @@ -482,7 +482,7 @@ impl Message {
}
}

fn search_error(result_text: String) -> ChorusError {
fn search_error(result_text: &str) -> ChorusError {
ChorusError::InvalidResponse {
error: format!(
"Got unexpected Response, or Response which is not valid JSON. Response: \n{}",
Expand Down
2 changes: 1 addition & 1 deletion src/gateway/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ impl Gateway {
/// # Note
/// The websocket url should begin with the prefix wss:// or ws:// (for unsecure connections)
pub async fn spawn(
websocket_url: String,
websocket_url: &str,
options: GatewayOptions,
) -> Result<GatewayHandle, GatewayError> {
let url = options.add_to_url(websocket_url);
Expand Down
4 changes: 2 additions & 2 deletions src/gateway/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ impl GatewayOptions {
/// Adds the options to an existing gateway url
///
/// Returns the new url
pub(crate) fn add_to_url(&self, url: String) -> String {
let mut url = url;
pub(crate) fn add_to_url(&self, url: &str) -> String {
let mut url = url.to_string();

let mut parameters = Vec::with_capacity(2);

Expand Down
12 changes: 6 additions & 6 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl Instance {
}

pub async fn is_limited(api_url: &str) -> ChorusResult<Option<LimitsConfiguration>> {
let api_url = UrlBundle::parse_url(api_url.to_string());
let api_url = UrlBundle::parse_url(api_url);
let client = Client::new();
let request = client
.get(format!("{}/policies/instance/limits", &api_url))
Expand Down Expand Up @@ -163,8 +163,8 @@ impl ChorusUser {
self.token.clone()
}

pub fn set_token(&mut self, token: String) {
self.token = token;
pub fn set_token(&mut self, token: &str) {
self.token = token.to_string();
}

/// Creates a new [ChorusUser] from existing data.
Expand Down Expand Up @@ -195,16 +195,16 @@ impl ChorusUser {
/// registering or logging in to the Instance, where you do not yet have a User object, but still
/// need to make a RateLimited request. To use the [`GatewayHandle`], you will have to identify
/// first.
pub(crate) async fn shell(instance: Shared<Instance>, token: String) -> ChorusUser {
pub(crate) async fn shell(instance: Shared<Instance>, token: &str) -> ChorusUser {
let settings = Arc::new(RwLock::new(UserSettings::default()));
let object = Arc::new(RwLock::new(User::default()));
let wss_url = instance.read().unwrap().urls.wss.clone();
let wss_url = &instance.read().unwrap().urls.wss.clone();
// Dummy gateway object
let gateway = Gateway::spawn(wss_url, GatewayOptions::default())
.await
.unwrap();
ChorusUser {
token,
token: token.to_string(),
belongs_to: instance.clone(),
limits: instance
.read()
Expand Down
34 changes: 17 additions & 17 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ pub struct UrlBundle {

impl UrlBundle {
/// Creates a new UrlBundle from the relevant urls.
pub fn new(root: String, api: String, wss: String, cdn: String) -> Self {
pub fn new(root: &str, api: &str, wss: &str, cdn: &str) -> Self {
Self {
root: UrlBundle::parse_url(root),
api: UrlBundle::parse_url(api),
Expand All @@ -203,17 +203,17 @@ impl UrlBundle {
/// let url = parse_url("localhost:3000");
/// ```
/// `-> Outputs "http://localhost:3000".`
pub fn parse_url(url: String) -> String {
let url = match Url::parse(&url) {
pub fn parse_url(url: &str) -> String {
let url = match Url::parse(url) {
Ok(url) => {
if url.scheme() == "localhost" {
return UrlBundle::parse_url(format!("http://{}", url));
return UrlBundle::parse_url(&format!("http://{}", url));
}
url
}
Err(ParseError::RelativeUrlWithoutBase) => {
let url_fmt = format!("http://{}", url);
return UrlBundle::parse_url(url_fmt);
return UrlBundle::parse_url(&url_fmt);
}
Err(_) => panic!("Invalid URL"), // TODO: should not panic here
};
Expand All @@ -236,7 +236,7 @@ impl UrlBundle {
/// of the above approaches fail, it is very likely that the instance is misconfigured, unreachable, or that
/// a wrong URL was provided.
pub async fn from_root_url(url: &str) -> ChorusResult<UrlBundle> {
let parsed = UrlBundle::parse_url(url.to_string());
let parsed = UrlBundle::parse_url(url);
let client = reqwest::Client::new();
let request_wellknown = client
.get(format!("{}/.well-known/spacebar", &parsed))
Expand Down Expand Up @@ -274,10 +274,10 @@ impl UrlBundle {
.await
{
Ok(UrlBundle::new(
url.to_string(),
body.api_endpoint,
body.gateway,
body.cdn,
url,
&body.api_endpoint,
&body.gateway,
&body.cdn,
))
} else {
Err(ChorusError::RequestFailed {
Expand All @@ -294,13 +294,13 @@ mod lib {

#[test]
fn test_parse_url() {
let mut result = UrlBundle::parse_url(String::from("localhost:3000/"));
assert_eq!(result, String::from("http://localhost:3000"));
result = UrlBundle::parse_url(String::from("https://some.url.com/"));
assert_eq!(result, String::from("https://some.url.com"));
result = UrlBundle::parse_url(String::from("https://some.url.com/"));
assert_eq!(result, String::from("https://some.url.com"));
result = UrlBundle::parse_url(String::from("https://some.url.com"));
let mut result = UrlBundle::parse_url("localhost:3000/");
assert_eq!(result, "http://localhost:3000");
result = UrlBundle::parse_url("https://some.url.com/");
assert_eq!(result, String::from("https://some.url.com"));
result = UrlBundle::parse_url("https://some.url.com/");
assert_eq!(result, "https://some.url.com");
result = UrlBundle::parse_url("https://some.url.com");
assert_eq!(result, "https://some.url.com");
}
}
4 changes: 2 additions & 2 deletions src/types/utils/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use jsonwebtoken::{
};
use serde::{Deserialize, Serialize};

pub fn generate_token(id: &Snowflake, email: String, jwt_key: &str) -> String {
let claims = Claims::new(&email, id);
pub fn generate_token(id: &Snowflake, email: &str, jwt_key: &str) -> String {
let claims = Claims::new(email, id);

build_token(&claims, jwt_key).unwrap()
}
Expand Down
4 changes: 2 additions & 2 deletions src/voice/gateway/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub struct VoiceGateway {

impl VoiceGateway {
#[allow(clippy::new_ret_no_self)]
pub async fn spawn(websocket_url: String) -> Result<VoiceGatewayHandle, VoiceGatewayError> {
pub async fn spawn(websocket_url: &str) -> Result<VoiceGatewayHandle, VoiceGatewayError> {
// Append the needed things to the websocket url
let processed_url = format!("wss://{}/?v=7", websocket_url);
trace!("VGW: Connecting to {}", processed_url.clone());
Expand Down Expand Up @@ -110,7 +110,7 @@ impl VoiceGateway {
});

Ok(VoiceGatewayHandle {
url: websocket_url.clone(),
url: websocket_url.to_string(),
events: shared_events,
websocket_send: shared_websocket_send.clone(),
kill_send: kill_send.clone(),
Expand Down
2 changes: 1 addition & 1 deletion src/voice/gateway/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl VoiceGatewayHandle {

/// Sends a speaking event to the gateway
pub async fn send_speaking(&self, to_send: Speaking) {
let to_send_value = serde_json::to_value(&to_send).unwrap();
let to_send_value = serde_json::to_value(to_send).unwrap();

trace!("VGW: Sending Speaking");

Expand Down
10 changes: 3 additions & 7 deletions tests/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,7 @@ async fn test_login_with_token() {
let mut bundle = common::setup().await;

let token = &bundle.user.token;
let other_user = bundle
.instance
.login_with_token(token.clone())
.await
.unwrap();
let other_user = bundle.instance.login_with_token(token).await.unwrap();
assert_eq!(
bundle.user.object.read().unwrap().id,
other_user.object.read().unwrap().id
Expand All @@ -98,8 +94,8 @@ async fn test_login_with_token() {
async fn test_login_with_invalid_token() {
let mut bundle = common::setup().await;

let token = "invalid token lalalalala".to_string();
let other_user = bundle.instance.login_with_token(token.clone()).await;
let token = "invalid token lalalalala";
let other_user = bundle.instance.login_with_token(token).await;

assert!(other_user.is_err());

Expand Down
19 changes: 11 additions & 8 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use chorus::{
instance::{ChorusUser, Instance},
types::{
Channel, ChannelCreateSchema, Guild, GuildCreateSchema, RegisterSchema,
RoleCreateModifySchema, RoleObject, Shared
RoleCreateModifySchema, RoleObject, Shared,
},
UrlBundle,
};
Expand Down Expand Up @@ -50,7 +50,7 @@ impl TestBundle {
limits: self.user.limits.clone(),
settings: self.user.settings.clone(),
object: self.user.object.clone(),
gateway: Gateway::spawn(self.instance.urls.wss.clone(), GatewayOptions::default())
gateway: Gateway::spawn(&self.instance.urls.wss, GatewayOptions::default())
.await
.unwrap(),
}
Expand All @@ -59,9 +59,12 @@ impl TestBundle {

// Set up a test by creating an Instance and a User. Reduces Test boilerplate.
pub(crate) async fn setup() -> TestBundle {

// So we can get logs when tests fail
let _ = simple_logger::SimpleLogger::with_level(simple_logger::SimpleLogger::new(), log::LevelFilter::Debug).init();
let _ = simple_logger::SimpleLogger::with_level(
simple_logger::SimpleLogger::new(),
log::LevelFilter::Debug,
)
.init();

let instance = Instance::new("http://localhost:3001/api").await.unwrap();
// Requires the existence of the below user.
Expand Down Expand Up @@ -121,10 +124,10 @@ pub(crate) async fn setup() -> TestBundle {
.unwrap();

let urls = UrlBundle::new(
"http://localhost:3001/api".to_string(),
"http://localhost:3001/api".to_string(),
"ws://localhost:3001/".to_string(),
"http://localhost:3001".to_string(),
"http://localhost:3001/api",
"http://localhost:3001/api",
"ws://localhost:3001/",
"http://localhost:3001",
);
TestBundle {
urls,
Expand Down
4 changes: 2 additions & 2 deletions tests/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use wasmtimer::tokio::sleep;
async fn test_gateway_establish() {
let bundle = common::setup().await;

let _: GatewayHandle = Gateway::spawn(bundle.urls.wss.clone(), GatewayOptions::default())
let _: GatewayHandle = Gateway::spawn(&bundle.urls.wss, GatewayOptions::default())
.await
.unwrap();
common::teardown(bundle).await
Expand All @@ -55,7 +55,7 @@ impl Subscriber<GatewayReady> for GatewayReadyObserver {
async fn test_gateway_authenticate() {
let bundle = common::setup().await;

let gateway: GatewayHandle = Gateway::spawn(bundle.urls.wss.clone(), GatewayOptions::default())
let gateway: GatewayHandle = Gateway::spawn(&bundle.urls.wss, GatewayOptions::default())
.await
.unwrap();

Expand Down

0 comments on commit 2cc0a75

Please sign in to comment.