Skip to content

Commit

Permalink
perf: optimize some code logic
Browse files Browse the repository at this point in the history
  • Loading branch information
lgou2w committed Oct 25, 2023
1 parent a9ea95a commit cfd4d00
Show file tree
Hide file tree
Showing 9 changed files with 64 additions and 68 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async-trait = "0.1.74"
byteorder = "1.5.0"
form_urlencoded = "1.2.0"
futures = { version = "0.3.28", default-features = false, features = ["std", "async-await"] }
lazy_static = "1.4.0"
once_cell = "1.18.0"
paste = "1.0.14"
reqwest = { version = "0.11.22", features = ["json", "stream"] }
sea-orm = { version = "0.12.4", features = ["sqlx-sqlite", "runtime-tokio", "macros", "runtime-tokio-native-tls"], default-features = false }
Expand Down
26 changes: 12 additions & 14 deletions src-tauri/src/disk_cache/addr.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use byteorder::{ByteOrder, ReadBytesExt};
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use serde::ser::{Serialize, Serializer};
use std::cmp::Ordering;
use std::collections::HashMap;
Expand All @@ -15,19 +15,17 @@ const ADDR_FILE_SELECTOR_OFFSET: u32 = 16;
const ADDR_START_BLOCK_MASK: u32 = 0x0000FFFF;
const ADDR_FILE_NAME_MASK: u32 = 0x0FFFFFFF;

lazy_static! {
static ref FILE_BLOCK_SIZE_MAPPINGS: HashMap<u32, u32> = {
let mut m = HashMap::new();
m.insert(1, 36); // Rankings
m.insert(2, 256); // Block 256
m.insert(3, 1024); // Block 1K
m.insert(4, 4096); // Block 4K
m.insert(5, 8); // Block Files
m.insert(6, 104); // Block Entries
m.insert(7, 48); // Block Evicted
m
};
}
static FILE_BLOCK_SIZE_MAPPINGS: Lazy<HashMap<u32, u32>> = Lazy::new(|| {
let mut m = HashMap::new();
m.insert(1, 36); // Rankings
m.insert(2, 256); // Block 256
m.insert(3, 1024); // Block 1K
m.insert(4, 4096); // Block 4K
m.insert(5, 8); // Block Files
m.insert(6, 104); // Block Entries
m.insert(7, 48); // Block Evicted
m
});

#[derive(Debug, Clone)]
pub struct CacheAddr(u32);
Expand Down
6 changes: 3 additions & 3 deletions src-tauri/src/disk_cache/block_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub struct BlockFileHeader {
pub hints: [i32; 4],
pub updating: i32,
pub user: [i32; 5],
pub allocation_map: Box<[u32; BLOCK_MAX_BLOCKS as usize / 32]>,
pub allocation_map: [u32; BLOCK_MAX_BLOCKS as usize / 32],
}

pub struct BlockFile {
Expand All @@ -49,8 +49,8 @@ impl BlockFileHeader {
let updating = reader.read_i32::<LittleEndian>()?;
let mut user = [0; 5];
reader.read_i32_into::<LittleEndian>(&mut user)?;
let mut allocation_map = Box::new([0; BLOCK_MAX_BLOCKS as usize / 32]);
reader.read_u32_into::<LittleEndian>(&mut *allocation_map)?;
let mut allocation_map = [0; BLOCK_MAX_BLOCKS as usize / 32];
reader.read_u32_into::<LittleEndian>(&mut allocation_map)?;

Ok(Self {
magic,
Expand Down
8 changes: 4 additions & 4 deletions src-tauri/src/disk_cache/entry_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub struct EntryStore {
pub flags: u32,
pub pad: [i32; 4],
pub self_hash: u32,
pub key: Box<[u8; BLOCK_KEY_SIZE as usize]>,
pub key: [u8; BLOCK_KEY_SIZE as usize],
}

impl EntryStore {
Expand All @@ -40,8 +40,8 @@ impl EntryStore {
let mut pad = [0; 4];
reader.read_i32_into::<LittleEndian>(&mut pad)?;
let self_hash = reader.read_u32::<LittleEndian>()?;
let mut key = Box::new([0; BLOCK_KEY_SIZE as usize]);
reader.read_exact(&mut *key)?;
let mut key = [0; BLOCK_KEY_SIZE as usize];
reader.read_exact(&mut key)?;

Ok(Self {
hash,
Expand Down Expand Up @@ -98,7 +98,7 @@ impl EntryStore {
let data = &self.key[0..self.key_len as usize];
Ok(String::from_utf8_lossy(data))
} else {
Ok(String::from_utf8_lossy(&*self.key))
Ok(String::from_utf8_lossy(&self.key))
}
}

Expand Down
6 changes: 3 additions & 3 deletions src-tauri/src/disk_cache/index_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub struct IndexFileHeader {
pub crash: i32,
pub experiment: i32,
pub create_time: u64,
pub pad: Box<[i32; 52]>,
pub pad: [i32; 52],
pub lru: LruData,
}

Expand Down Expand Up @@ -90,8 +90,8 @@ impl IndexFileHeader {
let crash = reader.read_i32::<LittleEndian>()?;
let experiment = reader.read_i32::<LittleEndian>()?;
let create_time = reader.read_u64::<LittleEndian>()?;
let mut pad = Box::new([0; 52]);
reader.read_i32_into::<LittleEndian>(&mut *pad)?;
let mut pad = [0; 52];
reader.read_i32_into::<LittleEndian>(&mut pad)?;
let lru = LruData::from_reader(reader)?;

Ok(Self {
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/src/gacha/srgf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ pub fn convert_srgf_to_offical(srgf: &mut SRGF) -> Result<Vec<StarRailGachaRecor
let owned_lang = &srgf.info.lang;

let mut result: Vec<StarRailGachaRecord> = Vec::with_capacity(srgf.list.len());
for item in srgf.list.iter_mut() {
for item in &mut srgf.list {
let record = StarRailGachaRecord::try_from(&*item, owned_uid, owned_lang)?;
result.push(record);
}
Expand All @@ -138,7 +138,7 @@ pub fn convert_srgf_to_offical(srgf: &mut SRGF) -> Result<Vec<StarRailGachaRecor

pub fn convert_offical_to_srgf(records: &[StarRailGachaRecord]) -> Result<SRGFList> {
let mut result: SRGFList = Vec::with_capacity(records.len());
for record in records.iter() {
for record in records {
let item = SRGFListItem::try_from(record)?;
result.push(item);
}
Expand Down
46 changes: 22 additions & 24 deletions src-tauri/src/gacha/uigf.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::constants::{ID, VERSION};
use crate::error::{Error, Result};
use crate::gacha::GenshinGachaRecord;
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Write};
Expand Down Expand Up @@ -82,25 +82,23 @@ impl UIGF {

// Convert

lazy_static! {
/*
* Gacha Type (Official) | Gacha Type (UIGF)
* 100 | 100
* 200 | 200
* 301 | 301
* 400 | 301
* 302 | 302
*/
pub static ref GACHA_TYPE_UIGF_MAPPINGS: HashMap<String, String> = {
let mut m = HashMap::with_capacity(5);
m.insert(String::from("100"), String::from("100"));
m.insert(String::from("200"), String::from("200"));
m.insert(String::from("301"), String::from("301"));
m.insert(String::from("400"), String::from("301")); // 400 -> 301
m.insert(String::from("302"), String::from("302"));
m
};
}
/*
* Gacha Type (Official) | Gacha Type (UIGF)
* 100 | 100
* 200 | 200
* 301 | 301
* 400 | 301
* 302 | 302
*/
pub static GACHA_TYPE_UIGF_MAPPINGS: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
let mut m = HashMap::with_capacity(5);
m.insert("100", "100");
m.insert("200", "200");
m.insert("301", "301");
m.insert("400", "301"); // 400 -> 301
m.insert("302", "302");
m
});

// UIGF -> Official GenshinGachaRecord
impl TryFrom<&UIGFListItem> for GenshinGachaRecord {
Expand Down Expand Up @@ -141,7 +139,7 @@ impl TryFrom<&GenshinGachaRecord> for UIGFListItem {

fn try_from(value: &GenshinGachaRecord) -> std::result::Result<Self, Self::Error> {
let uigf_gacha_type = GACHA_TYPE_UIGF_MAPPINGS
.get(&value.gacha_type)
.get(value.gacha_type.as_str())
.ok_or_else(|| Error::UIGFOrSRGFInvalidField(format!("gacha_type={}", value.gacha_type)))?;

Ok(Self {
Expand All @@ -155,7 +153,7 @@ impl TryFrom<&GenshinGachaRecord> for UIGFListItem {
lang: Some(value.lang.clone()),
item_type: value.item_type.clone(),
rank_type: Some(value.rank_type.clone()),
uigf_gacha_type: uigf_gacha_type.to_owned(),
uigf_gacha_type: uigf_gacha_type.to_string(),
})
}
}
Expand All @@ -165,7 +163,7 @@ pub fn convert_uigf_to_offical(uigf: &mut UIGF) -> Result<Vec<GenshinGachaRecord
let owned_lang = &uigf.info.lang;

let mut result: Vec<GenshinGachaRecord> = Vec::with_capacity(uigf.list.len());
for item in uigf.list.iter_mut() {
for item in &mut uigf.list {
if item.uid.is_none() {
item.uid.replace(owned_uid.clone());
}
Expand All @@ -182,7 +180,7 @@ pub fn convert_uigf_to_offical(uigf: &mut UIGF) -> Result<Vec<GenshinGachaRecord

pub fn convert_offical_to_uigf(records: &[GenshinGachaRecord]) -> Result<UIGFList> {
let mut result: UIGFList = Vec::with_capacity(records.len());
for record in records.iter() {
for record in records {
let item = UIGFListItem::try_from(record)?;
result.push(item);
}
Expand Down
32 changes: 16 additions & 16 deletions src-tauri/src/gacha/utilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::constants;
use crate::disk_cache::{BlockFile, EntryStore, IndexFile};
use crate::error::{Error, Result};
use crate::storage::entity_account::AccountFacet;
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use reqwest::Client as Reqwest;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -65,6 +65,7 @@ pub(super) fn lookup_path_line_from_keyword<P: AsRef<Path>>(

let file = File::open(path)?;
let reader = BufReader::new(file);
let keyword_len = keyword.len();

for line in reader.lines().map(|l| l.unwrap()) {
if !line.contains(keyword) {
Expand All @@ -73,7 +74,7 @@ pub(super) fn lookup_path_line_from_keyword<P: AsRef<Path>>(

if let Some(colon) = line.rfind(':') {
if let Some(end) = line.find(keyword) {
let path = &line[colon - 1..end + keyword.len()];
let path = &line[colon - 1..end + keyword_len];
return Ok(Some(Path::new(path).to_path_buf()));
}
}
Expand All @@ -92,15 +93,16 @@ mod web_caches {
major: u8,
minor: u8,
patch: u8,
build: u8,
build: Option<u8>,
}

impl WebCachesVersion {
pub fn version(&self) -> String {
format!(
"{}.{}.{}.{}",
self.major, self.minor, self.patch, self.build
)
if let Some(build) = self.build {
format!("{}.{}.{}.{}", self.major, self.minor, self.patch, build)
} else {
format!("{}.{}.{}", self.major, self.minor, self.patch)
}
}
}

Expand All @@ -120,7 +122,7 @@ mod web_caches {
major: major.parse()?,
minor: minor.parse()?,
patch: patch.parse()?,
build: build_opt.unwrap_or("0").parse()?,
build: build_opt.map(|opt| opt.parse::<u8>()).transpose()?,
}),
_ => Err(Error::WebCaches),
}
Expand Down Expand Up @@ -205,10 +207,10 @@ pub(super) fn lookup_gacha_urls_from_endpoint<P: AsRef<Path>>(
}

// These url start with '1/0/', only get the later part
let url = if url.starts_with("1/0/") {
url[4..].to_string()
let url = if let Some(stripped) = url.strip_prefix("1/0/") {
stripped
} else {
url.to_string()
&url
};

// Convert creation time
Expand All @@ -225,9 +227,9 @@ pub(super) fn lookup_gacha_urls_from_endpoint<P: AsRef<Path>>(
}

result.push(GachaUrl {
addr: addr.into(),
addr: u32::from(addr),
creation_time,
value: url,
value: url.to_owned(),
})
}

Expand Down Expand Up @@ -305,9 +307,7 @@ pub(super) async fn fetch_gacha_records<T: Sized + DeserializeOwned>(
// key: facet + uid + addr
// value: GachaUrl

lazy_static! {
static ref GACHA_URL_CACHED: Mutex<HashMap<String, GachaUrl>> = Default::default();
}
static GACHA_URL_CACHED: Lazy<Mutex<HashMap<String, GachaUrl>>> = Lazy::new(Default::default);

pub(crate) async fn find_gacha_url_and_validate_consistency<Record, Fetcher>(
fetcher: &Fetcher,
Expand Down

0 comments on commit cfd4d00

Please sign in to comment.