Skip to content

Commit

Permalink
Merge pull request #145 from qvkare/main
Browse files Browse the repository at this point in the history
Fix Clippy Warnings and Code Quality Improvements
  • Loading branch information
Joinhack authored Jan 20, 2025
2 parents 2af41de + 32fd136 commit cad54a1
Show file tree
Hide file tree
Showing 21 changed files with 86 additions and 109 deletions.
1 change: 1 addition & 0 deletions crates/blockless-drivers/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ edition = "2021"
default = ["builtin_http"]
builtin_http = []
wiggle_metadata = ["wiggle/wiggle_metadata"]
runtime = []

[dependencies]
blockless-drivers-macro = {path = "macro"}
Expand Down
18 changes: 9 additions & 9 deletions crates/blockless-drivers/macro/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ pub struct BlocklessConfig {
}

enum BlocklessConfigField {
WitxField(Paths),
LinkMethodField(syn::LitStr),
TargetField(syn::Path),
Witx(Paths),
LinkMethod(syn::LitStr),
Target(syn::Path),
}

mod kw {
Expand All @@ -29,9 +29,9 @@ impl BlocklessConfig {
let mut link_method = None;
for f in fields {
match f {
BlocklessConfigField::TargetField(t) => target = Some(t),
BlocklessConfigField::LinkMethodField(m) => link_method = Some(m),
BlocklessConfigField::WitxField(paths) => {
BlocklessConfigField::Target(t) => target = Some(t),
BlocklessConfigField::LinkMethod(m) => link_method = Some(m),
BlocklessConfigField::Witx(paths) => {
witx_confg = Some(WitxConf::Paths(paths));
}
}
Expand Down Expand Up @@ -65,15 +65,15 @@ impl Parse for BlocklessConfigField {
if lookahead.peek(kw::witx) {
input.parse::<kw::witx>()?;
input.parse::<Token![:]>()?;
Ok(BlocklessConfigField::WitxField(input.parse()?))
Ok(BlocklessConfigField::Witx(input.parse()?))
} else if lookahead.peek(kw::target) {
input.parse::<kw::target>()?;
input.parse::<Token![:]>()?;
Ok(BlocklessConfigField::TargetField(input.parse()?))
Ok(BlocklessConfigField::Target(input.parse()?))
} else if lookahead.peek(kw::link_method) {
input.parse::<kw::link_method>()?;
input.parse::<Token![:]>()?;
Ok(BlocklessConfigField::LinkMethodField(input.parse()?))
Ok(BlocklessConfigField::LinkMethod(input.parse()?))
} else {
Err(lookahead.error())
}
Expand Down
8 changes: 4 additions & 4 deletions crates/blockless-drivers/src/cdylib_driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ impl Driver for CdylibDriver {
let api = self.api.clone();
let uri: String = uri.into();
let opts: String = opts.into();
return Box::pin(async move {
Box::pin(async move {
let addr = match multiaddr::parse(uri.as_bytes()) {
Err(e) => {
error!("error parse:{:?}", e);
return Err(ErrorKind::DriverBadParams);
Err(ErrorKind::DriverBadParams)?
}
Ok(addr) => addr,
};
Expand All @@ -83,11 +83,11 @@ impl Driver for CdylibDriver {
let mut fd = 0;
let rs = api.blockless_open(&addr, &opts, &mut fd);
if rs != 0 {
return Err(rs.into());
Err(ErrorKind::from(rs))?
}
let file: DriverWasiFile = DriverWasiFile::new(api, fd)?;
let file: Box<dyn WasiFile> = Box::new(file);
Ok(file)
});
})
}
}
16 changes: 6 additions & 10 deletions crates/blockless-drivers/src/cgi_driver/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,21 @@ use std::path::Path;
use anyhow::Result;
use rusqlite::{Connection, OptionalExtension};

#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, Default)]
pub(crate) enum ExtensionMetaStatus {
#[default]
Normal = 0,
UPDATE = 1,
Invalid = -1,
}

impl Default for ExtensionMetaStatus {
fn default() -> Self {
ExtensionMetaStatus::Normal
}
}

impl From<i32> for ExtensionMetaStatus {
fn from(value: i32) -> Self {
match value {
0 => ExtensionMetaStatus::Normal,
1 => ExtensionMetaStatus::UPDATE,
-1 | _ => ExtensionMetaStatus::Invalid,
-1 => ExtensionMetaStatus::Invalid,
_ => ExtensionMetaStatus::Invalid,
}
}
}
Expand Down Expand Up @@ -69,7 +65,7 @@ impl DB {
"#;
Ok(self
.connect
.query_row(query_sql, &[alias], |row| {
.query_row(query_sql, [alias], |row| {
let id = row.get(0)?;
let alias = row.get(1)?;
let md5 = row.get(2)?;
Expand Down Expand Up @@ -114,7 +110,7 @@ impl DB {
.map(|rows| rows.filter_map(|row| row.ok()).collect::<Vec<_>>())?)
}

pub(crate) fn save_extensions(&mut self, exts: &Vec<ExtensionMeta>) -> Result<()> {
pub(crate) fn save_extensions(&mut self, exts: &[ExtensionMeta]) -> Result<()> {
for meta in exts.iter() {
match meta.status {
ExtensionMetaStatus::Normal => self.insert_extension_meta(meta),
Expand Down
13 changes: 4 additions & 9 deletions crates/blockless-drivers/src/cgi_driver/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ impl CgiProcess {
json::JsonValue::Array(ref args) => args
.iter()
.map(|arg| arg.as_str().map(String::from))
.filter(Option::is_some)
.map(Option::unwrap)
.flatten()
.collect(),
_ => Vec::new(),
};
Expand All @@ -87,8 +86,7 @@ impl CgiProcess {
.map(String::from)
.zip(arg["env_val"].as_str().map(String::from))
})
.filter(Option::is_some)
.map(Option::unwrap)
.flatten()
.collect(),
_ => Vec::new(),
};
Expand Down Expand Up @@ -233,7 +231,7 @@ async fn file_md5(path: impl AsRef<Path>) -> anyhow::Result<md5::Digest> {
/// get file meta from execute output with the parameter "--ext_verify".
async fn get_file_meta(file_path: &str) -> anyhow::Result<Option<ExtensionMeta>> {
let mut command = Command::new(file_path);
command.args(&["--ext_verify"]);
command.args(["--ext_verify"]);
let child = command.output().await?;
let val = std::str::from_utf8(&child.stdout[..])?;
//parse output json like {"alias":"xxx", "md5":"xxxx", "desciption":"xxxxx", "is_cgi": true}
Expand Down Expand Up @@ -338,10 +336,7 @@ async fn cgi_directory_list_extensions(path: &str) -> Result<Vec<ExtensionMeta>,
};
let metas = metas
.into_iter()
.filter(|meta| match meta.status {
ExtensionMetaStatus::Invalid => false,
_ => true,
})
.filter(|meta| !matches!(meta.status, ExtensionMetaStatus::Invalid))
.collect::<Vec<_>>();
Ok(metas)
}
Expand Down
62 changes: 31 additions & 31 deletions crates/blockless-drivers/src/ipfs_driver/http_raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,34 +65,34 @@ impl HttpRaw {
);
let _ = headers.iter().for_each(|(k, v)| {
let _ = v.iter().for_each(|i| {
buf.write(format!("{}: {}", k, i).as_bytes()).unwrap();
buf.write(EOL).unwrap();
buf.write_all(format!("{}: {}", k, i).as_bytes()).unwrap();
buf.write_all(EOL).unwrap();
});
});
buf
}

fn boundary_begin(boundary: &str) -> Vec<u8> {
let mut buf = Vec::<u8>::with_capacity(1024);
buf.write(b"--").unwrap();
buf.write(boundary.as_bytes()).unwrap();
buf.write(EOL).unwrap();
buf.write(b"Content-Disposition: form-data").unwrap();
buf.write(EOL).unwrap();
buf.write(b"Content-Type: application/octet-stream")
buf.write_all(b"--").unwrap();
buf.write_all(boundary.as_bytes()).unwrap();
buf.write_all(EOL).unwrap();
buf.write_all(b"Content-Disposition: form-data").unwrap();
buf.write_all(EOL).unwrap();
buf.write_all(b"Content-Type: application/octet-stream")
.unwrap();
buf.write(EOL).unwrap();
buf.write(EOL).unwrap();
buf.write_all(EOL).unwrap();
buf.write_all(EOL).unwrap();
buf
}

fn boundary_end(boundary: &str) -> Vec<u8> {
let mut buf = Vec::<u8>::with_capacity(1024);
buf.write(EOL).unwrap();
buf.write(b"--").unwrap();
buf.write(boundary.as_bytes()).unwrap();
buf.write(b"--").unwrap();
buf.write(EOL).unwrap();
buf.write_all(EOL).unwrap();
buf.write_all(b"--").unwrap();
buf.write_all(boundary.as_bytes()).unwrap();
buf.write_all(b"--").unwrap();
buf.write_all(EOL).unwrap();
buf
}

Expand All @@ -103,16 +103,16 @@ impl HttpRaw {
.ok_or(IpfsErrorKind::RequestError)?;
let boundary = self.boundary.as_ref().ok_or(IpfsErrorKind::RequestError)?;
let mut body_buf = Self::boundary_begin(boundary);
body_buf.write(val).unwrap();
body_buf.write(&Self::boundary_end(boundary)).unwrap();
body_buf.write_all(val).unwrap();
body_buf.write_all(&Self::boundary_end(boundary)).unwrap();
let mut buf = Vec::new();
buf.write(format!("Content-Length: {}", body_buf.len()).as_bytes())
buf.write_all(format!("Content-Length: {}", body_buf.len()).as_bytes())
.unwrap();
buf.write(EOL).unwrap();
buf.write(format!("Content-Type: multipart/form-data; boundary={}", boundary).as_bytes())
buf.write_all(EOL).unwrap();
buf.write_all(format!("Content-Type: multipart/form-data; boundary={}", boundary).as_bytes())
.unwrap();
buf.write(EOL).unwrap();
buf.write(EOL).unwrap();
buf.write_all(EOL).unwrap();
buf.write_all(EOL).unwrap();
buf.extend_from_slice(&body_buf);
Self::write_all(tcp_stream, buf).await?;
Ok(val.len() as _)
Expand Down Expand Up @@ -214,18 +214,18 @@ impl HttpRaw {

fn get_req_raw(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(1024);
buf.write(self.method.as_bytes()).unwrap();
buf.write(b" ").unwrap();
buf.write(self.url.path().as_bytes()).unwrap();
buf.write_all(self.method.as_bytes()).unwrap();
buf.write_all(b" ").unwrap();
buf.write_all(self.url.path().as_bytes()).unwrap();
self.url.query().map(|q| {
buf.write(b"?").unwrap();
buf.write(q.as_bytes()).unwrap();
buf.write_all(b"?").unwrap();
buf.write_all(q.as_bytes()).unwrap();
});
buf.write(b" ").unwrap();
buf.write(HTTP1).unwrap();
buf.write(EOL).unwrap();
buf.write_all(b" ").unwrap();
buf.write_all(HTTP1).unwrap();
buf.write_all(EOL).unwrap();
let h = self.header_raw();
buf.write(&h).unwrap();
buf.write_all(&h).unwrap();
buf
}

Expand Down
4 changes: 2 additions & 2 deletions crates/blockless-drivers/src/ipfs_driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ pub async fn close(handle: u32) -> Result<(), IpfsErrorKind> {

pub async fn write_body(handle: u32, buf: &[u8]) -> Result<u32, IpfsErrorKind> {
let ctx = get_ctx().unwrap();
if buf.len() == 0 {
if buf.is_empty() {
return Err(IpfsErrorKind::InvalidParameter);
}
let size = match ctx.get_mut(&handle) {
Expand All @@ -93,7 +93,7 @@ pub async fn write_body(handle: u32, buf: &[u8]) -> Result<u32, IpfsErrorKind> {

pub async fn read_body(handle: u32, buf: &mut [u8]) -> Result<u32, IpfsErrorKind> {
let ctx = get_ctx().unwrap();
if buf.len() == 0 {
if buf.is_empty() {
return Err(IpfsErrorKind::InvalidParameter);
}
match ctx.get_mut(&handle) {
Expand Down
4 changes: 3 additions & 1 deletion crates/blockless-drivers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,16 @@ use std::sync::Mutex;
use tcp_driver::TcpDriver;
use wasi_common::WasiFile;

type OpenFuture = Pin<Box<dyn Future<Output = Result<Box<dyn WasiFile>, ErrorKind>> + Send>>;

pub trait Driver {
fn name(&self) -> &str;

fn open(
&self,
uri: &str,
opts: &str,
) -> Pin<Box<dyn Future<Output = Result<Box<dyn WasiFile>, ErrorKind>> + Send>>;
) -> OpenFuture;
}

lazy_static! {
Expand Down
2 changes: 1 addition & 1 deletion crates/blockless-drivers/src/memory_driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::BlocklessMemoryErrorKind;
pub async fn read(buf: &mut [u8], string: String) -> Result<u32, BlocklessMemoryErrorKind> {
let bytes = string.as_bytes();

if buf.len() == 0 {
if buf.is_empty() {
return Err(BlocklessMemoryErrorKind::InvalidParameter);
}

Expand Down
4 changes: 2 additions & 2 deletions crates/blockless-drivers/src/s3_driver/bucket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ pub(crate) async fn list(cfg: &str) -> Result<String, S3ErrorKind> {
obj["name"] = rs.name.clone().into();
obj["is_truncated"] = rs.is_truncated.into();
rs.prefix.as_ref().map(|prefix| {
obj["prefix"] = prefix.clone().into();
obj["prefix"] = prefix.as_str().into();
});
let contents = rs
.contents
Expand All @@ -105,7 +105,7 @@ pub(crate) async fn list(cfg: &str) -> Result<String, S3ErrorKind> {
obj["e_tag"] = c.e_tag.clone().into();
obj["storage_class"] = c.storage_class.clone().into();
obj["key"] = c.key.clone().into();
obj["size"] = c.size.clone().into();
obj["size"] = c.size.into();
obj
})
.collect::<Vec<_>>();
Expand Down
2 changes: 1 addition & 1 deletion crates/blockless-drivers/src/s3_driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub async fn bucket_put_object(cfg: &str, buf: &[u8]) -> Result<(), S3ErrorKind>

pub async fn read(handle: u32, buf: &mut [u8]) -> Result<u32, S3ErrorKind> {
let ctx = get_ctx().unwrap();
if buf.len() == 0 {
if buf.is_empty() {
return Err(S3ErrorKind::InvalidParameter);
}
match ctx.get_mut(&handle) {
Expand Down
10 changes: 5 additions & 5 deletions crates/blockless-drivers/src/tcp_driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,28 @@ impl Driver for TcpDriver {
let socket: String = socket.into();
//this open options.
let _opts: String = opts.into();
return Box::pin(async move {
Box::pin(async move {
let ma = multiaddr::parse(socket.as_bytes()).map_err(|e| {
error!("error open:{:?}", e);
ErrorKind::DriverBadOpen
})?;
if ma.paths_ref().len() < 1 {
if ma.paths_ref().is_empty() {
error!("error open error path : {}", socket);
return Err(ErrorKind::DriverBadOpen);
Err(ErrorKind::DriverBadOpen)?
}
let socket = ma.paths_ref()[1].value_to_str();
let stream = match TcpStream::connect(socket).await {
Ok(s) => s,
Err(e) => {
error!("error connect in driver {}: {}", socket, e);
return Err(ErrorKind::ConnectError);
Err(ErrorKind::ConnectError)?
}
};
let stream = cap_std::net::TcpStream::from_std(stream.into_std().unwrap());
let socket: Socket = Socket::from(stream);
let stream: Box<dyn WasiFile> = Box::<dyn WasiFile>::from(socket);
Ok(stream)
});
})
}
}

Expand Down
Loading

0 comments on commit cad54a1

Please sign in to comment.