pkmn-rs/pkstrings/examples/strings.rs
Maxime “pep” Buquet 7fa4a2079a
pkstrings: Remove TryFrom<String> for PKString
To force the user to use .as_st so that it's more obvious that we don't
take the ownership of the String.

Signed-off-by: Maxime “pep” Buquet <pep@bouah.net>
2021-11-15 15:25:12 +01:00

61 lines
1.8 KiB
Rust

// Copyright (C) 2020 "Maxime “pep” Buquet <pep@bouah.net>"
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
// for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::convert::TryFrom;
use std::fs;
use std::path::PathBuf;
use pkstrings::PKString;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "strings", about = "Display printable strings in [file(s)]")]
struct Opt {
#[structopt(parse(from_os_str), long, short)]
files: Vec<PathBuf>,
}
fn print_buffer(offset: usize, buffer: &Vec<String>) {
let mut res: String = String::new();
for buf in buffer {
res.push_str(buf.as_str());
}
println!("{}: {}", format!("{:#7x}", offset), res);
}
fn read_data(data: Vec<u8>) {
let mut buffer: Vec<String> = Vec::new();
for (offset, ord) in data.iter().enumerate() {
// Read current chr
if let Ok(pkstr) = PKString::try_from(&[*ord][..]) {
buffer.push(String::from(pkstr));
} else {
if buffer.len() >= 4 {
print_buffer(offset, &buffer);
}
buffer.clear();
}
}
}
fn main() {
let opt = Opt::from_args();
for file in opt.files {
let data: Vec<u8> = fs::read(file).unwrap();
read_data(data)
}
}