Compare commits

...

3 commits

Author SHA1 Message Date
278ba2e8bd Ported to [yusb](https://github.com/fpagliughi/yusb) 2023-12-17 02:43:41 -06:00
c51d2b700a Fixed a lot of clippy warnings 2023-12-17 02:27:25 -06:00
6c1a66a97d Cleanup 2023-12-17 01:59:10 -06:00
6 changed files with 754 additions and 708 deletions

View file

@ -17,12 +17,14 @@ encoding_rs = "0.8.33"
magic-crypt = "3.1.12" magic-crypt = "3.1.12"
nofmt = "1.0.0" nofmt = "1.0.0"
once_cell = "1.18.0" once_cell = "1.18.0"
regex = "1.9.5"
unicode-jp = "0.4.0"
unicode-normalization = "0.1.22" unicode-normalization = "0.1.22"
hex = "0.4.3" hex = "0.4.3"
des = "0.8.1" des = "0.8.1"
webusb = "0.5.0" unicode-jp = "0.4.0"
regex = "1.10.2"
lazy_static = "1.4.0"
yusb = "0.1.2"
[lib] [lib]
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]

View file

@ -1,20 +1,20 @@
use nofmt; use nofmt;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use webusb::{UsbDevice, UsbRecipient, UsbRequestType, UsbControlTransferParameters};
use std::error::Error; use std::error::Error;
use yusb::{Device, DeviceHandle, Direction, Recipient, RequestType};
const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::new(9999999, 0); const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::new(9999999, 0);
const STANDARD_SEND: u8 =
yusb::request_type(Direction::Out, RequestType::Vendor, Recipient::Interface);
const STANDARD_RECV: u8 =
yusb::request_type(Direction::In, RequestType::Vendor, Recipient::Interface);
const BULK_WRITE_ENDPOINT: u8 = 0x02; const BULK_WRITE_ENDPOINT: u8 = 0x02;
const BULK_READ_ENDPOINT: u8 = 0x81; const BULK_READ_ENDPOINT: u8 = 0x81;
pub const CHUNKSIZE: u32 = 0x10000; pub static DEVICE_IDS: Lazy<Box<[DeviceId]>> = Lazy::new(|| {
nofmt::pls! {Box::new(
// TODO: I think this sucks, figure out a better way [
pub static DEVICE_IDS: Lazy<Vec<DeviceId>> = Lazy::new(|| {
nofmt::pls! {
Vec::from([
DeviceId {vendor_id: 0x04dd, product_id: 0x7202, name: Some(String::from("Sharp IM-MT899H"))}, DeviceId {vendor_id: 0x04dd, product_id: 0x7202, name: Some(String::from("Sharp IM-MT899H"))},
DeviceId {vendor_id: 0x04dd, product_id: 0x9013, name: Some(String::from("Sharp IM-DR400"))}, DeviceId {vendor_id: 0x04dd, product_id: 0x9013, name: Some(String::from("Sharp IM-DR400"))},
DeviceId {vendor_id: 0x04dd, product_id: 0x9014, name: Some(String::from("Sharp IM-DR80"))}, DeviceId {vendor_id: 0x04dd, product_id: 0x9014, name: Some(String::from("Sharp IM-DR80"))},
@ -65,6 +65,7 @@ pub static DEVICE_IDS: Lazy<Vec<DeviceId>> = Lazy::new(|| {
} }
}); });
/// The current status of the Minidisc device
pub enum Status { pub enum Status {
Ready, Ready,
Playing, Playing,
@ -76,14 +77,16 @@ pub enum Status {
DiscBlank, DiscBlank,
} }
/// The ID of a device, including the name
pub struct DeviceId { pub struct DeviceId {
vendor_id: u16, vendor_id: u16,
product_id: u16, product_id: u16,
name: Option<String>, name: Option<String>,
} }
/// A connection to a NetMD device
pub struct NetMD { pub struct NetMD {
device_connection: UsbDevice, device: DeviceHandle,
model: DeviceId, model: DeviceId,
status: Option<Status>, status: Option<Status>,
} }
@ -92,12 +95,12 @@ impl NetMD {
const READ_REPLY_RETRY_INTERVAL: u32 = 10; const READ_REPLY_RETRY_INTERVAL: u32 = 10;
/// Creates a new `NetMD` struct /// Creates a new `NetMD` struct
pub fn new( pub fn new(device: Device) -> Result<Self, Box<dyn Error>> {
device: UsbDevice, let descriptor = device.device_descriptor()?;
) -> Result<Self, Box<dyn Error>> {
let mut model = DeviceId { let mut model = DeviceId {
vendor_id: device.vendor_id, vendor_id: descriptor.vendor_id(),
product_id: device.product_id, product_id: descriptor.product_id(),
name: None, name: None,
}; };
@ -116,7 +119,7 @@ impl NetMD {
} }
Ok(Self { Ok(Self {
device_connection: device, device: device.open()?,
model, model,
status: None, status: None,
}) })
@ -140,18 +143,19 @@ impl NetMD {
/// Poll the device to get either the result /// Poll the device to get either the result
/// of the previous command, or the status /// of the previous command, or the status
pub fn poll(&mut self) -> Result<(u16, [u8; 4]), Box<dyn Error>> { pub fn poll(&mut self) -> Result<(u16, [u8; 4]), Box<dyn Error>> {
let poll_result: [u8; 4] = match self.device_connection.control_transfer_in( // Create an array to store the result of the poll
UsbControlTransferParameters { let mut poll_result = [0u8; 4];
request_type: UsbRequestType::Vendor,
recipient: UsbRecipient::Interface, let _status = match self.device.read_control(
request: 0x01, STANDARD_RECV,
value: 0, 0x01,
index: 0, 0,
}, 0,
4 &mut poll_result,
DEFAULT_TIMEOUT,
) { ) {
Ok(result) => result.try_into().unwrap(), Ok(size) => size,
Err(error) => return Err(format!("USB error: {:?}", error).into()), Err(error) => return Err(error.into()),
}; };
let length_bytes = [poll_result[2], poll_result[3]]; let length_bytes = [poll_result[2], poll_result[3]];
@ -186,18 +190,12 @@ impl NetMD {
true => 0xff, true => 0xff,
}; };
match self.device_connection.control_transfer_out( match self
UsbControlTransferParameters { .device
request_type: UsbRequestType::Vendor, .write_control(STANDARD_SEND, request, 0, 0, &command, DEFAULT_TIMEOUT)
recipient: UsbRecipient::Interface, {
request,
value: 0,
index: 0,
},
&command
) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(error) => Err(format!("USB error: {:?}", error).into()), Err(error) => Err(error.into()),
} }
} }
@ -231,9 +229,8 @@ impl NetMD {
current_attempt += 1; current_attempt += 1;
} }
match override_length { if let Some(value) = override_length {
Some(value) => length = value as u16, length = value as u16
None => (),
} }
let request = match use_factory_command { let request = match use_factory_command {
@ -242,18 +239,15 @@ impl NetMD {
}; };
// Create a buffer to fill with the result // Create a buffer to fill with the result
match self.device_connection.control_transfer_in( let mut buf: Vec<u8> = vec![0; length as usize];
UsbControlTransferParameters {
request_type: UsbRequestType::Vendor, // Create a buffer to fill with the result
recipient: UsbRecipient::Interface, match self
request, .device
value: 0, .read_control(STANDARD_RECV, request, 0, 0, &mut buf, DEFAULT_TIMEOUT)
index: 0, {
}, Ok(_) => Ok(buf),
length as usize Err(error) => Err(error.into()),
) {
Ok(data) => Ok(data),
Err(error) => return Err(format!("USB error: {:?}", error).into()),
} }
} }
@ -276,30 +270,26 @@ impl NetMD {
while done < length { while done < length {
let to_read = std::cmp::min(chunksize, length - done); let to_read = std::cmp::min(chunksize, length - done);
done -= to_read; done -= to_read;
let mut buffer; let mut buffer: Vec<u8> = vec![0; to_read as usize];
buffer = match self.device_connection.transfer_in( match self
BULK_READ_ENDPOINT, .device
to_read as usize, .read_bulk(BULK_READ_ENDPOINT, &mut buffer, DEFAULT_TIMEOUT)
) { {
Ok(result) => result, Ok(result) => result,
Err(error) => return Err(format!("USB error: {:?}", error).into()) 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) 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( let written = self
BULK_WRITE_ENDPOINT, .device
data .write_bulk(BULK_WRITE_ENDPOINT, data, DEFAULT_TIMEOUT)?;
) {
Ok(output) => output,
Err(error) => return Err(format!("USB error: {:?}", error).into())
};
Ok(written) Ok(written)
} }

View file

@ -9,9 +9,11 @@ use std::collections::HashMap;
use std::error::Error; use std::error::Error;
use magic_crypt::{MagicCrypt, SecureBit, MagicCryptTrait, new_magic_crypt}; use magic_crypt::{MagicCrypt, SecureBit, MagicCryptTrait, new_magic_crypt};
use hex; use hex;
use std::thread::sleep; use std::thread::sleep;
use std::time::Duration; use std::time::Duration;
use webusb; use yusb;
use lazy_static::lazy_static;
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
enum Action { enum Action {
@ -35,8 +37,9 @@ pub enum DiscFormat {
SPStereo = 6, SPStereo = 6,
} }
#[derive(Clone, Hash, Eq, PartialEq)]
enum WireFormat { enum WireFormat {
PCM = 0x00, Pcm = 0x00,
L105kbps = 0x90, L105kbps = 0x90,
LP2 = 0x94, LP2 = 0x94,
LP4 = 0xA8, LP4 = 0xA8,
@ -45,7 +48,7 @@ enum WireFormat {
impl WireFormat { impl WireFormat {
fn frame_size(&self) -> u16 { fn frame_size(&self) -> u16 {
match self { match self {
WireFormat::PCM => 2048, WireFormat::Pcm => 2048,
WireFormat::L105kbps => 192, WireFormat::L105kbps => 192,
WireFormat::LP2 => 152, WireFormat::LP2 => 152,
WireFormat::LP4 => 96, WireFormat::LP4 => 96,
@ -103,7 +106,7 @@ enum Descriptor {
DiscTitleTD, DiscTitleTD,
AudioUTOC1TD, AudioUTOC1TD,
AudioUTOC4TD, AudioUTOC4TD,
DSITD, Dstid,
AudioContentsTD, AudioContentsTD,
RootTD, RootTD,
@ -117,7 +120,7 @@ impl Descriptor {
Descriptor::DiscTitleTD => vec![0x10, 0x18, 0x01], Descriptor::DiscTitleTD => vec![0x10, 0x18, 0x01],
Descriptor::AudioUTOC1TD => vec![0x10, 0x18, 0x02], Descriptor::AudioUTOC1TD => vec![0x10, 0x18, 0x02],
Descriptor::AudioUTOC4TD => vec![0x10, 0x18, 0x03], 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::AudioContentsTD => vec![0x10, 0x10, 0x01],
Descriptor::RootTD => vec![0x10, 0x10, 0x00], Descriptor::RootTD => vec![0x10, 0x10, 0x00],
Descriptor::DiscSubunitIdentifier => vec![0x00], Descriptor::DiscSubunitIdentifier => vec![0x00],
@ -151,6 +154,15 @@ enum Status {
Interim = 0x0f, Interim = 0x0f,
} }
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 { impl std::convert::TryFrom<u8> for Status {
type Error = Box<dyn Error>; type Error = Box<dyn Error>;
@ -192,13 +204,13 @@ impl NetMDInterface {
const INTERIM_RESPONSE_RETRY_INTERVAL: u32 = 100; const INTERIM_RESPONSE_RETRY_INTERVAL: u32 = 100;
pub fn new( pub fn new(
device: webusb::UsbDevice, device: yusb::Device,
) -> Result<Self, Box<dyn Error>> { ) -> Result<Self, Box<dyn Error>> {
let net_md_device = base::NetMD::new(device).unwrap(); let net_md_device = base::NetMD::new(device).unwrap();
Ok(NetMDInterface { net_md_device }) 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; let mut output: u32 = 0;
for _ in 0..n as usize { for _ in 0..n as usize {
output <<= 8; output <<= 8;
@ -360,7 +372,7 @@ impl NetMDInterface {
while current_attempt < Self::MAX_INTERIM_READ_ATTEMPTS { while current_attempt < Self::MAX_INTERIM_READ_ATTEMPTS {
data = match self.net_md_device.read_reply(None) { data = match self.net_md_device.read_reply(None) {
Ok(reply) => reply, Ok(reply) => reply,
Err(error) => return Err(error.into()), Err(error) => return Err(error),
}; };
let status = match Status::try_from(data[0]) { let status = match Status::try_from(data[0]) {
@ -810,8 +822,8 @@ impl NetMDInterface {
if title.ends_with(delim) { if title.ends_with(delim) {
let first_entry = title.split(delim).collect::<Vec<&str>>()[0]; let first_entry = title.split(delim).collect::<Vec<&str>>()[0];
if first_entry.starts_with(title_marker) { if let Some(stripped_title) = first_entry.strip_prefix(title_marker) {
title = first_entry[title_marker.len()..].to_string(); title = stripped_title.to_string();
} else { } else {
title = String::new(); title = String::new();
} }
@ -833,19 +845,19 @@ impl NetMDInterface {
let mut full_width_group_list = raw_full_title.split(""); let mut full_width_group_list = raw_full_title.split("");
for (i, group) in group_list.enumerate() { for (i, group) in group_list.enumerate() {
if group == "" { if group.is_empty() {
continue; 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; continue;
} }
let track_range: String = match group.split_once(";") { let track_range: String = match group.split_once(';') {
Some(string) => string.0.to_string(), Some(string) => string.0.to_string(),
None => return Err("No groups were found".into()), None => return Err("No groups were found".into()),
}; };
if track_range.len() == 0 { if track_range.is_empty() {
continue; continue;
} }
@ -856,15 +868,15 @@ impl NetMDInterface {
let full_width_group_name = full_width_group_list let full_width_group_name = full_width_group_list
.find(|n| n.starts_with(&full_width_range)) .find(|n| n.starts_with(&full_width_range))
.unwrap() .unwrap()
.split_once("") .split_once('')
.unwrap() .unwrap()
.1; .1;
let mut track_minmax: Vec<&str> = Vec::new(); let mut track_minmax: Vec<&str> = Vec::new();
if track_range.find("-") != None { if track_range.find('-').is_some() {
track_minmax = track_range.split("-").collect(); track_minmax = track_range.split('-').collect();
} else { } else {
track_minmax.push(&track_range.as_str()); track_minmax.push(track_range.as_str());
} }
let (track_min, mut track_max) = ( let (track_min, mut track_max) = (
@ -872,7 +884,7 @@ impl NetMDInterface {
track_minmax[1].parse::<u16>().unwrap(), 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 // TODO: Do some error handling here
assert!(track_min <= track_max); assert!(track_min <= track_max);
@ -895,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) { if !track_dict.contains_key(&i) {
result.insert(0, (None, None, Vec::from([i]))) result.insert(0, (None, None, Vec::from([i])))
} }
@ -1022,23 +1034,18 @@ impl NetMDInterface {
}, },
}; };
let old_len: u16;
let new_len = new_title.len(); 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) => { Ok(current_title) => {
if title == current_title { if title == current_title {
return Ok(()) 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" => { Err(error) if error.to_string() == "Rejected" => 0,
old_len = 0; Err(error) => return Err(error)
}, };
Err(error) => {
return Err(error);
}
}
self.change_descriptor_state(&descriptor, &DescriptorAction::OpenWrite); self.change_descriptor_state(&descriptor, &DescriptorAction::OpenWrite);
let mut query = format_query( let mut query = format_query(
@ -1105,7 +1112,7 @@ impl NetMDInterface {
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close); 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 /// Gets the length of tracks as a `std::time::Duration` from a set
@ -1318,7 +1325,7 @@ impl NetMDInterface {
let chainlen = keychain.len(); let chainlen = keychain.len();
let databytes = 16 + 16 * chainlen + 24; let databytes = 16 + 16 * chainlen + 24;
if depth < 1 || depth > 63 { if !(1..=63).contains(&depth) {
return Err("Supplied depth is invalid".into()); return Err("Supplied depth is invalid".into());
} }
if ekbsignature.len() != 24 { if ekbsignature.len() != 24 {
@ -1386,7 +1393,7 @@ impl NetMDInterface {
return Err("Supplied Session Key length wrong".into()); 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( let mc = MagicCrypt::new(
hex_session_key, hex_session_key,
@ -1465,19 +1472,17 @@ impl NetMDInterface {
// Sharps are slow // Sharps are slow
sleep(Duration::from_millis(200)); sleep(Duration::from_millis(200));
let mut packet_count = 0; let mut _written_bytes = 0;
let mut written_bytes = 0; for (packet_count, (key, iv, data)) in packets.into_iter().enumerate(){
for (key, iv, data) in packets {
let mut binpack; let mut binpack;
if packet_count == 0 { if packet_count == 0 {
let packed_length: Vec<u8> = pkt_size.to_le_bytes().to_vec(); 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 { } else {
binpack = data.clone(); binpack = data.clone();
} }
self.net_md_device.write_bulk(&mut binpack)?; self.net_md_device.write_bulk(&mut binpack)?;
packet_count += 1; _written_bytes += data.len();
written_bytes += data.len();
} }
reply = self.read_reply(false)?; reply = self.read_reply(false)?;
@ -1492,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 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 part1 = String::from_iter(reply_data.clone()[0..8].iter());
let part2 = String::from_iter(reply_data.clone()[12..32].into_iter()); let part2 = String::from_iter(reply_data.clone()[12..32].iter());
Ok((res[0].to_i64().unwrap(), part1, part2)) Ok((res[0].to_i64().unwrap(), part1, part2))
} }
@ -1530,7 +1535,7 @@ pub fn retailmac(
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
let subkey_a = key[0..8].to_vec(); let subkey_a = key[0..8].to_vec();
let beginning = value[0..value.len() - 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( let mc = MagicCrypt::new(
String::from_utf8(subkey_a).unwrap(), String::from_utf8(subkey_a).unwrap(),
@ -1539,13 +1544,21 @@ pub fn retailmac(
); );
let step1 = mc.encrypt_bytes_to_bytes(&beginning); let step1 = mc.encrypt_bytes_to_bytes(&beginning);
let iv2 = String::from_utf8(step1); let _iv2 = String::from_utf8(step1);
Ok(()) Ok(())
} }
struct EKBOpenSource { 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 {
} }
impl EKBOpenSource { impl EKBOpenSource {
@ -1577,14 +1590,66 @@ impl EKBOpenSource {
*/ */
} }
#[derive(Clone)]
struct MDTrack { struct MDTrack {
title: String, title: String,
format: WireFormat, format: WireFormat,
data: Vec<u8>, data: Vec<u8>,
chunk_size: i32, chunk_size: i32,
full_width_title: Option<String>, full_width_title: Option<String>,
encrypt_packets_iterator: EncryptPacketsIterator
}
#[derive(Clone)]
struct EncryptPacketsIterator {
kek: Vec<u8>,
frame_size: i32,
data: Vec<u8>,
chunk_size: i32
} }
impl MDTrack { impl MDTrack {
pub fn full_width_title(self) -> String {
self.full_width_title.unwrap_or("".to_string())
}
pub fn title(&self) -> String {
self.title.clone()
}
pub fn data_format(&self) -> WireFormat {
self.format.clone()
}
pub fn frame_count(&self) -> usize {
self.total_size() / self.frame_size()
}
pub fn frame_size(&self) -> usize {
*FRAME_SIZE.get(&self.format).unwrap()
}
pub fn chunk_size(self) -> i32 {
self.chunk_size
}
pub fn total_size(&self) -> usize {
let frame_size = self.frame_size();
let mut len = self.data.len();
if len % frame_size != 0 {
len = len + (frame_size - (len % frame_size));
}
len
}
pub fn content_id() -> [u8; 20] {
[0x01, 0x0f, 0x50, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x48,
0xa2, 0x8d, 0x3e, 0x1a, 0x3b, 0x0c, 0x44, 0xaf, 0x2f, 0xa0]
}
pub fn get_kek() -> [u8; 8] {
[0x14, 0xe3, 0x83, 0x4e, 0xe2, 0xd3, 0xcc, 0xa5]
}
} }

View file

@ -1,7 +1,8 @@
use once_cell::sync::Lazy; use lazy_static::lazy_static;
use std::collections::HashMap; use std::collections::HashMap;
pub const MAPPINGS_JP: Lazy<HashMap<String, String>> = Lazy::new(|| {[ lazy_static! {
pub static ref MAPPINGS_JP: HashMap<String, String> = HashMap::from([
("!".to_string(), "".to_string()), ("!".to_string(), "".to_string()),
("\"".to_string(), "".to_string()), ("\"".to_string(), "".to_string()),
("#".to_string(), "".to_string()), ("#".to_string(), "".to_string()),
@ -191,9 +192,9 @@ pub const MAPPINGS_JP: Lazy<HashMap<String, String>> = Lazy::new(|| {[
("".to_string(), "".to_string()), ("".to_string(), "".to_string()),
("".to_string(), "".to_string()), ("".to_string(), "".to_string()),
("".to_string(), "".to_string()) ("".to_string(), "".to_string())
].into_iter().collect()}); ]);
pub const MAPPINGS_RU: Lazy<HashMap<String, String>> = Lazy::new(|| {[ pub static ref MAPPINGS_RU: HashMap<String, String> = HashMap::from([
("а".to_string(), "a".to_string()), ("а".to_string(), "a".to_string()),
("б".to_string(), "b".to_string()), ("б".to_string(), "b".to_string()),
("в".to_string(), "v".to_string()), ("в".to_string(), "v".to_string()),
@ -260,9 +261,9 @@ pub const MAPPINGS_RU: Lazy<HashMap<String, String>> = Lazy::new(|| {[
("Э".to_string(), "E".to_string()), ("Э".to_string(), "E".to_string()),
("Ю".to_string(), "Iu".to_string()), ("Ю".to_string(), "Iu".to_string()),
("Я".to_string(), "Ia".to_string()) ("Я".to_string(), "Ia".to_string())
].into_iter().collect()}); ]);
pub const MAPPINGS_DE: Lazy<HashMap<String, String>> = Lazy::new(|| {[ pub static ref MAPPINGS_DE: HashMap<String, String> = HashMap::from([
("Ä".to_string(), "Ae".to_string()), ("Ä".to_string(), "Ae".to_string()),
("ä".to_string(), "ae".to_string()), ("ä".to_string(), "ae".to_string()),
("Ö".to_string(), "Oe".to_string()), ("Ö".to_string(), "Oe".to_string()),
@ -270,9 +271,9 @@ pub const MAPPINGS_DE: Lazy<HashMap<String, String>> = Lazy::new(|| {[
("Ü".to_string(), "Ue".to_string()), ("Ü".to_string(), "Ue".to_string()),
("ü".to_string(), "ue".to_string()), ("ü".to_string(), "ue".to_string()),
("ß".to_string(), "ss".to_string()) ("ß".to_string(), "ss".to_string())
].into_iter().collect()}); ]);
pub const MAPPINGS_HW: Lazy<HashMap<String, String>> = Lazy::new(|| {[ pub static ref MAPPINGS_HW: HashMap<String, String> = HashMap::from([
("".to_string(),"-".to_string()), ("".to_string(),"-".to_string()),
("".to_string(),"-".to_string()), ("".to_string(),"-".to_string()),
("".to_string(),"".to_string()), ("".to_string(),"".to_string()),
@ -551,6 +552,7 @@ pub const MAPPINGS_HW: Lazy<HashMap<String, String>> = Lazy::new(|| {[
("".to_string(),"ヴ".to_string()), ("".to_string(),"ヴ".to_string()),
("".to_string(),"".to_string()), ("".to_string(),"".to_string()),
("".to_string(),"".to_string()), ("".to_string(),"".to_string()),
].into_iter().collect()}); ]);
pub const ALLOWED_HW_KANA: Lazy<Vec<String>> = Lazy::new(|| {MAPPINGS_HW.values().cloned().collect()}); pub static ref ALLOWED_HW_KANA: Vec<String> = MAPPINGS_HW.values().cloned().collect();
}

View file

@ -1,26 +1,23 @@
use crate::netmd::utils; use crate::netmd::utils;
use once_cell::sync::Lazy; use lazy_static::lazy_static;
use std::collections::hash_map::HashMap; use std::collections::hash_map::HashMap;
use std::error::Error; use std::error::Error;
/** lazy_static!{
%b, w, d, q - explained above (can have endiannes overriden by '>' and '<' operators, f. ex. %>d %<q) /// %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 /// %s - Uint8Array preceded by 2 bytes of length
%x - Uint8Array preceded by 2 bytes of length /// %x - Uint8Array preceded by 2 bytes of length
%z - Uint8Array preceded by 1 byte of length /// %z - Uint8Array preceded by 1 byte of length
%* - raw Uint8Array /// %* - raw Uint8Array
%B - BCD-encoded 1-byte number /// %B - BCD-encoded 1-byte number
%W - BCD-encoded 2-byte number /// %W - BCD-encoded 2-byte number
*/ static ref FORMAT_TYPE_LEN_DICT: HashMap<char, i32> = HashMap::from([
const FORMAT_TYPE_LEN_DICT: Lazy<HashMap<char, i32>> = Lazy::new(|| {
HashMap::from([
('b', 1), // byte ('b', 1), // byte
('w', 2), // word ('w', 2), // word
('d', 4), // doubleword ('d', 4), // doubleword
('q', 8), // quadword ('q', 8), // quadword
]) ]);
}); }
const DEBUG: bool = false; const DEBUG: bool = false;
@ -108,7 +105,7 @@ pub fn format_query(
result.push(0); result.push(0);
} }
} }
character if character == '*' => { '*' => {
let mut array_value = arg_stack.next().unwrap().to_vec().unwrap(); let mut array_value = arg_stack.next().unwrap().to_vec().unwrap();
result.append(&mut array_value); result.append(&mut array_value);
} }
@ -215,17 +212,17 @@ pub fn scan_query(
character if character == '*' || character == '#' => { character if character == '*' || character == '#' => {
let mut result_buffer: Vec<u8> = Vec::new(); let mut result_buffer: Vec<u8> = Vec::new();
let temp_stack = input_stack.clone(); 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); result_buffer.push(entry);
input_stack.next(); input_stack.next();
} }
result.push(QueryValue::Array(result_buffer)); result.push(QueryValue::Array(result_buffer));
} }
character if character == 'B' => { 'B' => {
let v = input_stack.next().unwrap(); let v = input_stack.next().unwrap();
result.push(QueryValue::Number(utils::bcd_to_int(v as i32) as i64)); 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 let v = (input_stack.next().unwrap() as i32) << 8
| input_stack.next().unwrap() as i32; | input_stack.next().unwrap() as i32;
result.push(QueryValue::Number(utils::bcd_to_int(v) as i64)); 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 diacritics;
use encoding_rs::SHIFT_JIS; use encoding_rs::SHIFT_JIS;
use regex::Regex; use regex::Regex;
use std::collections::hash_map::HashMap; use std::{collections::hash_map::HashMap, error::Error, vec::IntoIter};
use unicode_normalization::UnicodeNormalization; use unicode_normalization::UnicodeNormalization;
extern crate kana; extern crate kana;
@ -14,7 +14,7 @@ pub fn bcd_to_int(mut bcd: i32) -> i32 {
while bcd != 0 { while bcd != 0 {
let nibble_value = bcd & 0xf; let nibble_value = bcd & 0xf;
bcd = bcd >> 4; bcd >>= 4;
value += nibble_value * i32::pow(10, nibble); value += nibble_value * i32::pow(10, nibble);
nibble += 1; nibble += 1;
} }
@ -36,7 +36,7 @@ pub fn int_to_bcd(mut value: i32) -> i32 {
bcd 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([ let mappings: HashMap<char, char> = HashMap::from([
('0', ''), ('0', ''),
('1', ''), ('1', ''),
@ -60,21 +60,15 @@ pub fn half_width_to_full_width_range(range: &String) -> String {
} }
pub fn get_bytes<const S: usize>( pub fn get_bytes<const S: usize>(
iterator: &mut std::vec::IntoIter<u8>, iterator: &mut IntoIter<u8>,
) -> Result<[u8; S], Box<dyn std::error::Error>> { ) -> Result<[u8; S], Box<dyn Error>> {
let mut bytes = [0; S]; let byte_vec: Vec<u8> = iterator.take(S).collect();
let bytes: [u8; S] = byte_vec.try_into().unwrap();
for i in 0..S {
bytes[i] = match iterator.next() {
Some(byte) => byte,
None => return Err("Could not retrieve byte from file".into()),
};
}
Ok(bytes) 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); let new_string = SHIFT_JIS.encode(string);
new_string.0.len() 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 { pub fn validate_shift_jis(sjis_string: Vec<u8>) -> bool {
let (_, _, had_errors) = SHIFT_JIS.decode(&sjis_string); let (_, _, had_errors) = SHIFT_JIS.decode(&sjis_string);
if had_errors { had_errors
true
} else {
false
}
} }
fn check(string: String) -> Option<String> { 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 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 // 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 let new_title: String = title
.chars() .chars()
.map(|character| { .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; let sjis_string = SHIFT_JIS.encode(&new_title).0;
if validate_shift_jis(sjis_string.clone().into()) { 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(); let re = Regex::new(r"[^\x00-\x7F]").unwrap();
re.replace_all( re.replace_all(
&diacritics::remove_diacritics(title) &diacritics::remove_diacritics(title)