Compare commits

..

No commits in common. "278ba2e8bdc71d957eb62246f5115c604fc7e7ed" and "cafd518f9d3b75c2398efdebcbe6b0be9433c393" have entirely different histories.

6 changed files with 708 additions and 754 deletions

View file

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

View file

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

View file

@ -9,11 +9,9 @@ use std::collections::HashMap;
use std::error::Error;
use magic_crypt::{MagicCrypt, SecureBit, MagicCryptTrait, new_magic_crypt};
use hex;
use std::thread::sleep;
use std::time::Duration;
use yusb;
use lazy_static::lazy_static;
use webusb;
#[derive(Copy, Clone)]
enum Action {
@ -37,9 +35,8 @@ pub enum DiscFormat {
SPStereo = 6,
}
#[derive(Clone, Hash, Eq, PartialEq)]
enum WireFormat {
Pcm = 0x00,
PCM = 0x00,
L105kbps = 0x90,
LP2 = 0x94,
LP4 = 0xA8,
@ -48,7 +45,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,
@ -106,7 +103,7 @@ enum Descriptor {
DiscTitleTD,
AudioUTOC1TD,
AudioUTOC4TD,
Dstid,
DSITD,
AudioContentsTD,
RootTD,
@ -120,7 +117,7 @@ impl Descriptor {
Descriptor::DiscTitleTD => vec![0x10, 0x18, 0x01],
Descriptor::AudioUTOC1TD => vec![0x10, 0x18, 0x02],
Descriptor::AudioUTOC4TD => vec![0x10, 0x18, 0x03],
Descriptor::Dstid => vec![0x10, 0x18, 0x04],
Descriptor::DSITD => vec![0x10, 0x18, 0x04],
Descriptor::AudioContentsTD => vec![0x10, 0x10, 0x01],
Descriptor::RootTD => vec![0x10, 0x10, 0x00],
Descriptor::DiscSubunitIdentifier => vec![0x00],
@ -154,15 +151,6 @@ enum Status {
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 {
type Error = Box<dyn Error>;
@ -204,13 +192,13 @@ impl NetMDInterface {
const INTERIM_RESPONSE_RETRY_INTERVAL: u32 = 100;
pub fn new(
device: yusb::Device,
device: webusb::UsbDevice,
) -> Result<Self, Box<dyn Error>> {
let net_md_device = base::NetMD::new(device).unwrap();
Ok(NetMDInterface { net_md_device })
}
fn construct_multibyte(&mut self, buffer: &[u8], n: u8, offset: &mut usize) -> u32 {
fn construct_multibyte(&mut self, buffer: &Vec<u8>, n: u8, offset: &mut usize) -> u32 {
let mut output: u32 = 0;
for _ in 0..n as usize {
output <<= 8;
@ -372,7 +360,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),
Err(error) => return Err(error.into()),
};
let status = match Status::try_from(data[0]) {
@ -822,8 +810,8 @@ impl NetMDInterface {
if title.ends_with(delim) {
let first_entry = title.split(delim).collect::<Vec<&str>>()[0];
if let Some(stripped_title) = first_entry.strip_prefix(title_marker) {
title = stripped_title.to_string();
if first_entry.starts_with(title_marker) {
title = first_entry[title_marker.len()..].to_string();
} else {
title = String::new();
}
@ -845,19 +833,19 @@ impl NetMDInterface {
let mut full_width_group_list = raw_full_title.split("");
for (i, group) in group_list.enumerate() {
if group.is_empty() {
if group == "" {
continue;
}
if group.starts_with("0;") || group.find(';').is_none() || !raw_title.contains("//") {
if group.starts_with("0;") || group.find(";") == None || raw_title.find("//") == None {
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.is_empty() {
if track_range.len() == 0 {
continue;
}
@ -868,15 +856,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('-').is_some() {
track_minmax = track_range.split('-').collect();
if track_range.find("-") != None {
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) = (
@ -884,7 +872,7 @@ impl NetMDInterface {
track_minmax[1].parse::<u16>().unwrap(),
);
track_max = u16::min(track_max, track_count);
track_max = u16::min(track_max, track_count as u16);
// TODO: Do some error handling here
assert!(track_min <= track_max);
@ -907,7 +895,7 @@ impl NetMDInterface {
));
}
for i in 0..track_count {
for i in 0..track_count as u16 {
if !track_dict.contains_key(&i) {
result.insert(0, (None, None, Vec::from([i])))
}
@ -1034,18 +1022,23 @@ impl NetMDInterface {
},
};
let old_len: u16;
let new_len = new_title.len();
let old_len: u16 = match self.track_title(track, wchar) {
match self.track_title(track, wchar) {
Ok(current_title) => {
if title == current_title {
return Ok(())
}
length_after_encoding_to_jis(&current_title) as u16
old_len = length_after_encoding_to_jis(&current_title) as u16;
},
Err(error) if error.to_string() == "Rejected" => 0,
Err(error) => return Err(error)
};
Err(error) if error.to_string() == "Rejected" => {
old_len = 0;
},
Err(error) => {
return Err(error);
}
}
self.change_descriptor_state(&descriptor, &DescriptorAction::OpenWrite);
let mut query = format_query(
@ -1112,7 +1105,7 @@ impl NetMDInterface {
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close);
Ok(res[0].to_vec().unwrap())
return Ok(res[0].to_vec().unwrap());
}
/// Gets the length of tracks as a `std::time::Duration` from a set
@ -1325,7 +1318,7 @@ impl NetMDInterface {
let chainlen = keychain.len();
let databytes = 16 + 16 * chainlen + 24;
if !(1..=63).contains(&depth) {
if depth < 1 || depth > 63 {
return Err("Supplied depth is invalid".into());
}
if ekbsignature.len() != 24 {
@ -1393,7 +1386,7 @@ impl NetMDInterface {
return Err("Supplied Session Key length wrong".into());
}
let message = [vec![1, 1, 1, 1], contentid, keyenckey].concat();
let message = vec![vec![1, 1, 1, 1], contentid, keyenckey].concat();
let mc = MagicCrypt::new(
hex_session_key,
@ -1472,17 +1465,19 @@ impl NetMDInterface {
// Sharps are slow
sleep(Duration::from_millis(200));
let mut _written_bytes = 0;
for (packet_count, (key, iv, data)) in packets.into_iter().enumerate(){
let mut packet_count = 0;
let mut written_bytes = 0;
for (key, iv, data) in packets {
let mut binpack;
if packet_count == 0 {
let packed_length: Vec<u8> = pkt_size.to_le_bytes().to_vec();
binpack = [vec![0, 0, 0, 0], packed_length, key, iv, data.clone()].concat();
binpack = vec![vec![0, 0, 0, 0], packed_length, key, iv, data.clone()].concat();
} else {
binpack = data.clone();
}
self.net_md_device.write_bulk(&mut binpack)?;
_written_bytes += data.len();
packet_count += 1;
written_bytes += data.len();
}
reply = self.read_reply(false)?;
@ -1497,8 +1492,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].iter());
let part2 = String::from_iter(reply_data.clone()[12..32].iter());
let part1 = String::from_iter(reply_data.clone()[0..8].into_iter());
let part2 = String::from_iter(reply_data.clone()[12..32].into_iter());
Ok((res[0].to_i64().unwrap(), part1, part2))
}
@ -1535,7 +1530,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(),
@ -1544,21 +1539,13 @@ pub fn retailmac(
);
let step1 = mc.encrypt_bytes_to_bytes(&beginning);
let _iv2 = String::from_utf8(step1);
let iv2 = String::from_utf8(step1);
Ok(())
}
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 {
@ -1590,66 +1577,14 @@ impl EKBOpenSource {
*/
}
#[derive(Clone)]
struct MDTrack {
title: String,
format: WireFormat,
data: Vec<u8>,
chunk_size: i32,
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 {
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,8 +1,7 @@
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use std::collections::HashMap;
lazy_static! {
pub static ref MAPPINGS_JP: HashMap<String, String> = HashMap::from([
pub const MAPPINGS_JP: Lazy<HashMap<String, String>> = Lazy::new(|| {[
("!".to_string(), "".to_string()),
("\"".to_string(), "".to_string()),
("#".to_string(), "".to_string()),
@ -192,9 +191,9 @@ lazy_static! {
("".to_string(), "".to_string()),
("".to_string(), "".to_string()),
("".to_string(), "".to_string())
]);
].into_iter().collect()});
pub static ref MAPPINGS_RU: HashMap<String, String> = HashMap::from([
pub const MAPPINGS_RU: Lazy<HashMap<String, String>> = Lazy::new(|| {[
("а".to_string(), "a".to_string()),
("б".to_string(), "b".to_string()),
("в".to_string(), "v".to_string()),
@ -261,9 +260,9 @@ lazy_static! {
("Э".to_string(), "E".to_string()),
("Ю".to_string(), "Iu".to_string()),
("Я".to_string(), "Ia".to_string())
]);
].into_iter().collect()});
pub static ref MAPPINGS_DE: HashMap<String, String> = HashMap::from([
pub const MAPPINGS_DE: Lazy<HashMap<String, String>> = Lazy::new(|| {[
("Ä".to_string(), "Ae".to_string()),
("ä".to_string(), "ae".to_string()),
("Ö".to_string(), "Oe".to_string()),
@ -271,9 +270,9 @@ lazy_static! {
("Ü".to_string(), "Ue".to_string()),
("ü".to_string(), "ue".to_string()),
("ß".to_string(), "ss".to_string())
]);
].into_iter().collect()});
pub static ref MAPPINGS_HW: HashMap<String, String> = HashMap::from([
pub const MAPPINGS_HW: Lazy<HashMap<String, String>> = Lazy::new(|| {[
("".to_string(),"-".to_string()),
("".to_string(),"-".to_string()),
("".to_string(),"".to_string()),
@ -552,7 +551,6 @@ lazy_static! {
("".to_string(),"ヴ".to_string()),
("".to_string(),"".to_string()),
("".to_string(),"".to_string()),
]);
].into_iter().collect()});
pub static ref ALLOWED_HW_KANA: Vec<String> = MAPPINGS_HW.values().cloned().collect();
}
pub const ALLOWED_HW_KANA: Lazy<Vec<String>> = Lazy::new(|| {MAPPINGS_HW.values().cloned().collect()});

View file

@ -1,23 +1,26 @@
use crate::netmd::utils;
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use std::collections::hash_map::HashMap;
use std::error::Error;
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, 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([
('b', 1), // byte
('w', 2), // word
('d', 4), // doubleword
('q', 8), // quadword
]);
}
])
});
const DEBUG: bool = false;
@ -105,7 +108,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);
}
@ -212,17 +215,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) {
for entry in temp_stack.take(initial_length as usize) {
result_buffer.push(entry);
input_stack.next();
}
result.push(QueryValue::Array(result_buffer));
}
'B' => {
character if character == 'B' => {
let v = input_stack.next().unwrap();
result.push(QueryValue::Number(utils::bcd_to_int(v as i32) as i64));
}
'W' => {
character if character == '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, error::Error, vec::IntoIter};
use std::collections::hash_map::HashMap;
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 >>= 4;
bcd = 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: &str) -> String {
pub fn half_width_to_full_width_range(range: &String) -> String {
let mappings: HashMap<char, char> = HashMap::from([
('0', ''),
('1', ''),
@ -60,15 +60,21 @@ pub fn half_width_to_full_width_range(range: &str) -> String {
}
pub fn get_bytes<const S: usize>(
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();
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()),
};
}
Ok(bytes)
}
pub fn length_after_encoding_to_jis(string: &str) -> usize {
pub fn length_after_encoding_to_jis(string: &String) -> usize {
let new_string = SHIFT_JIS.encode(string);
new_string.0.len()
@ -77,7 +83,11 @@ pub fn length_after_encoding_to_jis(string: &str) -> usize {
pub fn validate_shift_jis(sjis_string: Vec<u8>) -> bool {
let (_, _, had_errors) = SHIFT_JIS.decode(&sjis_string);
had_errors
if had_errors {
true
} else {
false
}
}
fn check(string: String) -> Option<String> {
@ -114,11 +124,11 @@ pub fn sanitize_half_width_title(mut title: String) -> Vec<u8> {
return agressive_sanitize_title(&title).into();
}
sjis_string.into()
return sjis_string.into();
}
// TODO: This function is bad, probably should do the string sanitization in the frontend
pub fn sanitize_full_width_title(title: &str, just_remap: bool) -> Vec<u8> {
pub fn sanitize_full_width_title(title: &String, just_remap: bool) -> Vec<u8> {
let new_title: String = title
.chars()
.map(|character| {
@ -151,13 +161,13 @@ pub fn sanitize_full_width_title(title: &str, 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();
}
sjis_string.into()
return sjis_string.into();
}
pub fn agressive_sanitize_title(title: &str) -> String {
pub fn agressive_sanitize_title(title: &String) -> String {
let re = Regex::new(r"[^\x00-\x7F]").unwrap();
re.replace_all(
&diacritics::remove_diacritics(title)