rust 如何在没有任何Mutex jujitsu的情况下在惰性静态上下文中适应两个不同大小的可变静态数组

ni65a41a  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(105)

我试图填充两个不同大小的静态常量可变数组,通过将它们作为参数传递给函数。我尝试了各种方法,但最多我被困在这个错误:

error[E0277]: the trait bound `BISHOP_TABLE: BitboardTable` is not satisfied
  --> src/lib.rs:18:59
   |
18 |         pub static ref BISHOP_MAGICS: Magic = init_magics(&BISHOP_TABLE);
   |                                                           ^^^^^^^^^^^^^ the trait `BitboardTable` is not implemented for `BISHOP_TABLE`
   |
   = help: the following other types implement trait `BitboardTable`:
             Mutex<[Bitboard; 5248]>
             Mutex<[Bitboard; 102400]>
   = note: required for the cast from `&BISHOP_TABLE` to `&dyn BitboardTable`

这里是样板文件:

use bitintr::{Pext, Popcnt};
use lazy_static::lazy_static;
use std::sync::Mutex;

#[derive(Default, Copy, Clone)]
struct Bitboard(u64);

struct Magic {
    attacks: &'static[Bitboard]
}

lazy_static! {
        pub static ref ROOK_TABLE: Mutex<[Bitboard; 0x19000]> = Mutex::new([Default::default(); 0x19000]);
        pub static ref BISHOP_TABLE: Mutex<[Bitboard; 0x1480]> = Mutex::new([Default::default(); 0x1480]);
   
        pub static ref ROOK_MAGICS: Magic = init_magics(&ROOK_TABLE);
        pub static ref BISHOP_MAGICS: Magic = init_magics(&BISHOP_TABLE);
}

    pub trait BitboardTable {
        fn get_mutex(&self) -> &Mutex<[Bitboard]>;
    }
    
    impl BitboardTable for Mutex<[Bitboard; 0x19000]> {
        fn get_mutex(&self) -> &Mutex<[Bitboard]> {
            self
        }
    }
    
    impl BitboardTable for Mutex<[Bitboard; 0x1480]> {
        fn get_mutex(&self) -> &Mutex<[Bitboard]> {
            self
        }
    }
    

pub fn init_magics(table: &dyn BitboardTable) -> Magic {

    let mut size = 0;
    let mut magic_attacks = 0;

    magic_attacks += size;
    let mut attacks = & mut table.get_mutex().lock().expect("")[magic_attacks..];

    loop {

        attacks[0.pext(0) as usize] = 1;

        size += 1;
 
        if size > 5 { break }
    }

    Magic { attacks };
}
uqjltbpv

uqjltbpv1#

问题是lazy_static为每个static ref定义了一个新的类型,编译器看不到它只需要调用该类型的Deref实现来获得实现相关trait的&Mutex<[Bitboard; _]>。您可以通过使用*来简化自己来沿着它:

lazy_static! {
        static ref ROOK_TABLE: Mutex<[Bitboard; 1]> = Mutex::new([Default::default(); 1]);
        static ref ROOK_MAGICS: () = init_magics(&*ROOK_TABLE);
}

相关问题