Skip to content

Commit 7c37a03

Browse files
committed
v0.4.6 : clippy pedantic
1 parent 19d6f5e commit 7c37a03

File tree

6 files changed

+90
-75
lines changed

6 files changed

+90
-75
lines changed

Cargo.toml

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ license = "MIT OR Apache-2.0"
99
name = "shmap"
1010
readme = "README.md"
1111
repository = "https://github.com/BarbossHack/shmap"
12-
version = "0.4.5"
12+
version = "0.4.6"
1313

1414
[dependencies]
1515
aes-gcm = { version = "0.10", features = ["std"] }
@@ -19,11 +19,18 @@ fdlimit = "0.3"
1919
libc = "0.2"
2020
log = "0.4"
2121
memmap2 = "0.9"
22-
named-lock = "0.3"
22+
named-lock = "0.4"
2323
rand = "0.8"
2424
serde = { version = "1.0", features = ["serde_derive"] }
2525
sha2 = "0.10"
2626
thiserror = "1.0"
2727

2828
[dev-dependencies]
29-
env_logger = "0.10"
29+
env_logger = "0.11"
30+
31+
[lints.clippy]
32+
missing_errors_doc = "allow"
33+
nursery = { level = "warn", priority = -1 }
34+
pedantic = { level = "warn", priority = -1 }
35+
undocumented_unsafe_blocks = "warn"
36+
unwrap_used = "warn"

clippy.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
allow-unwrap-in-tests = true

src/map.rs

Lines changed: 35 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::{
22
errors::ShmapError,
33
metadata::Metadata,
4-
shm::{shm_open_read, shm_open_write, shm_unlink, SHM_DIR},
4+
shm::{self, SHM_DIR},
55
};
66
use aes_gcm::{
77
aead::{generic_array::GenericArray, Aead},
@@ -38,13 +38,15 @@ impl Default for Shmap {
3838

3939
impl Shmap {
4040
/// Initialize Shmap with no TTL or encryption.
41+
#[must_use]
4142
pub fn new() -> Self {
42-
Shmap::_new(None)
43+
Self::_new(None)
4344
}
4445

4546
/// Initialize Shmap with AES256 encryption key (random bytes).
47+
#[must_use]
4648
pub fn new_with_encryption(encryption_key: &[u8; 32]) -> Self {
47-
Shmap::_new(Some(encryption_key))
49+
Self::_new(Some(encryption_key))
4850
}
4951

5052
fn _new(encryption_key: Option<&[u8; 32]>) -> Self {
@@ -58,9 +60,9 @@ impl Shmap {
5860
Aes256Gcm::new(key)
5961
});
6062

61-
let shmap = Shmap { cipher };
63+
let shmap = Self { cipher };
6264
if let Err(e) = shmap.clean() {
63-
warn!("Error while cleaning shmap keys: {}", e)
65+
warn!("Error while cleaning shmap keys: {}", e);
6466
}
6567
shmap
6668
}
@@ -74,17 +76,14 @@ impl Shmap {
7476

7577
// Remove item if expired
7678
let not_found = match self.get_metadata(key)? {
77-
Some(metadata) => match metadata.expiration {
78-
Some(expiration) => {
79-
let expired = Utc::now().gt(&expiration);
80-
if expired {
81-
warn!("Key <{}> expired, removing", &key);
82-
let _ = self.remove(key);
83-
}
84-
expired
79+
Some(metadata) => metadata.expiration.map_or(false, |expiration| {
80+
let expired = Utc::now().gt(&expiration);
81+
if expired {
82+
warn!("Key <{}> expired, removing", &key);
83+
let _ = self.remove(key);
8584
}
86-
None => false,
87-
},
85+
expired
86+
}),
8887
None => true,
8988
};
9089
if not_found {
@@ -123,7 +122,7 @@ impl Shmap {
123122
let lock = NamedLock::with_path(
124123
PathBuf::from(SHM_DIR).join(
125124
sanitized_key
126-
.trim_end_matches(&format!(".{}", METADATA_SUFFIX))
125+
.trim_end_matches(&format!(".{METADATA_SUFFIX}"))
127126
.to_string()
128127
+ "."
129128
+ LOCK_SUFFIX,
@@ -132,7 +131,7 @@ impl Shmap {
132131
let guard = lock.lock()?;
133132

134133
// Read the item from shm
135-
let fd = match shm_open_read(sanitized_key) {
134+
let fd = match shm::open_read(sanitized_key) {
136135
Ok(fd) => fd,
137136
Err(e) => match e {
138137
ShmapError::ShmFileNotFound => {
@@ -143,6 +142,7 @@ impl Shmap {
143142
e => return Err(e),
144143
},
145144
};
145+
// SAFETY: Mmap call is unsafe
146146
let mmap = unsafe { Mmap::map(fd) }?;
147147
if mmap.len() == 0 {
148148
// If the value is empty, remove it and return None
@@ -162,10 +162,9 @@ impl Shmap {
162162
sanitized_key
163163
);
164164
return Ok(None);
165-
} else {
166-
let nonce = Nonce::from_slice(&mmap[..12]);
167-
cipher.decrypt(nonce, &mmap[12..])?
168165
}
166+
let nonce = Nonce::from_slice(&mmap[..12]);
167+
cipher.decrypt(nonce, &mmap[12..])?
169168
} else {
170169
mmap.to_vec()
171170
};
@@ -238,7 +237,7 @@ impl Shmap {
238237
let lock = NamedLock::with_path(
239238
PathBuf::from(SHM_DIR).join(
240239
sanitized_key
241-
.trim_end_matches(&format!(".{}", METADATA_SUFFIX))
240+
.trim_end_matches(&format!(".{METADATA_SUFFIX}"))
242241
.to_string()
243242
+ "."
244243
+ LOCK_SUFFIX,
@@ -247,13 +246,16 @@ impl Shmap {
247246
let guard = lock.lock()?;
248247

249248
// Insert the item to shm
250-
match || -> Result<(), ShmapError> {
251-
let fd = shm_open_write(sanitized_key, bytes.len())?;
249+
let write_result = || -> Result<(), ShmapError> {
250+
let fd = shm::open_write(sanitized_key, bytes.len())?;
251+
// SAFETY: libc call is unsafe
252252
let mut mmap = unsafe { MmapMut::map_mut(fd) }?;
253253
mmap.copy_from_slice(bytes.as_slice());
254254
Ok(())
255-
}() {
256-
Ok(_) => Ok(()),
255+
}();
256+
257+
match write_result {
258+
Ok(()) => Ok(()),
257259
Err(e) => {
258260
drop(guard);
259261
let _ = self._remove(sanitized_key);
@@ -274,12 +276,13 @@ impl Shmap {
274276
self._remove(&sanitize_metadata_key)
275277
}
276278

279+
#[allow(clippy::unused_self)]
277280
fn _remove(&self, sanitized_key: &str) -> Result<(), ShmapError> {
278281
if !sanitized_key.ends_with(LOCK_SUFFIX) {
279282
let lock = NamedLock::with_path(
280283
PathBuf::from(SHM_DIR).join(
281284
sanitized_key
282-
.trim_end_matches(&format!(".{}", METADATA_SUFFIX))
285+
.trim_end_matches(&format!(".{METADATA_SUFFIX}"))
283286
.to_string()
284287
+ "."
285288
+ LOCK_SUFFIX,
@@ -288,7 +291,7 @@ impl Shmap {
288291
let _guard = lock.lock()?;
289292
}
290293

291-
shm_unlink(sanitized_key)?;
294+
shm::unlink(sanitized_key)?;
292295

293296
Ok(())
294297
}
@@ -317,7 +320,7 @@ impl Shmap {
317320
&& !filename.ends_with(METADATA_SUFFIX)
318321
&& !filename.ends_with(LOCK_SUFFIX)
319322
{
320-
let metadata_filename = format!("{}.{}", filename, METADATA_SUFFIX);
323+
let metadata_filename = format!("{filename}.{METADATA_SUFFIX}");
321324
match self.get_deserialize::<Metadata>(&metadata_filename) {
322325
Ok(Some(metadata)) => match metadata.expiration {
323326
Some(expiration) => {
@@ -353,8 +356,7 @@ impl Shmap {
353356
}
354357
} else if filename.starts_with(SHMAP_PREFIX) && filename.ends_with(METADATA_SUFFIX) {
355358
let filename_path = dir_entry.path().to_string_lossy().to_string();
356-
let item_filename =
357-
filename_path.trim_end_matches(&format!(".{}", METADATA_SUFFIX));
359+
let item_filename = filename_path.trim_end_matches(&format!(".{METADATA_SUFFIX}"));
358360
if !PathBuf::from(item_filename).exists()
359361
&& duration_since_modified_time > Duration::from_secs(5)
360362
{
@@ -366,9 +368,9 @@ impl Shmap {
366368
}
367369
} else if filename.starts_with(SHMAP_PREFIX) && filename.ends_with(LOCK_SUFFIX) {
368370
let filename_path = dir_entry.path().to_string_lossy().to_string();
369-
let item_filename = filename_path.trim_end_matches(&format!(".{}", LOCK_SUFFIX));
371+
let item_filename = filename_path.trim_end_matches(&format!(".{LOCK_SUFFIX}"));
370372
if !PathBuf::from(item_filename).exists()
371-
&& !PathBuf::from(format!("{}.{}", item_filename, METADATA_SUFFIX)).exists()
373+
&& !PathBuf::from(format!("{item_filename}.{METADATA_SUFFIX}")).exists()
372374
&& duration_since_modified_time > Duration::from_secs(5)
373375
{
374376
warn!(
@@ -383,7 +385,7 @@ impl Shmap {
383385
}
384386
}
385387

386-
pub(crate) fn sanitize_key(key: &str) -> String {
388+
pub fn sanitize_key(key: &str) -> String {
387389
let mut hasher = Sha224::new();
388390
hasher.update(key);
389391
format!("{}.{:x}", SHMAP_PREFIX, hasher.finalize())

src/metadata.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ impl Metadata {
2525
None => None,
2626
};
2727

28-
Ok(Metadata {
28+
Ok(Self {
2929
key: key.to_owned(),
3030
expiration,
3131
encrypted,

src/shm.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ pub struct Fd(RawFd);
1313

1414
impl From<RawFd> for Fd {
1515
fn from(value: RawFd) -> Self {
16-
Fd(value)
16+
Self(value)
1717
}
1818
}
1919

@@ -25,14 +25,15 @@ impl MmapAsRawDesc for Fd {
2525

2626
impl Drop for Fd {
2727
fn drop(&mut self) {
28+
// SAFETY: libc call is unsafe
2829
unsafe {
2930
libc::close(self.0);
3031
}
3132
}
3233
}
3334

3435
/// Open shm in readonly.
35-
pub fn shm_open_read(name: &str) -> Result<Fd, ShmapError> {
36+
pub fn open_read(name: &str) -> Result<Fd, ShmapError> {
3637
let fd = shm_open(name, libc::O_RDONLY)?;
3738
// On success, returns a file descriptor (a nonnegative integer)
3839
if fd < 0 {
@@ -49,14 +50,16 @@ pub fn shm_open_read(name: &str) -> Result<Fd, ShmapError> {
4950
}
5051

5152
/// Open shm with read/write rights, and initialze it to `length`size.
52-
pub fn shm_open_write(name: &str, length: usize) -> Result<Fd, ShmapError> {
53+
pub fn open_write(name: &str, length: usize) -> Result<Fd, ShmapError> {
5354
let fd = shm_open(name, libc::O_RDWR | libc::O_CREAT | libc::O_TRUNC)?;
5455
// On success, returns a file descriptor (a nonnegative integer)
5556
if fd < 0 {
5657
let err = std::io::Error::last_os_error();
5758
return Err(ShmapError::IOError(err));
5859
}
5960

61+
// SAFETY: libc call is unsafe
62+
#[allow(clippy::cast_possible_wrap)]
6063
let ret = unsafe { libc::ftruncate(fd, length as libc::off_t) };
6164
if ret != 0 {
6265
let err = std::io::Error::last_os_error();
@@ -68,14 +71,16 @@ pub fn shm_open_write(name: &str, length: usize) -> Result<Fd, ShmapError> {
6871

6972
fn shm_open(name: &str, flags: i32) -> Result<RawFd, ShmapError> {
7073
let name = std::ffi::CString::new(name)?;
74+
// SAFETY: libc call is unsafe
7175
let fd = unsafe { libc::shm_open(name.as_ptr(), flags, 0o600) };
7276
Ok(fd)
7377
}
7478

7579
/// Unlink (remove) shm by its name.
76-
pub fn shm_unlink(name: &str) -> Result<(), ShmapError> {
77-
let name = std::ffi::CString::new(name)?;
78-
let ret = unsafe { libc::shm_unlink(name.as_ptr()) };
80+
pub fn unlink(name: &str) -> Result<(), ShmapError> {
81+
let c_name = std::ffi::CString::new(name)?;
82+
// SAFETY: libc call is unsafe
83+
let ret = unsafe { libc::shm_unlink(c_name.as_ptr()) };
7984
// returns 0 on success, or -1 on error
8085
if ret != 0 {
8186
let err = std::io::Error::last_os_error();

0 commit comments

Comments
 (0)