OLD | NEW |
| (Empty) |
1 // Copyright 2016 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 //! This module contains some useful functions for encoding. | |
6 | |
7 /// Given some size value, the size is aligned to some number in bytes. | |
8 /// | |
9 /// Neither the size nor bytes may be zero (those are always aligned) and | |
10 /// bytes must be a power of two (other alignments don't make sense). | |
11 pub fn align_bytes(size: usize, bytes: usize) -> usize { | |
12 debug_assert!(bytes != 0); | |
13 debug_assert!((bytes & (!bytes + 1)) == bytes); | |
14 (size + bytes - 1) & (!(bytes - 1)) | |
15 } | |
16 | |
17 /// Converts some number of bits into however many bytes are needed to | |
18 /// represent that bit size. | |
19 pub fn bits_to_bytes(bits: usize) -> usize { | |
20 ((bits + 7) >> 3) | |
21 } | |
22 | |
23 #[cfg(test)] | |
24 mod tests { | |
25 use super::align_bytes; | |
26 use super::bits_to_bytes; | |
27 | |
28 #[test] | |
29 fn check_align_bytes() { | |
30 assert_eq!(align_bytes(12, 8), 16); | |
31 assert_eq!(align_bytes(16, 4), 16); | |
32 assert_eq!(align_bytes(1, 1), 1); | |
33 } | |
34 | |
35 #[test] | |
36 #[should_panic] | |
37 fn check_bad_align_bytes() { | |
38 assert_eq!(align_bytes(15, 7), 21); | |
39 assert_eq!(align_bytes(2, 0), 0); | |
40 } | |
41 | |
42 #[test] | |
43 fn check_bits_to_bytes() { | |
44 assert_eq!(bits_to_bytes(8), 1); | |
45 assert_eq!(bits_to_bytes(0), 0); | |
46 assert_eq!(bits_to_bytes(1), 1); | |
47 assert_eq!(bits_to_bytes(21), 3); | |
48 } | |
49 } | |
OLD | NEW |