// Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
pub trait FloorLog2 {
fn floor_log2(&self ) -> Self ;
}
pub trait CeilLog2 {
fn ceil_log2(&self ) -> Self ;
}
impl FloorLog2 for u32 {
fn floor_log2(&self ) -> Self {
debug_assert_ne!(*self , 0 );
0 u32.leading_zeros() - self .leading_zeros() - 1
}
}
impl FloorLog2 for u64 {
fn floor_log2(&self ) -> Self {
debug_assert_ne!(*self , 0 );
(0 u64.leading_zeros() - self .leading_zeros() - 1 ) as u64
}
}
impl FloorLog2 for usize {
fn floor_log2(&self ) -> Self {
debug_assert_ne!(*self , 0 );
(0 usize.leading_zeros() - self .leading_zeros() - 1 ) as usize
}
}
impl <T> CeilLog2 for T
where
T: FloorLog2,
T: std::ops::Add<Output = Self >,
T: std::ops::Sub<Output = Self >,
T: std::ops::BitAnd<Output = Self >,
T: std::cmp::PartialEq,
T: From<u8>,
T: Copy,
{
fn ceil_log2(&self ) -> Self {
if (*self & (*self - 1 .into())) != 0 .into() {
self .floor_log2() + 1 .into()
} else {
self .floor_log2()
}
}
}
#[ cfg(test)]
mod test {
use super ::*;
#[ test]
fn test_floor() {
assert_eq!(0 , 1 u32.floor_log2());
assert_eq!(1 , 2 u32.floor_log2());
assert_eq!(1 , 3 u32.floor_log2());
assert_eq!(2 , 4 u32.floor_log2());
}
#[ test]
fn test_ceil() {
assert_eq!(0 , 1 u32.ceil_log2());
assert_eq!(1 , 2 u32.ceil_log2());
assert_eq!(2 , 3 u32.ceil_log2());
assert_eq!(2 , 4 u32.ceil_log2());
}
#[ test]
fn test_floor_us() {
assert_eq!(0 , 1 usize.floor_log2());
assert_eq!(1 , 2 usize.floor_log2());
assert_eq!(1 , 3 usize.floor_log2());
assert_eq!(2 , 4 usize.floor_log2());
}
#[ test]
fn test_ceil_us() {
assert_eq!(0 , 1 usize.ceil_log2());
assert_eq!(1 , 2 usize.ceil_log2());
assert_eq!(2 , 3 usize.ceil_log2());
assert_eq!(2 , 4 usize.ceil_log2());
}
}
Messung V0.5 in Prozent C=87 H=94 G=90
¤ Dauer der Verarbeitung: 0.11 Sekunden
(vorverarbeitet am 2026-08-25)
¤
*© Formatika GbR, Deutschland