@@ -77,32 +77,50 @@ pub mod write;
77
77
78
78
/// When compressing data, the compression level can be specified by a value in
79
79
/// this enum.
80
- #[ derive( Copy , Clone , Debug ) ]
80
+ #[ derive( Copy , Clone , Debug , PartialEq , Eq ) ]
81
81
pub struct Compression ( u32 ) ;
82
82
83
83
impl 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
+ }
87
104
}
88
105
89
106
/// Do not compress.
107
+ #[ deprecated( since = "0.5.1" , note = "libbz2 does not support compression level 0" ) ]
90
108
pub fn none ( ) -> Compression {
91
109
Compression ( 0 )
92
110
}
93
111
94
112
/// Optimize for the best speed of encoding.
95
- pub fn fast ( ) -> Compression {
113
+ pub const fn fast ( ) -> Compression {
96
114
Compression ( 1 )
97
115
}
98
116
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 {
101
119
Compression ( 9 )
102
120
}
103
121
104
122
/// Return the compression level as an integer.
105
- pub fn level ( & self ) -> u32 {
123
+ pub const fn level ( & self ) -> u32 {
106
124
self . 0
107
125
}
108
126
}
@@ -113,3 +131,30 @@ impl Default for Compression {
113
131
Compression ( 6 )
114
132
}
115
133
}
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