Skip to content

Commit

Permalink
misc: use impl instead of type generic (#300)
Browse files Browse the repository at this point in the history
  • Loading branch information
vnghia authored Jun 15, 2024
1 parent 538b025 commit 718daf7
Show file tree
Hide file tree
Showing 40 changed files with 144 additions and 154 deletions.
2 changes: 1 addition & 1 deletion frontend/src/components/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ static ERROR_SIGNAL: GlobalSignal<Option<Cow<'static, str>>> = Signal::global(De
pub struct ErrorToast;

impl ErrorToast {
pub fn write<E: Into<Cow<'static, str>>>(e: E) {
pub fn write(e: impl Into<Cow<'static, str>>) {
*ERROR_SIGNAL.write() = Some(e.into());
}

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/folder/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub fn AddFolder() -> Element {
{
spawn(async move {
if common_state
.send_with_common::<_, AddMusicFolderBody>(
.send_with_common::<AddMusicFolderBody>(
"/rest/addMusicFolder",
AddMusicFolderParams {
name: name().expect("name should not be none"),
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/folder/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub fn Folder(id: Uuid) -> Element {
{
spawn(async move {
if common_state
.send_with_common::<_, UpdateMusicFolderBody>(
.send_with_common::<UpdateMusicFolderBody>(
"/rest/updateMusicFolder",
UpdateMusicFolderParams { id, name: name(), path: path(), fs_type: fs_type() },
)
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/components/folder/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ struct Folder {

async fn get_scan_status(common_state: &CommonState, id: Uuid) -> Result<Option<ScanStatus>> {
common_state
.send_with_common::<_, GetScanStatusBody>("/rest/getScanStatus", GetScanStatusParams { id })
.send_with_common::<GetScanStatusBody>("/rest/getScanStatus", GetScanStatusParams { id })
.await
.map(|r| r.scan)
}
Expand All @@ -45,7 +45,7 @@ pub fn Folders() -> Element {
use_future(move || async move {
if let Some(common_state) = common_state() {
let ids = common_state
.send_with_common::<_, GetMusicFolderIdsBody>(
.send_with_common::<GetMusicFolderIdsBody>(
"/rest/getMusicFolderIds",
GetMusicFolderIdsParams {},
)
Expand All @@ -57,7 +57,7 @@ pub fn Folders() -> Element {
let result: Result<()> = try {
folders.push(Folder {
stat: common_state
.send_with_common::<_, GetMusicFolderStatBody>(
.send_with_common::<GetMusicFolderStatBody>(
"/rest/getMusicFolderStat",
GetMusicFolderStatParams { id },
)
Expand Down Expand Up @@ -86,7 +86,7 @@ pub fn Folders() -> Element {
let result: Result<()> = try {
let id = folders.get(idx).expect("folder should not be none").stat.music_folder.id;
folders.get_mut(idx).expect("folder stat should not be none").scan = common_state
.send_with_common::<_, StartScanBody>(
.send_with_common::<StartScanBody>(
"/rest/startScan",
StartScanParams { id, mode },
)
Expand All @@ -106,7 +106,7 @@ pub fn Folders() -> Element {
remove_idx.set(None);
let folder = folders.remove(idx);
common_state
.send_with_common::<_, RemoveMusicFolderBody>(
.send_with_common::<RemoveMusicFolderBody>(
"/rest/removeMusicFolder",
RemoveMusicFolderParams { id: folder.stat.music_folder.id },
)
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/components/folder/permission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub fn FolderPermission(id: Uuid) -> Element {
if let Some(common_state) = common_state() {
let result: Result<_, anyhow::Error> = try {
let allowed_ids = common_state
.send_with_common::<_, GetAllowedUsersBody>(
.send_with_common::<GetAllowedUsersBody>(
"/rest/getAllowedUsers",
GetAllowedUsersParams { id },
)
Expand All @@ -35,7 +35,7 @@ pub fn FolderPermission(id: Uuid) -> Element {
.collect::<HashSet<_>>();
users.set(
common_state
.send_with_common::<_, GetBasicUserIdsBody>(
.send_with_common::<GetBasicUserIdsBody>(
"/rest/getBasicUserIds",
GetBasicUserIdsParams {},
)
Expand All @@ -62,15 +62,15 @@ pub fn FolderPermission(id: Uuid) -> Element {

if allow {
common_state
.send_with_common::<_, AddPermissionBody>(
.send_with_common::<AddPermissionBody>(
"/rest/addPermission",
AddPermissionParams { user_id: Some(user_id), music_folder_id: Some(id) },
)
.await
.toast();
} else {
common_state
.send_with_common::<_, RemovePermissionBody>(
.send_with_common::<RemovePermissionBody>(
"/rest/removePermission",
RemovePermissionParams {
user_id: Some(user_id),
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/login/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub fn Login() -> Element {
role: Default::default(),
};
let LoginBody { id, role } = common_state_inner
.send_with_common::<_, LoginBody>("/rest/login", LoginParams {})
.send_with_common::<LoginBody>("/rest/login", LoginParams {})
.await?;

common_state.set(Some(CommonState { id, role, ..common_state_inner }));
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/setup/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn Setup() -> Element {
let result: Result<_, anyhow::Error> = try {
let server_url = server_url();

CommonState::send::<_, SetupBody>(
CommonState::send::<SetupBody>(
&server_url,
"rest/setup",
SetupParams {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/user/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub fn CreateUser() -> Element {
let Role { admin_role, stream_role, download_role, share_role } = role();

if common_state
.send_with_common::<_, CreateUserBody>(
.send_with_common::<CreateUserBody>(
"/rest/createUser",
CreateUserParams {
username: username(),
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/user/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn Users() -> Element {
if let Some(common_state) = common_state() {
users.set(
common_state
.send_with_common::<_, GetUsersBody>("/rest/getUsers", GetUsersParams {})
.send_with_common::<GetUsersBody>("/rest/getUsers", GetUsersParams {})
.await
.toast()
.map_or_else(Default::default, |r| {
Expand All @@ -43,7 +43,7 @@ pub fn Users() -> Element {
delete_idx.set(None);
let user = users.remove(idx);
common_state
.send_with_common::<_, DeleteUserBody>(
.send_with_common::<DeleteUserBody>(
"/rest/deleteUser",
DeleteUserParams { id: user.id },
)
Expand Down
18 changes: 7 additions & 11 deletions frontend/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,34 +60,30 @@ impl CommonState {
common_state
}

pub fn build_url_with_common<'common, P: WithCommon<'common, Out = impl Serialize>>(
pub fn build_url_with_common<'common>(
&'common self,
params: P,
params: impl WithCommon<'common, Out = impl Serialize>,
) -> String {
Self::build_url(params.with_common(&self.common))
}

pub fn build_url<P: Serialize>(params: P) -> String {
pub fn build_url(params: impl Serialize) -> String {
serde_html_form::to_string(params)
.expect("failed to serialize params which is not possible")
}

pub async fn send_with_common<
'common,
P: WithCommon<'common, Out = impl Serialize>,
B: DeserializeOwned,
>(
pub async fn send_with_common<'common, B: DeserializeOwned>(
&'common self,
url: &'static str,
params: P,
params: impl WithCommon<'common, Out = impl Serialize>,
) -> Result<B> {
Self::send_with_query(&self.server_url, url, &self.build_url_with_common(params)).await
}

pub async fn send<P: Serialize, B: DeserializeOwned>(
pub async fn send<B: DeserializeOwned>(
server_url: &Option<Url>,
url: &'static str,
params: P,
params: impl Serialize,
) -> Result<B> {
Self::send_with_query(server_url, url, &Self::build_url(params)).await
}
Expand Down
4 changes: 2 additions & 2 deletions lastfm-client/src/artist/get_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ mod tests {
async fn test_artist_get_info() {
let client = Client::new_from_env();
let params = Params { artist: Some("Cher".into()), mbid: None };
let artist = client.send::<_, Response>(&params).await.unwrap().artist;
let artist = client.send::<Response>(&params).await.unwrap().artist;
assert_eq!(artist.artist.name, "Cher");
assert_eq!(
artist.artist.mbid.unwrap(),
Expand All @@ -59,7 +59,7 @@ mod tests {
async fn test_artist_get_info_missing_mbid() {
let client = Client::new_from_env();
let params = Params { artist: Some("non-existent girl".into()), mbid: None };
let artist = client.send::<_, Response>(&params).await.unwrap().artist;
let artist = client.send::<Response>(&params).await.unwrap().artist;
assert_eq!(artist.artist.name, "non-existent girl");
assert!(artist.artist.mbid.is_none());
assert_eq!(artist.artist.url, "https://www.last.fm/music/non-existent+girl");
Expand Down
2 changes: 1 addition & 1 deletion lastfm-client/src/artist/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ mod tests {
let client = Client::new_from_env();
let params = Params { artist: "cher".into(), limit: Some(1), page: Some(1) };
let mut artists =
client.send::<_, Response>(&params).await.unwrap().results.artist_matches.artist;
client.send::<Response>(&params).await.unwrap().results.artist_matches.artist;
assert_eq!(artists.len(), 1);
let artist = artists.remove(0);
assert_eq!(artist.name, "Cher");
Expand Down
6 changes: 3 additions & 3 deletions lastfm-client/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ impl Client {
.map_err(ClientError::from)
}

pub async fn send<P: Serialize + MethodName, R: DeserializeOwned>(
pub async fn send<R: DeserializeOwned>(
&self,
params: &P,
params: &(impl Serialize + MethodName),
) -> Result<R, ClientError> {
self.client
.get(concat_string!(Self::LASTFM_ROOT_URL, self.to_query_str(params)?))
Expand Down Expand Up @@ -81,7 +81,7 @@ mod tests {

assert!(
Client::new("invalid-api-key".into())
.send::<_, ()>(&TestParams { ..Faker.fake() })
.send::<()>(&TestParams { ..Faker.fake() })
.await
.is_err()
)
Expand Down
4 changes: 2 additions & 2 deletions proc_macros/src/request/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ pub fn add_common_convert(input: TokenStream) -> Result<TokenStream, Error> {
impl<#lt> #with_common_path<#lt> for #item_ident {
type Out = #common_item_ident<#lt>;

fn with_common<T: Into<std::borrow::Cow<#lt, #common_path>>>(
self, common: T
fn with_common(
self, common: impl Into<std::borrow::Cow<#lt, #common_path>>
) -> #common_item_ident<#lt> {
let value = self;
let common = common.into();
Expand Down
2 changes: 1 addition & 1 deletion src/models/cover_arts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub struct NewCoverArt<'a> {
}

impl<'a> NewCoverArt<'a> {
pub fn to_path<P: AsRef<LocalPath>>(&'a self, song_art_dir: P) -> LocalPathBuf {
pub fn to_path(&'a self, song_art_dir: impl AsRef<LocalPath>) -> LocalPathBuf {
hash_size_to_path(song_art_dir, self.file_hash as _, self.file_size as _)
.join(concat_string!("cover.", self.format))
}
Expand Down
18 changes: 9 additions & 9 deletions src/open_subsonic/common/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ use crate::models::*;
use crate::utils::password::*;
use crate::{Database, OSError};

async fn validate<P: AsRef<CommonParams>, const REQUIRED_ROLE: users::Role>(
async fn validate<const REQUIRED_ROLE: users::Role>(
Database { pool, key }: &Database,
common_params: P,
common_params: impl AsRef<CommonParams>,
) -> Result<(Uuid, users::Role)> {
let common_params = common_params.as_ref();
let (user_id, user_password, user_role) = match users::table
Expand Down Expand Up @@ -67,7 +67,7 @@ where
.await
.map_err(std::convert::Into::<OSError>::into)?;
let database = Database::from_ref(state);
let (user_id, user_role) = validate::<_, REQUIRED_ROLE>(&database, &params).await?;
let (user_id, user_role) = validate::<REQUIRED_ROLE>(&database, &params).await?;
(user_id, user_role, params.into())
}
Method::POST => {
Expand All @@ -82,7 +82,7 @@ where
.await
.map_err(std::convert::Into::<OSError>::into)?;
let database = Database::from_ref(state);
let (user_id, user_role) = validate::<_, REQUIRED_ROLE>(&database, &common).await?;
let (user_id, user_role) = validate::<REQUIRED_ROLE>(&database, &common).await?;
(user_id, user_role, params)
}
_ => unreachable!("method is not allowed"),
Expand Down Expand Up @@ -120,7 +120,7 @@ mod tests {
async fn test_validate_success() {
let infra = Infra::new().await.add_user(None).await;
assert!(
validate::<_, { users::Role::const_default() }>(
validate::<{ users::Role::const_default() }>(
infra.database(),
TestParams {}.with_common(infra.to_common_params(0))
)
Expand All @@ -134,7 +134,7 @@ mod tests {
let infra = Infra::new().await.add_user(None).await;
let wrong_username: String = Username().fake();
assert!(matches!(
validate::<_, { users::Role::const_default() }>(
validate::<{ users::Role::const_default() }>(
infra.database(),
TestParams {}.with_common(CommonParams {
username: wrong_username,
Expand All @@ -159,7 +159,7 @@ mod tests {
let client_token = to_password_token(Password(16..32).fake::<String>(), &client_salt);

assert!(matches!(
validate::<_, { users::Role::const_default() }>(
validate::<{ users::Role::const_default() }>(
infra.database(),
TestParams {}.with_common(CommonParams {
username,
Expand All @@ -183,7 +183,7 @@ mod tests {
.add_user(Some(users::Role { admin_role: true, ..users::Role::const_default() }))
.await;
assert!(
validate::<_, { users::Role { admin_role: true, ..users::Role::const_default() } }>(
validate::<{ users::Role { admin_role: true, ..users::Role::const_default() } }>(
infra.database(),
TestParams {}.with_common(infra.to_common_params(0))
)
Expand All @@ -196,7 +196,7 @@ mod tests {
async fn test_validate_no_admin() {
let infra = Infra::new().await.add_user(None).await;
assert!(matches!(
validate::<_, { users::Role { admin_role: true, ..users::Role::const_default() } }>(
validate::<{ users::Role { admin_role: true, ..users::Role::const_default() } }>(
infra.database(),
TestParams {}.with_common(infra.to_common_params(0))
)
Expand Down
12 changes: 6 additions & 6 deletions src/open_subsonic/common/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ impl StreamResponse {
mime_guess::from_ext(ext).first_or_octet_stream()
}

pub async fn try_from_path<P: AsRef<LocalPath>, O: Into<Option<u64>>, S: Into<Option<u64>>>(
path: P,
offset: O,
size: S,
pub async fn try_from_path(
path: impl AsRef<LocalPath>,
offset: impl Into<Option<u64>>,
size: impl Into<Option<u64>>,
seekable: bool,
) -> Result<Self> {
let path = path.as_ref();
Expand All @@ -72,12 +72,12 @@ impl StreamResponse {
))
}

pub fn from_async_read<R: AsyncRead + Send + Sync + 'static>(
pub fn from_async_read(
ext: &str,
offset: u64,
size: u64,
seekable: bool,
reader: R,
reader: impl AsyncRead + Send + Sync + 'static,
) -> Self {
Self {
mime: Self::from_ext(ext),
Expand Down
6 changes: 3 additions & 3 deletions src/open_subsonic/cover_art/upsert_cover_art_from_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use crate::utils::fs::path::hash_size_to_path;
use crate::utils::fs::LocalPath;
use crate::DatabasePool;

pub async fn upsert_cover_art_from_data<P: AsRef<LocalPath>, D: AsRef<[u8]>>(
pub async fn upsert_cover_art_from_data(
pool: &DatabasePool,
art_dir: P,
file_data: D,
art_dir: impl AsRef<LocalPath>,
file_data: impl AsRef<[u8]>,
file_format: &str,
) -> Result<Uuid> {
let file_data = file_data.as_ref();
Expand Down
4 changes: 2 additions & 2 deletions src/open_subsonic/cover_art/upsert_cover_art_from_url.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use super::upsert_cover_art_from_data;
use crate::utils::fs::LocalPath;
use crate::{DatabasePool, OSError};

pub async fn upsert_cover_art_from_url<P: AsRef<LocalPath>>(
pub async fn upsert_cover_art_from_url(
pool: &DatabasePool,
art_dir: P,
art_dir: impl AsRef<LocalPath>,
url: &str,
) -> Result<Uuid> {
let response = reqwest::get(url).await?.error_for_status()?;
Expand Down
Loading

0 comments on commit 718daf7

Please sign in to comment.