@@ -77,32 +77,50 @@ pub mod write;
7777
7878/// When compressing data, the compression level can be specified by a value in
7979/// this enum.
80- #[ derive( Copy , Clone , Debug ) ]
80+ #[ derive( Copy , Clone , Debug , PartialEq , Eq ) ]
8181pub struct Compression ( u32 ) ;
8282
8383impl Compression {
84- /// Create a new compression spec with a specific numeric level (0-9).
85- pub fn new ( level : u32 ) -> Compression {
86- Compression ( level)
84+ /// Create a new compression spec with a specific numeric level in the range `1..=9`.
85+ ///
86+ /// # Panics
87+ ///
88+ /// A level outside of the `1..=9` range will throw a panic. Use [`Self::try_new`] to
89+ /// gracefully handle invalid levels (e.g. from user input).
90+ #[ track_caller]
91+ pub const fn new ( level : u32 ) -> Compression {
92+ match Self :: try_new ( level) {
93+ Some ( v) => v,
94+ None => panic ! ( "expected a compression level in the range 1..=9" ) ,
95+ }
96+ }
97+
98+ /// Create a new compression spec with a specific numeric level in the range `1..=9`.
99+ pub const fn try_new ( level : u32 ) -> Option < Compression > {
100+ match level {
101+ 1 ..=9 => Some ( Compression ( level) ) ,
102+ _ => None ,
103+ }
87104 }
88105
89106 /// Do not compress.
107+ #[ deprecated( since = "0.5.1" , note = "libbz2 does not support compression level 0" ) ]
90108 pub fn none ( ) -> Compression {
91109 Compression ( 0 )
92110 }
93111
94112 /// Optimize for the best speed of encoding.
95- pub fn fast ( ) -> Compression {
113+ pub const fn fast ( ) -> Compression {
96114 Compression ( 1 )
97115 }
98116
99- /// Optimize for the size of data being encoded .
100- pub fn best ( ) -> Compression {
117+ /// Optimize for smallest output size .
118+ pub const fn best ( ) -> Compression {
101119 Compression ( 9 )
102120 }
103121
104122 /// Return the compression level as an integer.
105- pub fn level ( & self ) -> u32 {
123+ pub const fn level ( & self ) -> u32 {
106124 self . 0
107125 }
108126}
@@ -113,3 +131,30 @@ impl Default for Compression {
113131 Compression ( 6 )
114132 }
115133}
134+
135+ #[ cfg( test) ]
136+ mod test {
137+ use super :: * ;
138+
139+ #[ test]
140+ #[ should_panic]
141+ fn new_level_0 ( ) {
142+ Compression :: new ( 0 ) ;
143+ }
144+
145+ #[ test]
146+ #[ should_panic]
147+ fn new_level_10 ( ) {
148+ Compression :: new ( 10 ) ;
149+ }
150+
151+ #[ test]
152+ fn try_new ( ) {
153+ assert ! ( Compression :: try_new( 0 ) . is_none( ) ) ;
154+ assert ! ( Compression :: try_new( 10 ) . is_none( ) ) ;
155+
156+ assert_eq ! ( Compression :: try_new( 1 ) , Some ( Compression :: fast( ) ) ) ;
157+ assert_eq ! ( Compression :: try_new( 6 ) , Some ( Compression :: default ( ) ) ) ;
158+ assert_eq ! ( Compression :: try_new( 9 ) , Some ( Compression :: best( ) ) ) ;
159+ }
160+ }
0 commit comments