11// https://en.wikipedia.org/wiki/Move-to-front_transform
22
3+ fn blank_char_table ( ) -> Vec < char > {
4+ ( 0 ..=255 ) . map ( |ch| ch as u8 as char ) . collect ( )
5+ }
6+
37pub fn move_to_front_encode ( text : & str ) -> Vec < u8 > {
4- let mut char_table: Vec < char > = ( 0 ..= 255 ) . map ( |ch| ch as u8 as char ) . collect ( ) ;
8+ let mut char_table = blank_char_table ( ) ;
59 let mut result = Vec :: new ( ) ;
610
711 for ch in text. chars ( ) {
@@ -16,7 +20,7 @@ pub fn move_to_front_encode(text: &str) -> Vec<u8> {
1620}
1721
1822pub fn move_to_front_decode ( encoded : & [ u8 ] ) -> String {
19- let mut char_table: Vec < char > = ( 0 ..= 255 ) . map ( |ch| ch as u8 as char ) . collect ( ) ;
23+ let mut char_table = blank_char_table ( ) ;
2024 let mut result = String :: new ( ) ;
2125
2226 for & pos in encoded {
@@ -33,23 +37,24 @@ pub fn move_to_front_decode(encoded: &[u8]) -> String {
3337mod test {
3438 use super :: * ;
3539
36- #[ test]
37- fn test_move_to_front_encode ( ) {
38- assert_eq ! ( move_to_front_encode( "" ) , [ ] ) ;
39- assert_eq ! ( move_to_front_encode( "@" ) , [ 64 ] ) ;
40- assert_eq ! ( move_to_front_encode( "aaba" ) , [ 97 , 0 , 98 , 1 ] ) ;
41- assert_eq ! ( move_to_front_encode( "aZ!" ) , [ 97 , 91 , 35 ] ) ;
42- assert_eq ! ( move_to_front_encode( "banana" ) , [ 98 , 98 , 110 , 1 , 1 , 1 ] ) ;
43- assert_eq ! ( move_to_front_encode( "\0 \n \t " ) , [ 0 , 10 , 10 ] ) ;
40+ macro_rules! test_mtf {
41+ ( $( $name: ident: ( $text: expr, $encoded: expr) , ) * ) => {
42+ $(
43+ #[ test]
44+ fn $name( ) {
45+ assert_eq!( move_to_front_encode( $text) , $encoded) ;
46+ assert_eq!( move_to_front_decode( & $encoded) , $text) ;
47+ }
48+ ) *
49+ }
4450 }
4551
46- #[ test]
47- fn test_move_to_front_decode ( ) {
48- assert_eq ! ( move_to_front_decode( & [ ] ) , "" ) ;
49- assert_eq ! ( move_to_front_decode( & [ 64 ] ) , "@" ) ;
50- assert_eq ! ( move_to_front_decode( & [ 97 , 0 , 98 , 1 ] ) , "aaba" ) ;
51- assert_eq ! ( move_to_front_decode( & [ 97 , 91 , 35 ] ) , "aZ!" ) ;
52- assert_eq ! ( move_to_front_decode( & [ 98 , 98 , 110 , 1 , 1 , 1 ] ) , "banana" ) ;
53- assert_eq ! ( move_to_front_decode( & [ 0 , 10 , 10 ] ) , "\0 \n \t " ) ;
52+ test_mtf ! {
53+ empty: ( "" , vec![ ] ) ,
54+ single_char: ( "@" , vec![ 64 ] ) ,
55+ repeated_chars: ( "aaba" , vec![ 97 , 0 , 98 , 1 ] ) ,
56+ mixed_chars: ( "aZ!" , vec![ 97 , 91 , 35 ] ) ,
57+ word: ( "banana" , vec![ 98 , 98 , 110 , 1 , 1 , 1 ] ) ,
58+ special_chars: ( "\0 \n \t " , vec![ 0 , 10 , 10 ] ) ,
5459 }
5560}
0 commit comments