Guest User

Untitled

a guest
Aug 15th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. #![feature(asm)]
  2.  
  3. trait FindFirstBit {
  4. fn ffs(&self) -> u8;
  5. }
  6.  
  7. #[inline(always)]
  8. fn supports_asm() -> bool {
  9. cfg!(any(
  10. target_arch = "x86",
  11. target_arch = "x86_64"
  12. ))
  13. }
  14.  
  15. macro_rules! impl_ffs {
  16. ($type:ty, $ltype:ty, $extension:expr) => (
  17. impl FindFirstBit for $type {
  18. fn ffs(&self) -> u8 {
  19. use std::mem::size_of;
  20. unsafe {
  21. if supports_asm() {
  22. let result: $type;
  23. asm!("bsf $1, $0" : "=r"(result) : "0"(*self));
  24. result as u8
  25. } else if $extension {
  26. const BITS: $type = (size_of::<$ltype>() << 3) as $type;
  27. if *self <= !(1 << BITS) {
  28. (*self as $ltype).ffs()
  29. } else {
  30. let lower_bits = ((*self >> (BITS / 2)) as $ltype).ffs();
  31. ((BITS / 2) + (lower_bits as $type)) as u8
  32. }
  33. } else {
  34. const BIT_TABLE: [u8; 256] = [
  35. 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
  36. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  37. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  38. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  39. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  40. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  41. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  42. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
  43. ];
  44. let bytes = match *self {
  45. n if n <= 0xff => 0,
  46. n if n <= 0xffff => 8,
  47. n if n <= 0xffffff => 16,
  48. _ => 24
  49. };
  50. *BIT_TABLE.as_ptr().offset((*self >> bytes) as isize) + bytes
  51. }
  52. }
  53. }
  54. }
  55. );
  56. }
  57.  
  58. impl_ffs!(u32, u32, false);
  59. impl_ffs!(u64, u32, true);
  60. impl_ffs!(u128, u64, true);
Add Comment
Please, Sign In to add comment