Fixed a lot of clippy warnings

This commit is contained in:
G2-Games 2023-12-17 02:27:25 -06:00
parent 6c1a66a97d
commit c51d2b700a
6 changed files with 640 additions and 656 deletions

View file

@ -23,6 +23,7 @@ des = "0.8.1"
webusb = "0.5.0"
unicode-jp = "0.4.0"
regex = "1.10.2"
lazy_static = "1.4.0"
[lib]

View file

@ -231,10 +231,7 @@ impl NetMD {
current_attempt += 1;
}
match override_length {
Some(value) => length = value as u16,
None => (),
}
if let Some(value) = override_length { length = value as u16 }
let request = match use_factory_command {
false => 0x81,
@ -253,7 +250,7 @@ impl NetMD {
length as usize
) {
Ok(data) => Ok(data),
Err(error) => return Err(format!("USB error: {:?}", error).into()),
Err(error) => Err(format!("USB error: {:?}", error).into()),
}
}
@ -276,9 +273,8 @@ impl NetMD {
while done < length {
let to_read = std::cmp::min(chunksize, length - done);
done -= to_read;
let mut buffer;
buffer = match self.device_connection.transfer_in(
let buffer = match self.device_connection.transfer_in(
BULK_READ_ENDPOINT,
to_read as usize,
) {
@ -286,13 +282,13 @@ impl NetMD {
Err(error) => return Err(format!("USB error: {:?}", error).into())
};
final_result.extend_from_slice(&mut buffer);
final_result.extend_from_slice(&buffer);
}
Ok(final_result)
}
pub fn write_bulk(&mut self, data: &mut Vec<u8>) -> Result<usize, Box<dyn Error>> {
pub fn write_bulk(&mut self, data: &mut [u8]) -> Result<usize, Box<dyn Error>> {
let written = match self.device_connection.transfer_out(
BULK_WRITE_ENDPOINT,
data

View file

@ -9,10 +9,11 @@ use std::collections::HashMap;
use std::error::Error;
use magic_crypt::{MagicCrypt, SecureBit, MagicCryptTrait, new_magic_crypt};
use hex;
use once_cell::sync::Lazy;
use std::thread::sleep;
use std::time::Duration;
use webusb;
use lazy_static::lazy_static;
#[derive(Copy, Clone)]
enum Action {
@ -38,7 +39,7 @@ pub enum DiscFormat {
#[derive(Clone, Hash, Eq, PartialEq)]
enum WireFormat {
PCM = 0x00,
Pcm = 0x00,
L105kbps = 0x90,
LP2 = 0x94,
LP4 = 0xA8,
@ -47,7 +48,7 @@ enum WireFormat {
impl WireFormat {
fn frame_size(&self) -> u16 {
match self {
WireFormat::PCM => 2048,
WireFormat::Pcm => 2048,
WireFormat::L105kbps => 192,
WireFormat::LP2 => 152,
WireFormat::LP4 => 96,
@ -105,7 +106,7 @@ enum Descriptor {
DiscTitleTD,
AudioUTOC1TD,
AudioUTOC4TD,
DSITD,
Dstid,
AudioContentsTD,
RootTD,
@ -119,7 +120,7 @@ impl Descriptor {
Descriptor::DiscTitleTD => vec![0x10, 0x18, 0x01],
Descriptor::AudioUTOC1TD => vec![0x10, 0x18, 0x02],
Descriptor::AudioUTOC4TD => vec![0x10, 0x18, 0x03],
Descriptor::DSITD => vec![0x10, 0x18, 0x04],
Descriptor::Dstid => vec![0x10, 0x18, 0x04],
Descriptor::AudioContentsTD => vec![0x10, 0x10, 0x01],
Descriptor::RootTD => vec![0x10, 0x10, 0x00],
Descriptor::DiscSubunitIdentifier => vec![0x00],
@ -153,12 +154,14 @@ enum Status {
Interim = 0x0f,
}
const FRAME_SIZE: Lazy<HashMap<WireFormat, usize>> = Lazy::new(|| HashMap::from([
(WireFormat::PCM, 2048),
(WireFormat::LP2, 192),
(WireFormat::L105kbps, 152),
(WireFormat::LP4, 96),
]));
lazy_static!{
static ref FRAME_SIZE: HashMap<WireFormat, usize> = HashMap::from([
(WireFormat::Pcm, 2048),
(WireFormat::LP2, 192),
(WireFormat::L105kbps, 152),
(WireFormat::LP4, 96),
]);
}
impl std::convert::TryFrom<u8> for Status {
type Error = Box<dyn Error>;
@ -207,7 +210,7 @@ impl NetMDInterface {
Ok(NetMDInterface { net_md_device })
}
fn construct_multibyte(&mut self, buffer: &Vec<u8>, n: u8, offset: &mut usize) -> u32 {
fn construct_multibyte(&mut self, buffer: &[u8], n: u8, offset: &mut usize) -> u32 {
let mut output: u32 = 0;
for _ in 0..n as usize {
output <<= 8;
@ -369,7 +372,7 @@ impl NetMDInterface {
while current_attempt < Self::MAX_INTERIM_READ_ATTEMPTS {
data = match self.net_md_device.read_reply(None) {
Ok(reply) => reply,
Err(error) => return Err(error.into()),
Err(error) => return Err(error),
};
let status = match Status::try_from(data[0]) {
@ -819,8 +822,8 @@ impl NetMDInterface {
if title.ends_with(delim) {
let first_entry = title.split(delim).collect::<Vec<&str>>()[0];
if first_entry.starts_with(title_marker) {
title = first_entry[title_marker.len()..].to_string();
if let Some(stripped_title) = first_entry.strip_prefix(title_marker) {
title = stripped_title.to_string();
} else {
title = String::new();
}
@ -842,19 +845,19 @@ impl NetMDInterface {
let mut full_width_group_list = raw_full_title.split("");
for (i, group) in group_list.enumerate() {
if group == "" {
if group.is_empty() {
continue;
}
if group.starts_with("0;") || group.find(";") == None || raw_title.find("//") == None {
if group.starts_with("0;") || group.find(';').is_none() || !raw_title.contains("//") {
continue;
}
let track_range: String = match group.split_once(";") {
let track_range: String = match group.split_once(';') {
Some(string) => string.0.to_string(),
None => return Err("No groups were found".into()),
};
if track_range.len() == 0 {
if track_range.is_empty() {
continue;
}
@ -865,15 +868,15 @@ impl NetMDInterface {
let full_width_group_name = full_width_group_list
.find(|n| n.starts_with(&full_width_range))
.unwrap()
.split_once("")
.split_once('')
.unwrap()
.1;
let mut track_minmax: Vec<&str> = Vec::new();
if track_range.find("-") != None {
track_minmax = track_range.split("-").collect();
if track_range.find('-').is_some() {
track_minmax = track_range.split('-').collect();
} else {
track_minmax.push(&track_range.as_str());
track_minmax.push(track_range.as_str());
}
let (track_min, mut track_max) = (
@ -881,7 +884,7 @@ impl NetMDInterface {
track_minmax[1].parse::<u16>().unwrap(),
);
track_max = u16::min(track_max, track_count as u16);
track_max = u16::min(track_max, track_count);
// TODO: Do some error handling here
assert!(track_min <= track_max);
@ -904,7 +907,7 @@ impl NetMDInterface {
));
}
for i in 0..track_count as u16 {
for i in 0..track_count {
if !track_dict.contains_key(&i) {
result.insert(0, (None, None, Vec::from([i])))
}
@ -1031,23 +1034,18 @@ impl NetMDInterface {
},
};
let old_len: u16;
let new_len = new_title.len();
match self.track_title(track, wchar) {
let old_len: u16 = match self.track_title(track, wchar) {
Ok(current_title) => {
if title == current_title {
return Ok(())
}
old_len = length_after_encoding_to_jis(&current_title) as u16;
length_after_encoding_to_jis(&current_title) as u16
},
Err(error) if error.to_string() == "Rejected" => {
old_len = 0;
},
Err(error) => {
return Err(error);
}
}
Err(error) if error.to_string() == "Rejected" => 0,
Err(error) => return Err(error)
};
self.change_descriptor_state(&descriptor, &DescriptorAction::OpenWrite);
let mut query = format_query(
@ -1114,7 +1112,7 @@ impl NetMDInterface {
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close);
return Ok(res[0].to_vec().unwrap());
Ok(res[0].to_vec().unwrap())
}
/// Gets the length of tracks as a `std::time::Duration` from a set
@ -1327,7 +1325,7 @@ impl NetMDInterface {
let chainlen = keychain.len();
let databytes = 16 + 16 * chainlen + 24;
if depth < 1 || depth > 63 {
if !(1..=63).contains(&depth) {
return Err("Supplied depth is invalid".into());
}
if ekbsignature.len() != 24 {
@ -1395,7 +1393,7 @@ impl NetMDInterface {
return Err("Supplied Session Key length wrong".into());
}
let message = vec![vec![1, 1, 1, 1], contentid, keyenckey].concat();
let message = [vec![1, 1, 1, 1], contentid, keyenckey].concat();
let mc = MagicCrypt::new(
hex_session_key,
@ -1474,19 +1472,17 @@ impl NetMDInterface {
// Sharps are slow
sleep(Duration::from_millis(200));
let mut packet_count = 0;
let mut written_bytes = 0;
for (key, iv, data) in packets {
let mut _written_bytes = 0;
for (packet_count, (key, iv, data)) in packets.into_iter().enumerate(){
let mut binpack;
if packet_count == 0 {
let packed_length: Vec<u8> = pkt_size.to_le_bytes().to_vec();
binpack = vec![vec![0, 0, 0, 0], packed_length, key, iv, data.clone()].concat();
binpack = [vec![0, 0, 0, 0], packed_length, key, iv, data.clone()].concat();
} else {
binpack = data.clone();
}
self.net_md_device.write_bulk(&mut binpack)?;
packet_count += 1;
written_bytes += data.len();
_written_bytes += data.len();
}
reply = self.read_reply(false)?;
@ -1501,8 +1497,8 @@ impl NetMDInterface {
let reply_data = String::from_utf8(mc.decrypt_bytes_to_bytes(&res[1].to_vec().unwrap())?).unwrap().chars().collect::<Vec<char>>();
let part1 = String::from_iter(reply_data.clone()[0..8].into_iter());
let part2 = String::from_iter(reply_data.clone()[12..32].into_iter());
let part1 = String::from_iter(reply_data.clone()[0..8].iter());
let part2 = String::from_iter(reply_data.clone()[12..32].iter());
Ok((res[0].to_i64().unwrap(), part1, part2))
}
@ -1539,7 +1535,7 @@ pub fn retailmac(
) -> Result<(), Box<dyn Error>> {
let subkey_a = key[0..8].to_vec();
let beginning = value[0..value.len() - 8].to_vec();
let end = value[value.len() - 8..].to_vec();
let _end = value[value.len() - 8..].to_vec();
let mc = MagicCrypt::new(
String::from_utf8(subkey_a).unwrap(),
@ -1548,17 +1544,19 @@ pub fn retailmac(
);
let step1 = mc.encrypt_bytes_to_bytes(&beginning);
let iv2 = String::from_utf8(step1);
let _iv2 = String::from_utf8(step1);
Ok(())
}
const DISC_FOR_WIRE: Lazy<HashMap<WireFormat, DiscFormat>> = Lazy::new(|| HashMap::from([
(WireFormat::PCM, DiscFormat::SPStereo),
(WireFormat::LP2, DiscFormat::LP2),
(WireFormat::L105kbps, DiscFormat::LP2),
(WireFormat::LP4, DiscFormat::LP4),
]));
lazy_static!{
static ref DISC_FOR_WIRE: HashMap<WireFormat, DiscFormat> = HashMap::from([
(WireFormat::Pcm, DiscFormat::SPStereo),
(WireFormat::LP2, DiscFormat::LP2),
(WireFormat::L105kbps, DiscFormat::LP2),
(WireFormat::LP4, DiscFormat::LP4),
]);
}
struct EKBOpenSource {
}

File diff suppressed because it is too large Load diff

View file

@ -1,26 +1,23 @@
use crate::netmd::utils;
use once_cell::sync::Lazy;
use lazy_static::lazy_static;
use std::collections::hash_map::HashMap;
use std::error::Error;
/**
%b, w, d, q - explained above (can have endiannes overriden by '>' and '<' operators, f. ex. %>d %<q)
%s - Uint8Array preceded by 2 bytes of length
%x - Uint8Array preceded by 2 bytes of length
%z - Uint8Array preceded by 1 byte of length
%* - raw Uint8Array
%B - BCD-encoded 1-byte number
%W - BCD-encoded 2-byte number
*/
const FORMAT_TYPE_LEN_DICT: Lazy<HashMap<char, i32>> = Lazy::new(|| {
HashMap::from([
lazy_static!{
/// %b, w, d, q - explained above (can have endiannes overriden by '>' and '<' operators, f. ex. %>d %<q)
/// %s - Uint8Array preceded by 2 bytes of length
/// %x - Uint8Array preceded by 2 bytes of length
/// %z - Uint8Array preceded by 1 byte of length
/// %* - raw Uint8Array
/// %B - BCD-encoded 1-byte number
/// %W - BCD-encoded 2-byte number
static ref FORMAT_TYPE_LEN_DICT: HashMap<char, i32> = HashMap::from([
('b', 1), // byte
('w', 2), // word
('d', 4), // doubleword
('q', 8), // quadword
])
});
]);
}
const DEBUG: bool = false;
@ -108,7 +105,7 @@ pub fn format_query(
result.push(0);
}
}
character if character == '*' => {
'*' => {
let mut array_value = arg_stack.next().unwrap().to_vec().unwrap();
result.append(&mut array_value);
}
@ -215,17 +212,17 @@ pub fn scan_query(
character if character == '*' || character == '#' => {
let mut result_buffer: Vec<u8> = Vec::new();
let temp_stack = input_stack.clone();
for entry in temp_stack.take(initial_length as usize) {
for entry in temp_stack.take(initial_length) {
result_buffer.push(entry);
input_stack.next();
}
result.push(QueryValue::Array(result_buffer));
}
character if character == 'B' => {
'B' => {
let v = input_stack.next().unwrap();
result.push(QueryValue::Number(utils::bcd_to_int(v as i32) as i64));
}
character if character == 'W' => {
'W' => {
let v = (input_stack.next().unwrap() as i32) << 8
| input_stack.next().unwrap() as i32;
result.push(QueryValue::Number(utils::bcd_to_int(v) as i64));

View file

@ -2,7 +2,7 @@ use crate::netmd::mappings::{ALLOWED_HW_KANA, MAPPINGS_DE, MAPPINGS_HW, MAPPINGS
use diacritics;
use encoding_rs::SHIFT_JIS;
use regex::Regex;
use std::collections::hash_map::HashMap;
use std::{collections::hash_map::HashMap, error::Error, vec::IntoIter};
use unicode_normalization::UnicodeNormalization;
extern crate kana;
@ -14,7 +14,7 @@ pub fn bcd_to_int(mut bcd: i32) -> i32 {
while bcd != 0 {
let nibble_value = bcd & 0xf;
bcd = bcd >> 4;
bcd >>= 4;
value += nibble_value * i32::pow(10, nibble);
nibble += 1;
}
@ -36,7 +36,7 @@ pub fn int_to_bcd(mut value: i32) -> i32 {
bcd
}
pub fn half_width_to_full_width_range(range: &String) -> String {
pub fn half_width_to_full_width_range(range: &str) -> String {
let mappings: HashMap<char, char> = HashMap::from([
('0', ''),
('1', ''),
@ -60,21 +60,15 @@ pub fn half_width_to_full_width_range(range: &String) -> String {
}
pub fn get_bytes<const S: usize>(
iterator: &mut std::vec::IntoIter<u8>,
) -> Result<[u8; S], Box<dyn std::error::Error>> {
let mut bytes = [0; S];
for i in 0..S {
bytes[i] = match iterator.next() {
Some(byte) => byte,
None => return Err("Could not retrieve byte from file".into()),
};
}
iterator: &mut IntoIter<u8>,
) -> Result<[u8; S], Box<dyn Error>> {
let byte_vec: Vec<u8> = iterator.take(S).collect();
let bytes: [u8; S] = byte_vec.try_into().unwrap();
Ok(bytes)
}
pub fn length_after_encoding_to_jis(string: &String) -> usize {
pub fn length_after_encoding_to_jis(string: &str) -> usize {
let new_string = SHIFT_JIS.encode(string);
new_string.0.len()
@ -83,11 +77,7 @@ pub fn length_after_encoding_to_jis(string: &String) -> usize {
pub fn validate_shift_jis(sjis_string: Vec<u8>) -> bool {
let (_, _, had_errors) = SHIFT_JIS.decode(&sjis_string);
if had_errors {
true
} else {
false
}
had_errors
}
fn check(string: String) -> Option<String> {
@ -124,11 +114,11 @@ pub fn sanitize_half_width_title(mut title: String) -> Vec<u8> {
return agressive_sanitize_title(&title).into();
}
return sjis_string.into();
sjis_string.into()
}
// TODO: This function is bad, probably should do the string sanitization in the frontend
pub fn sanitize_full_width_title(title: &String, just_remap: bool) -> Vec<u8> {
pub fn sanitize_full_width_title(title: &str, just_remap: bool) -> Vec<u8> {
let new_title: String = title
.chars()
.map(|character| {
@ -161,13 +151,13 @@ pub fn sanitize_full_width_title(title: &String, just_remap: bool) -> Vec<u8> {
let sjis_string = SHIFT_JIS.encode(&new_title).0;
if validate_shift_jis(sjis_string.clone().into()) {
return agressive_sanitize_title(&title).into();
return agressive_sanitize_title(title).into();
}
return sjis_string.into();
sjis_string.into()
}
pub fn agressive_sanitize_title(title: &String) -> String {
pub fn agressive_sanitize_title(title: &str) -> String {
let re = Regex::new(r"[^\x00-\x7F]").unwrap();
re.replace_all(
&diacritics::remove_diacritics(title)