Skip to content

Commit

Permalink
Refacotr test code
Browse files Browse the repository at this point in the history
Change-Id: Ibd72cedd16a1a8415b9a6f6a98cc4f013b54628a
  • Loading branch information
yangkx1024 committed Nov 24, 2023
1 parent 3cf6b8b commit 29512c1
Show file tree
Hide file tree
Showing 26 changed files with 197 additions and 282 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "mmkv"
version = "0.2.7"
version = "0.2.8"
edition = "2021"
authors = ["Kexuan Yang <[email protected]>"]
description = "Rust version of MMKV"
Expand Down
5 changes: 3 additions & 2 deletions android/buildSrc/src/main/java/Configuration.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
object Configuration {
// const val libVersion = "0.2.7.1-SNAPSHOT"
const val libVersion = "0.2.7.1"
const val versionStr = "0.2.8"
// const val libVersion = versionStr + "-SNAPSHOT"
const val libVersion = versionStr
const val groupId = "net.yangkx"
const val description = "Library uses file-based mmap to store key-values"
private const val releasesRepoUrl = "https://s01.oss.sonatype.org/content/repositories/releases/"
Expand Down
Git LFS file not shown
Git LFS file not shown
Git LFS file not shown
4 changes: 2 additions & 2 deletions android/library-encrypt/src/main/jniLibs/arm64-v8a/libmmkv.so
Git LFS file not shown
Git LFS file not shown
4 changes: 2 additions & 2 deletions android/library-encrypt/src/main/jniLibs/x86_64/libmmkv.so
Git LFS file not shown
4 changes: 2 additions & 2 deletions android/library/src/debug/jniLibs/arm64-v8a/libmmkv.so
Git LFS file not shown
4 changes: 2 additions & 2 deletions android/library/src/debug/jniLibs/armeabi-v7a/libmmkv.so
Git LFS file not shown
2 changes: 1 addition & 1 deletion android/library/src/debug/jniLibs/x86_64/libmmkv.so
Git LFS file not shown
4 changes: 2 additions & 2 deletions android/library/src/main/jniLibs/arm64-v8a/libmmkv.so
Git LFS file not shown
4 changes: 2 additions & 2 deletions android/library/src/main/jniLibs/armeabi-v7a/libmmkv.so
Git LFS file not shown
4 changes: 2 additions & 2 deletions android/library/src/main/jniLibs/x86_64/libmmkv.so
Git LFS file not shown
16 changes: 8 additions & 8 deletions ios/MMKV/Sources/RustMMKV.xcframework/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<key>HeadersPath</key>
<string>Headers</string>
<key>LibraryIdentifier</key>
<string>macos-arm64_x86_64</string>
<string>ios-arm64_x86_64-simulator</string>
<key>LibraryPath</key>
<string>libmmkv.a</string>
<key>SupportedArchitectures</key>
Expand All @@ -19,42 +19,42 @@
<string>x86_64</string>
</array>
<key>SupportedPlatform</key>
<string>macos</string>
<string>ios</string>
<key>SupportedPlatformVariant</key>
<string>simulator</string>
</dict>
<dict>
<key>BinaryPath</key>
<string>libmmkv.a</string>
<key>HeadersPath</key>
<string>Headers</string>
<key>LibraryIdentifier</key>
<string>ios-arm64_x86_64-simulator</string>
<string>ios-arm64</string>
<key>LibraryPath</key>
<string>libmmkv.a</string>
<key>SupportedArchitectures</key>
<array>
<string>arm64</string>
<string>x86_64</string>
</array>
<key>SupportedPlatform</key>
<string>ios</string>
<key>SupportedPlatformVariant</key>
<string>simulator</string>
</dict>
<dict>
<key>BinaryPath</key>
<string>libmmkv.a</string>
<key>HeadersPath</key>
<string>Headers</string>
<key>LibraryIdentifier</key>
<string>ios-arm64</string>
<string>macos-arm64_x86_64</string>
<key>LibraryPath</key>
<string>libmmkv.a</string>
<key>SupportedArchitectures</key>
<array>
<string>arm64</string>
<string>x86_64</string>
</array>
<key>SupportedPlatform</key>
<string>ios</string>
<string>macos</string>
</dict>
</array>
<key>CFBundlePackageType</key>
Expand Down
4 changes: 2 additions & 2 deletions ios/MMKV/Sources/RustMMKV.xcframework/ios-arm64/libmmkv.a
Git LFS file not shown
Git LFS file not shown
Git LFS file not shown
40 changes: 19 additions & 21 deletions src/core/encrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ use std::ops::Deref;
use std::rc::Rc;

use aes::Aes128;
use eax::aead::{generic_array::GenericArray, KeyInit, OsRng, Payload};
use eax::aead::consts::U8;
use eax::aead::rand_core::RngCore;
use eax::aead::stream::{NewStream, StreamBE32, StreamPrimitive};
use eax::aead::{generic_array::GenericArray, KeyInit, OsRng, Payload};
use eax::Eax;

use crate::core::buffer::{Buffer, Decoder, Encoder, Take};
Expand Down Expand Up @@ -67,9 +67,10 @@ impl Encrypt {
return Err(EncryptFailed(String::from("counter overflow")));
}

let result = self.stream.encrypt(
self.position, false, Payload::from(bytes.as_slice()),
).map_err(|e| EncryptFailed(e.to_string()))?;
let result = self
.stream
.encrypt(self.position, false, Payload::from(bytes.as_slice()))
.map_err(|e| EncryptFailed(e.to_string()))?;

self.position += Stream::COUNTER_INCR;
Ok(result)
Expand All @@ -80,9 +81,10 @@ impl Encrypt {
return Err(DecryptFailed(String::from("counter overflow")));
}

let result = self.stream.decrypt(
self.position, false, Payload::from(bytes.as_slice()),
).map_err(|e| DecryptFailed(e.to_string()))?;
let result = self
.stream
.decrypt(self.position, false, Payload::from(bytes.as_slice()))
.map_err(|e| DecryptFailed(e.to_string()))?;

self.position += Stream::COUNTER_INCR;
Ok(result)
Expand Down Expand Up @@ -147,7 +149,9 @@ impl Debug for EncryptBuffer {

impl Debug for Encrypt {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Encrypt").field("nonce", &hex::encode(self.nonce.to_vec())).finish()
f.debug_struct("Encrypt")
.field("nonce", &hex::encode(self.nonce.to_vec()))
.finish()
}
}

Expand All @@ -163,20 +167,14 @@ mod tests {

#[test]
fn test_crypt_buffer() {
let encryptor = Rc::new(
RefCell::new(
Encrypt::new(hex::decode(TEST_KEY).unwrap().try_into().unwrap())
)
);
let encryptor = Rc::new(RefCell::new(Encrypt::new(
hex::decode(TEST_KEY).unwrap().try_into().unwrap(),
)));
let nonce = encryptor.borrow_mut().nonce;
let decryptor = Rc::new(
RefCell::new(
Encrypt::new_with_nonce(
hex::decode(TEST_KEY).unwrap().try_into().unwrap(),
&nonce,
)
)
);
let decryptor = Rc::new(RefCell::new(Encrypt::new_with_nonce(
hex::decode(TEST_KEY).unwrap().try_into().unwrap(),
&nonce,
)));
let buffer = Buffer::from_i32("key1", 1);
let buffer = EncryptBuffer::new_with_buffer(buffer, encryptor.clone());
let bytes = buffer.encode_to_bytes().unwrap();
Expand Down
7 changes: 6 additions & 1 deletion src/core/memory_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ mod tests {
#[test]
fn test_mmap() {
let _ = fs::remove_file("test_mmap");
let file = OpenOptions::new().create(true).write(true).read(true).open("test_mmap").unwrap();
let file = OpenOptions::new()
.create(true)
.write(true)
.read(true)
.open("test_mmap")
.unwrap();
file.set_len(1024).unwrap();
let mut mm = MemoryMap::new(&file);
assert_eq!(mm.len(), 8);
Expand Down
85 changes: 36 additions & 49 deletions src/core/mmkv_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,12 @@ impl MmkvImpl {
let bytes = transform(buffer.clone()).encode_to_bytes()?;
mm.append(bytes).map_err(|e| EncodeFailed(e.to_string()))?;
}
info!(LOG_TAG, "trimmed, len from {} to {}", original_len, mm.len());
info!(
LOG_TAG,
"trimmed, len from {} to {}",
original_len,
mm.len()
);
// the encrypt has been reset, need encode it with new encrypt
if cfg!(feature = "encryption") {
data = buffer.encode_to_bytes()?;
Expand Down Expand Up @@ -228,13 +233,10 @@ impl Display for MmkvImpl {
#[cfg(test)]
mod tests {
use std::path::Path;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::{fs, thread};

use crate::core::buffer::Buffer;
use crate::core::crc::CrcBuffer;
#[cfg(feature = "encryption")]
use crate::core::encrypt::EncryptBuffer;
use crate::core::mmkv_impl::MmkvImpl;
use crate::Error::{InstanceClosed, KeyNotFound, TypeMissMatch};

Expand Down Expand Up @@ -349,56 +351,41 @@ mod tests {
fn test_multi_thread_mmkv() {
let _ = fs::remove_file("test_multi_thread_mmkv");
let _ = fs::remove_file("test_multi_thread_mmkv.meta");
static mut MMKV: OnceLock<MmkvImpl> = OnceLock::new();
let mmkv = MmkvImpl::new(
let mmkv_impl = MmkvImpl::new(
Path::new("test_multi_thread_mmkv"),
4096,
#[cfg(feature = "encryption")]
"88C51C536176AD8A8EE4A06F62EE897E",
);
let mmkv_ptr = Box::into_raw(Box::new(mmkv_impl));
let mmkv = AtomicPtr::new(std::ptr::null_mut());
mmkv.store(mmkv_ptr, Ordering::Release);
let action = |thread_id: &str| {
for i in 0..1000 {
let key = &format!("{thread_id}_key_{i}");
let mmkv = unsafe { mmkv.load(Ordering::Acquire).as_mut().unwrap() };
mmkv.put(key, Buffer::from_i32(key, i)).unwrap();
}
};
thread::scope(|s| {
for i in 0..4 {
s.spawn(move || action(format!("thread_{i}").as_ref()));
}
});
unsafe {
MMKV.set(mmkv).unwrap();
let action = || {
let current_thread = thread::current();
let thread_id = current_thread.id();
for i in 0..500 {
let key = &format!("{:?}_key_{i}", thread_id);
MMKV.get_mut()
.unwrap()
.put(key, Buffer::from_i32(key, i))
.unwrap();
}
};
thread::scope(|s| {
for _ in 0..4 {
s.spawn(action);
}
});
if cfg!(feature = "encryption") {
#[cfg(feature = "encryption")]
{
let encrypt = MMKV.get().unwrap().encrypt.clone();
let count = MMKV
.get()
.unwrap()
.mm
.read()
.unwrap()
.iter(|| EncryptBuffer::new(encrypt.clone()))
.count();
assert_eq!(count, 2000);
}
} else {
let count = MMKV
.get()
.unwrap()
.mm
.read()
.unwrap()
.iter(|| CrcBuffer::new())
.count();
assert_eq!(count, 2000);
};
let _ = Box::from_raw(mmkv.swap(std::ptr::null_mut(), Ordering::Release));
}
let mmkv = MmkvImpl::new(
Path::new("test_multi_thread_mmkv"),
4096,
#[cfg(feature = "encryption")]
"88C51C536176AD8A8EE4A06F62EE897E",
);
for i in 0..4 {
for j in 0..1000 {
let key = &format!("thread_{i}_key_{j}");
assert_eq!(mmkv.get(key).unwrap().decode_i32().unwrap(), j)
}
}
let _ = fs::remove_file("test_multi_thread_mmkv");
let _ = fs::remove_file("test_multi_thread_mmkv.meta");
Expand Down
Loading

0 comments on commit 29512c1

Please sign in to comment.