use std::io::Read;
use std::io::Write;
use std::fmt;
use flate2::Compression;
use flate2::write::DeflateEncoder;
use flate2::read::DeflateDecoder;
#[derive(Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "with_serde", derive(serde_derive::Serialize, serde_derive::Deserialize))]
pub struct ComprString {
gz: Box<[u8]>
}
impl ComprString {
pub fn new(s: &str) -> Self {
let mut e = DeflateEncoder::new(Vec::with_capacity(s.len()/2), Compression::best());
e.write_all(s.as_bytes()).unwrap();
ComprString{ gz: e.finish().unwrap().into_boxed_slice() }
}
pub fn to_string(&self) -> String {
let mut deflater = DeflateDecoder::new(&self.gz[..]);
let mut s = String::with_capacity(self.gz.len()*2);
deflater.read_to_string(&mut s).unwrap();
s
}
pub fn compressed_len(&self) -> usize {
self.gz.len()
}
}
impl fmt::Display for ComprString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.to_string())
}
}
impl fmt::Debug for ComprString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.to_string().fmt(f)?;
write!(f, "@{}B", self.gz.len())
}
}
impl From<String> for ComprString {
fn from(o: String) -> Self {
Self::new(&o)
}
}
impl Into<String> for ComprString {
fn into(self) -> String {
self.to_string()
}
}
impl From<Box<str>> for ComprString {
fn from(o: Box<str>) -> Self {
Self::new(&o)
}
}
impl Into<Box<str>> for ComprString {
fn into(self) -> Box<str> {
self.to_string().into_boxed_str()
}
}
impl<'a> From<&'a str> for ComprString {
fn from(o: &'a str) -> Self {
Self::new(o)
}
}
#[test]
fn test() {
let s = ComprString::new("hęllo world");
assert_eq!("hęllo world", &s.to_string());
assert_eq!("hęllo world", &format!("{}", s));
assert_eq!("\"hęllo world\"@17B", &format!("{:?}", s));
let s2 = ComprString::new("hęllo world");
assert_eq!(s, s2);
let s = ComprString::new("");
assert_eq!("", &s.to_string());
assert_eq!(2, s.compressed_len());
let l = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
let s = ComprString::new(l);
assert_eq!(l, &s.to_string());
assert!(s.compressed_len() < l.len());
}