Created
January 5, 2017 06:06
-
-
Save SpamapS/44f1ee697903141e926ca3f54bc0b74b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fmt::*; | |
use std::iter::IntoIterator; | |
use std::ops::{Index, RangeFrom}; | |
#[test] | |
fn test_debug_kinda_string() { | |
let z: Vec<u8> = vec![240, 159, 146, 150]; | |
let x = GearBytes(z); | |
let f = format!("{:?}", &x); | |
assert_eq!("\"💖\"", f); | |
let f = format!("{}", &x); | |
assert_eq!("💖", f); | |
} | |
#[test] | |
fn test_debug_kinda_string_invalid_utf8() { | |
let z = vec![64, 0, 0, 0,]; | |
let x = GearBytes(z); | |
let f = format!("{}", &x); | |
assert_eq!("@\u{0}\u{0}\u{0}", f); | |
} | |
/// We almost always just want vectors of u8's or slices of u8's | |
/// But for convenience in debugging these will be shown as lossy utf8 strings | |
/// | |
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Hash)] | |
pub struct GearBytes(pub Vec<u8>); | |
impl Debug for GearBytes { | |
fn fmt(&self, f: &mut Formatter) -> Result { | |
write!(f, "{:?}", String::from_utf8_lossy(&self.0)) | |
} | |
} | |
impl Display for GearBytes { | |
fn fmt(&self, f: &mut Formatter) -> Result { | |
write!(f, "{}", String::from_utf8_lossy(&self.0)) | |
} | |
} | |
impl IntoIterator for GearBytes { | |
type Item = u8; | |
type IntoIter = ::std::vec::IntoIter<u8>; | |
fn into_iter(self) -> Self::IntoIter { | |
self.0.into_iter() | |
} | |
} | |
impl Index<usize> for GearBytes { | |
type Output = u8; | |
fn index(&self, idx: usize) -> &u8 { | |
self.0.index(idx) | |
} | |
} | |
impl Index<RangeFrom<usize>> for GearBytes { | |
type Output = [u8]; | |
fn index(&self, idx: RangeFrom<usize>) -> &[u8] { | |
self.0.index(idx) | |
} | |
} | |
impl Extend<u8> for GearBytes { | |
fn extend<I>(&mut self, iter: I) where I:IntoIterator<Item=u8> { | |
self.0.extend(iter) | |
} | |
} | |
impl GearBytes { | |
pub fn len(&self) -> usize { | |
self.0.len() | |
} | |
pub fn with_capacity(capacity: usize) -> GearBytes { | |
let vec = Vec::with_capacity(capacity); | |
GearBytes(vec) | |
} | |
pub fn push(&mut self, item: u8) { | |
self.0.push(item) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment