use cli_clipboard::{ClipboardContext, ClipboardProvider};
use colored::*;
use std::cmp::min;
#[cfg(unix)]
use nix::unistd::{fork, ForkResult};
pub fn yank(string: &str) {
let platform = std::env::consts::OS;
if vec![
"linux",
"freebsd",
"netbsd",
"dragonfly",
"netbsd",
"openbsd",
"solaris",
]
.contains(&platform)
{
#[cfg(unix)]
match unsafe { fork() } {
Ok(ForkResult::Child) => {
let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
ctx.set_contents(string.to_owned()).unwrap();
loop {
let clipboard = ctx.get_contents().unwrap();
std::thread::sleep(std::time::Duration::from_secs(1));
if clipboard != string {
std::process::exit(0);
}
}
}
Err(_) => {
println!("{}", "Error: Clipboard fork failed".red());
std::process::exit(1);
}
_ => {}
}
} else {
let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
ctx.set_contents(string.to_owned()).unwrap();
}
}
pub fn insert_and_shift<T: Copy>(list: &mut Vec<T>, index: usize, element: T) {
if index > list.len() - 1 {
return;
}
list.insert(index, element);
list.truncate(list.len() - 1);
}
#[allow(clippy::iter_count, clippy::needless_range_loop)]
pub fn edit_distance(search_chars: &[char], known_term: &str) -> usize {
let known_chars: Vec<char> = known_term.chars().collect();
let n = search_chars.iter().count() + 1;
let m = known_chars.iter().count() + 1;
let mut mat = vec![0; m * n];
for i in 1..n {
mat[i * m] = i;
}
for i in 1..m {
mat[i] = i;
}
for i in 1..n {
for j in 1..m {
let sub_cost = if search_chars[i - 1] == known_chars[j - 1] {
0
} else {
1
};
mat[i * m + j] = min(
mat[(i - 1) * m + j - 1] + sub_cost, min(
mat[(i - 1) * m + j] + 1, mat[i * m + j - 1] + 1, ),
);
if i > 1
&& j > 1
&& search_chars[i - 1] == known_chars[j - 2]
&& search_chars[i - 2] == known_chars[j - 1]
{
mat[i * m + j] = min(
mat[i * m + j],
mat[(i - 2) * m + j - 2] + 1, );
}
}
}
mat[m * n - 1]
}