Prefer &str over String where possible.

This commit is contained in:
bitfl0wer 2024-08-26 12:36:01 +02:00
parent f0dbd3410f
commit 2cc0a75540
No known key found for this signature in database
GPG Key ID: 8D90CA11485CD14D
16 changed files with 64 additions and 66 deletions

View File

@ -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
//

View File

@ -25,8 +25,8 @@ 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
@ -34,7 +34,9 @@ async fn main() {
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

View File

@ -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?;

View File

@ -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?;

View File

@ -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?;

View File

@ -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") {
@ -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();
@ -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{}",

View File

@ -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);

View File

@ -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);

View File

@ -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))
@ -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.
@ -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()

View File

@ -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),
@ -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
};
@ -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))
@ -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 {
@ -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");
}
}

View File

@ -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()
}

View File

@ -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());
@ -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(),

View File

@ -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");

View File

@ -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
@ -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());

View File

@ -10,7 +10,7 @@ use chorus::{
instance::{ChorusUser, Instance},
types::{
Channel, ChannelCreateSchema, Guild, GuildCreateSchema, RegisterSchema,
RoleCreateModifySchema, RoleObject, Shared
RoleCreateModifySchema, RoleObject, Shared,
},
UrlBundle,
};
@ -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(),
}
@ -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.
@ -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,

View File

@ -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
@ -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();