hexe_core 0.0.5

The core components of the hexe chess engine crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! A square to piece mapping for fast square lookups.

use core::{fmt, hash, mem, ops, ptr, str};

#[cfg(feature = "simd")]
use core::simd::u8x64;

use consts::PTR_SIZE;
use misc::Contained;
use piece::Piece;
use prelude::*;
use uncon::*;
use util::*;

mod entry;
pub use self::entry::*;

mod iter;
pub use self::iter::*;

#[cfg(all(test, nightly))]
mod benches;

#[cfg(test)]
mod tests;

mod tables {
    use super::*;

    macro_rules! def_pieces {
        ($($n:ident => $p:ident),+ $(,)*) => {
            $(const $n: u8 = Piece::$p as u8;)+
        }
    }

    def_pieces! {
        WP => WhitePawn,   BP => BlackPawn,
        WN => WhiteKnight, BN => BlackKnight,
        WB => WhiteBishop, BB => BlackBishop,
        WR => WhiteRook,   BR => BlackRook,
        WK => WhiteKing,   BK => BlackKing,
        WQ => WhiteQueen,  BQ => BlackQueen,
    }

    /// The piece map for standard chess.
    pub const STANDARD: [u8; SQUARE_NUM] = [
        WR,   WN,   WB,   WQ,   WK,   WB,   WN,   WR,
        WP,   WP,   WP,   WP,   WP,   WP,   WP,   WP,
        NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
        NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
        NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
        NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
        BP,   BP,   BP,   BP,   BP,   BP,   BP,   BP,
        BR,   BN,   BB,   BQ,   BK,   BB,   BN,   BR,
    ];
}

const NONE: u8 = 12;

const SQUARE_NUM: usize = 64;

/// A mapping of sixty-four squares to pieces.
///
/// This allows for faster lookups than possible with bitboards.
///
/// **Note:** `PieceMap::default()` returns an empty piece map. Use
/// [`PieceMap::STANDARD`](#associatedconstant.STANDARD) to get a mapping for
/// standard chess.
#[repr(C)]
pub struct PieceMap(Inner);

#[derive(Copy, Clone)]
#[repr(C)]
union Inner {
    #[cfg(feature = "simd")]
    simd: u8x64,
    array: [u8; SQUARE_NUM],
}

impl FromUnchecked<[u8; SQUARE_NUM]> for PieceMap {
    #[inline]
    unsafe fn from_unchecked(array: [u8; SQUARE_NUM]) -> PieceMap {
        PieceMap(Inner { array: array })
    }
}

#[cfg(feature = "simd")]
impl FromUnchecked<u8x64> for PieceMap {
    #[inline]
    unsafe fn from_unchecked(vector: u8x64) -> PieceMap {
        PieceMap(Inner { simd: vector })
    }
}

impl Clone for PieceMap {
    #[inline]
    fn clone(&self) -> PieceMap { PieceMap(self.0) }
}

impl PartialEq for PieceMap {
    #[inline]
    fn eq(&self, other: &PieceMap) -> bool {
        #[cfg(feature = "simd")]
        {
            self as *const _ == other as *const _ ||
            self.as_vector() == other.as_vector()
        }
        #[cfg(not(feature = "simd"))]
        {
            self.as_bytes()[..] == other.as_bytes()[..]
        }
    }
}

impl Eq for PieceMap {}

impl Default for PieceMap {
    #[inline]
    fn default() -> PieceMap {
        PieceMap::EMPTY
    }
}

impl hash::Hash for PieceMap {
    #[inline]
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        state.write(self.as_bytes());
    }
}

static INDEX_ERR: &'static str = "no piece found for square";

impl ops::Index<Square> for PieceMap {
    type Output = Piece;

    #[inline]
    fn index(&self, sq: Square) -> &Piece {
        self.get(sq).expect(INDEX_ERR)
    }
}

impl ops::IndexMut<Square> for PieceMap {
    #[inline]
    fn index_mut(&mut self, sq: Square) -> &mut Piece {
        self.get_mut(sq).expect(INDEX_ERR)
    }
}

impl fmt::Debug for PieceMap {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_map().entries(self.iter()).finish()
    }
}

impl fmt::Display for PieceMap {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.map_str(|s| s.fmt(f))
    }
}

impl ::core::iter::FromIterator<(Square, Piece)> for PieceMap {
    #[inline]
    fn from_iter<T: IntoIterator<Item=(Square, Piece)>>(iter: T) -> PieceMap {
        let mut map = PieceMap::new();
        map.extend(iter);
        map
    }
}

impl Extend<(Square, Piece)> for PieceMap {
    #[inline]
    fn extend<T: IntoIterator<Item=(Square, Piece)>>(&mut self, iter: T) {
        for (s, p) in iter.into_iter() {
            self.insert(s, p);
        }
    }
}

impl PieceMap {
    /// An empty piece map.
    pub const EMPTY: PieceMap = PieceMap(Inner { array: [NONE; SQUARE_NUM] });

    /// The piece map for standard chess.
    pub const STANDARD: PieceMap = PieceMap(Inner { array: tables::STANDARD });

    /// Creates an empty piece map.
    #[inline]
    pub fn new() -> PieceMap {
        PieceMap::default()
    }

    /// Attempts to create a piece map from the fen string.
    pub fn from_fen(fen: &str) -> Option<PieceMap> {
        let mut map = PieceMap::EMPTY;
        let bytes = fen.as_bytes();

        let mut rank: usize = 7;
        let mut file: usize = 0;

        for &byte in bytes {
            match byte {
                b'/' => {
                    if file != 8 || rank == 0 {
                        return None;
                    }
                    file = 0;
                    rank -= 1;
                },
                b'1'...b'8' => {
                    file += (byte - b'0') as usize;
                    if file > 8 {
                        return None;
                    }
                },
                _ => if let Some(pc) = Piece::from_char(byte as char) {
                    let sq = Square::new(File::from(file),
                                         Rank::from(rank));
                    map.insert(sq, pc);
                    file += 1;
                } else {
                    return None;
                },
            }
        }

        if rank == 0 && file == 8 {
            Some(map)
        } else {
            None
        }
    }

    /// Creates a map with _all_ squares populated by `piece`.
    #[inline]
    pub fn filled(piece: Piece) -> PieceMap {
        PieceMap(Inner { array: [piece as u8; SQUARE_NUM] })
    }

    /// Creates a new piece map by instantiating each slot with the provided
    /// initializer.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hexe_core::board::piece_map::*;
    /// let piece_map = PieceMap::from_init(|sq| {
    ///     # None
    ///     /* ... */
    /// });
    /// ```
    #[inline]
    pub fn from_init<F>(mut init: F) -> PieceMap
        where F: FnMut(Square) -> Option<Piece>
    {
        let mut map: PieceMap = unsafe { mem::uninitialized() };
        for i in 0..SQUARE_NUM {
            let val = init(i.into()).map(|p| p as u8).unwrap_or(NONE);
            unsafe { ptr::write(&mut map.0.array[i], val) };
        }
        map
    }

    #[cfg(feature = "simd")]
    #[inline]
    fn inner(&self) -> &u8x64 { self.as_vector() }

    #[cfg(not(feature = "simd"))]
    #[inline]
    fn inner(&self) -> &[u8; SQUARE_NUM] { self.as_bytes() }

    /// Reverses the square mapping.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hexe_core::board::piece_map::*;
    /// # use hexe_core::prelude::*;
    /// let mut map = PieceMap::new();
    /// let piece = Piece::WhitePawn;
    ///
    /// map.insert(Square::A1, piece);
    /// map.reverse();
    ///
    /// assert_eq!(map[Square::H8], piece);
    /// ```
    #[inline]
    pub fn reverse(&mut self) {
        unsafe { self.0.array.reverse() };
    }

    /// Shuffles the map in-place.
    #[cfg(any(test, feature = "rand"))]
    pub fn shuffle<R: ::rand::Rng>(&mut self, rng: &mut R) {
        rng.shuffle(unsafe { self.as_bytes_mut() });
    }

    #[inline]
    #[cfg_attr(feature = "simd", allow(dead_code))]
    fn inner_ptr_sized(&self) -> &[usize; SQUARE_NUM / PTR_SIZE] {
        unsafe { (&self.0).into_unchecked() }
    }

    #[inline]
    fn inner_u64(&self) -> &[u64; 8] {
        unsafe { (&self.0).into_unchecked() }
    }

    #[inline]
    fn inner_2d_mut(&mut self) -> &mut [[u8; 8]; 8] {
        unsafe { (&mut self.0).into_unchecked() }
    }

    /// Mirrors the map across the horizontal axis of a chess board.
    pub fn mirror_horizontal(&mut self) {
        self.inner_2d_mut().reverse();
    }

    /// Mirrors the map across the vertical axis of a chess board.
    pub fn mirror_vertical(&mut self) {
        self.reverse();
        self.mirror_horizontal();
    }

    /// Returns the first square and piece pair in the map.
    #[inline]
    pub fn first(&self) -> Option<(Square, &Piece)> {
        self.iter().next()
    }

    /// Returns the first square and mutable piece pair in the map.
    #[inline]
    pub fn first_mut(&mut self) -> Option<(Square, &mut Piece)> {
        self.iter_mut().next()
    }

    /// Returns the last square and piece pair in the map.
    #[inline]
    pub fn last(&self) -> Option<(Square, &Piece)> {
        self.iter().next_back()
    }

    /// Returns the last square and mutable piece pair in the map.
    #[inline]
    pub fn last_mut(&mut self) -> Option<(Square, &mut Piece)> {
        self.iter_mut().next_back()
    }

    /// Efficiently fills the rank entirely with the given piece.
    #[inline]
    pub fn fill_rank(&mut self, r: Rank, pc: Piece) {
        self.inner_2d_mut()[r as usize] = [pc as u8; 8];
    }

    /// Performs a raw replacement.
    #[inline]
    unsafe fn replace(&mut self, sq: Square, pc: u8) -> Option<Piece> {
        match mem::replace(&mut self.as_bytes_mut()[sq as usize], pc) {
            NONE => None,
            p => Some(p.into_unchecked())
        }
    }

    /// Inserts the piece at a square, returning the previous one if any.
    #[inline]
    pub fn insert(&mut self, sq: Square, pc: Piece) -> Option<Piece> {
        unsafe { self.replace(sq, pc as u8) }
    }

    /// Removes the piece at a square.
    #[inline]
    pub fn remove(&mut self, sq: Square) -> Option<Piece> {
        unsafe { self.replace(sq, NONE) }
    }

    /// Swaps two values in the map.
    #[inline]
    pub fn swap<T: Swap>(&mut self, i: T, j: T) {
        T::swap(i, j, self);
    }

    /// Takes the piece at the square and moves it.
    #[inline]
    pub fn relocate(&mut self, from: Square, to: Square) {
        let buf = unsafe { self.as_bytes_mut() };
        buf[to as usize] = mem::replace(&mut buf[from as usize], NONE);
    }

    /// Performs a capture of the piece at `to` via the piece at `from`.
    ///
    /// If the squares are the same, then this will simply perform a removal.
    #[inline]
    pub fn capture(&mut self, from: Square, to: Square) -> Option<Piece> {
        let pc = self.remove(to);
        self.swap(from, to);
        pc
    }

    /// Performs an en passant capture of the piece on the same file as `to` and
    /// the same rank as `from`, via the piece at `from`.
    ///
    /// There are no checks made regarding whether `from` and `to` are legal en
    /// passant squares. The capture is performed with no assumptions. This also
    /// does not check whether the destination square contains a piece. If it
    /// does, it will be replaced by whichever value is at `from`.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hexe_core::board::piece_map::*;
    /// # use hexe_core::prelude::Square::*;
    /// # use hexe_core::prelude::Piece::*;
    /// let mut map = PieceMap::STANDARD;
    /// map.relocate(D2, D5);
    /// map.relocate(C7, C5);
    ///
    /// assert_eq!(map[D5], WhitePawn);
    /// assert_eq!(map[C5], BlackPawn);
    ///
    /// let pc = map.en_passant(D5, C6);
    /// assert_eq!(pc, Some(BlackPawn));
    /// assert_eq!(map.get(C5), None);
    /// ```
    #[inline]
    pub fn en_passant(&mut self, from: Square, to: Square) -> Option<Piece> {
        let ep = to.combine(from);
        let pc = self.remove(ep);
        self.relocate(from, to);
        pc
    }

    /// Performs a **blind** castle of the pieces for the castling right.
    ///
    /// Under legal castling circumstances, this method makes it so that squares
    /// involved with castling using `right` are in a correct state post-castle.
    #[inline]
    pub fn castle(&mut self, right: Right) {
        use piece::Piece::*;
        use square::Square::*;

        macro_rules! quad {
            ($a:expr, $b:expr, $c:expr, $d:expr) => {
                (($d as u32) << 24) |
                (($c as u32) << 16) |
                (($b as u32) << 8)  |
                ( $a as u32)
            }
        }

        struct Values { value: [u32; 4], pairs: [(Square, Square); 4] }

        static VALUES: Values = Values {
            value: [
                quad!(NONE, WhiteRook, WhiteKing, NONE),
                quad!(NONE, NONE,      WhiteKing, WhiteRook),
                quad!(NONE, BlackRook, BlackKing, NONE),
                quad!(NONE, NONE,      BlackKing, BlackRook),
            ],
            pairs: [(E1, E1), (E1, A1), (E8, E8), (E8, A8)],
        };

        let (king_sq, start_sq) = VALUES.pairs[right as usize];
        self.remove(king_sq);

        let buf = unsafe { self.as_bytes_mut() };
        let ptr = &mut buf[start_sq as usize] as *mut u8 as *mut u32;
        unsafe { *ptr = VALUES.value[right as usize] };
    }

    /// Inserts all pieces for which the function returns `Some`.
    #[inline]
    pub fn extend_from<F>(&mut self, mut f: F)
        where F: FnMut(Square) -> Option<Piece>
    {
        self.extend(Square::ALL.filter_map(|s| f(s).map(|p| (s, p))));
    }

    /// Retains only the elements specified by the predicate.
    #[inline]
    pub fn retain<F>(&mut self, mut f: F)
        where F: FnMut(Square, &mut Piece) -> bool
    {
        let iter = unsafe { self.0.array.iter_mut() };
        for (i, slot) in iter.enumerate() {
            if *slot != NONE && !f(i.into(), unsafe { slot.into_unchecked() }) {
                *slot = NONE;
            }
        }
    }

    /// Clears the map, removing all pieces.
    #[inline]
    pub fn clear(&mut self) {
        self.0.array = [NONE; SQUARE_NUM];
    }

    /// Removes all pieces from the given file.
    #[inline]
    pub fn clear_file(&mut self, file: File) {
        for rank in self.inner_2d_mut() {
            rank[file as usize] = NONE;
        }
    }

    /// Removes all pieces from the given rank.
    #[inline]
    pub fn clear_rank(&mut self, rank: Rank) {
        self.inner_2d_mut()[rank as usize] = [NONE; 8];
    }

    /// Returns whether `self` is empty.
    ///
    /// For much better performance and readability, is recommended to use this
    /// method over checking whether `self.len() == 0`.
    #[inline]
    pub fn is_empty(&self) -> bool {
        #[cfg(feature = "simd")]
        {
            *self.as_vector() == u8x64::splat(NONE)
        }
        #[cfg(not(feature = "simd"))]
        {
            let empty = usize::splat(NONE);
            for &slot in self.inner_ptr_sized() {
                if slot != empty {
                    return false;
                }
            }
            true
        }
    }

    /// Returns the total number of pieces in `self`.
    ///
    /// This operation is performed in O(n) time. It is recommended to store
    /// the result if it is used repeatedly.
    #[inline]
    pub fn len(&self) -> usize {
        SQUARE_NUM - self.inner().count(NONE)
    }

    /// Returns the number of occurrences of `piece` in `self`.
    ///
    /// This operation is performed in O(n) time. It is recommended to store
    /// the result if it is used repeatedly.
    #[inline]
    pub fn count(&self, piece: Piece) -> usize {
        self.inner().count(piece as u8)
    }

    /// Returns whether the map contains the value.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hexe_core::board::piece_map::*;
    /// # use hexe_core::prelude::*;
    /// let sq = Square::B7;
    /// let pc = Piece::WhiteRook;
    ///
    /// let mut map = PieceMap::new();
    /// map.insert(sq, pc);
    ///
    /// assert!(map.contains(sq));
    /// assert!(map.contains(pc));
    /// ```
    #[inline]
    pub fn contains<'a, T: Contained<&'a Self>>(&'a self, value: T) -> bool {
        value.contained_in(self)
    }

    /// Returns whether the rank contains the piece.
    #[inline]
    pub fn rank_contains(&self, rank: Rank, pc: Piece) -> bool {
        self.inner_u64()[rank as usize].contains_byte(pc as u8)
    }

    /// Returns the first square for the piece.
    #[inline]
    pub fn find(&self, pc: Piece) -> Option<Square> {
        ::memchr::memchr(pc as u8, self.as_bytes()).map(|index| unsafe {
            index.into_unchecked()
        })
    }

    /// Returns the last square for the piece.
    #[inline]
    pub fn rfind(&self, pc: Piece) -> Option<Square> {
        ::memchr::memrchr(pc as u8, self.as_bytes()).map(|index| unsafe {
            index.into_unchecked()
        })
    }

    /// Gets the given square's corresponding entry in the map for in-place
    /// manipulation.
    #[inline]
    pub fn entry(&mut self, sq: Square) -> Entry {
        Entry::from_map(self, sq)
    }

    /// Returns a reference to the piece at a square, if any.
    #[inline]
    pub fn get(&self, sq: Square) -> Option<&Piece> {
        match self.as_bytes()[sq as usize] {
            NONE => None,
            ref p => unsafe { Some(p.into_unchecked()) }
        }
    }

    /// Returns a mutable reference to the piece at a square, if any.
    #[inline]
    pub fn get_mut(&mut self, sq: Square) -> Option<&mut Piece> {
        unsafe {
            match self.0.array[sq as usize] {
                NONE => None,
                ref mut p => Some(p.into_unchecked())
            }
        }
    }

    /// Returns a reference to the piece at a square without checking.
    ///
    /// # Safety
    ///
    /// Calling this method when there's no piece at the given square will
    /// produce [undefined behavior][ub]. Use with caution.
    ///
    /// [ub]: https://en.wikipedia.org/wiki/Undefined_behavior
    #[inline]
    pub unsafe fn get_unchecked(&self, sq: Square) -> &Piece {
        (&self.as_bytes()[sq as usize]).into_unchecked()
    }

    /// Returns a mutable reference to the piece at a square without checking.
    ///
    /// # Safety
    ///
    /// Calling this method when there's no piece at the given square will
    /// produce [undefined behavior][ub]. Use with caution.
    ///
    /// [ub]: https://en.wikipedia.org/wiki/Undefined_behavior
    #[inline]
    pub unsafe fn get_unchecked_mut(&mut self, sq: Square) -> &mut Piece {
        (&mut self.as_bytes_mut()[sq as usize]).into_unchecked()
    }

    /// Returns the color of the piece at the given square, if any.
    #[inline]
    pub fn color_at(&self, sq: Square) -> Option<Color> {
        self.get(sq).map(|p| p.color())
    }

    /// Returns the color of the piece at the square without checking whether a
    /// valid piece exists there.
    ///
    /// Because of how `Color` is encoded in `Piece`, this is not an `unsafe`
    /// operation. If the square is empty, the returned color is `White`.
    /// However, errors and bugs may arise if this is used on an empty square.
    #[inline]
    pub fn color_at_unchecked(&self, sq: Square) -> Color {
        (self.as_bytes()[sq as usize] & 1).into()
    }

    /// Returns the role of the piece at the given square, if any.
    #[inline]
    pub fn role_at(&self, sq: Square) -> Option<Role> {
        const NO_PIECE: u8 = NONE >> 1;
        match self.as_bytes()[sq as usize] >> 1 {
            NO_PIECE => None,
            pc => unsafe { Some(mem::transmute(pc)) },
        }
    }

    /// Returns the result of applying a function to a mutable string
    /// representation of `self`.
    ///
    /// This method has the same benefits as [`Square::map_str`]
    ///
    /// # Examples
    ///
    /// **Note:** `PieceMap` implements [`Display`], thus it can be printed
    /// directly without using this method.
    ///
    /// ```
    /// # use hexe_core::board::piece_map::*;
    /// let map = PieceMap::STANDARD;
    /// let exp = "r n b q k b n r\n\
    ///            p p p p p p p p\n\
    ///            . . . . . . . .\n\
    ///            . . . . . . . .\n\
    ///            . . . . . . . .\n\
    ///            . . . . . . . .\n\
    ///            P P P P P P P P\n\
    ///            R N B Q K B N R";
    ///
    /// map.map_str(|s| assert_eq!(s, exp));
    /// ```
    ///
    /// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
    /// [`Square::map_str`]: ../../square/enum.Square.html#method.map_str
    #[inline]
    pub fn map_str<T, F: FnOnce(&mut str) -> T>(&self, f: F) -> T {
        let mut buf = *::consts::BOARD_DOTS;
        for square in Square::ALL {
            if let Some(&piece) = self.get(square) {
                let ch = char::from(piece) as u8;
                let idx = (0b111000 ^ square as usize) << 1;
                unsafe { *buf.get_unchecked_mut(idx) = ch };
            }
        }
        unsafe { f(str::from_utf8_unchecked_mut(&mut buf)) }
    }

    /// Returns the result of applying a function to a [FEN] string
    /// representation of `self`.
    ///
    /// [FEN]: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
    #[inline]
    pub fn map_fen<T, F: FnOnce(&mut str) -> T>(&self, f: F) -> T {
        const NUM: usize = 8;
        const MAX: usize = NUM * NUM + 7;
        let mut len: usize = 0;

        unsafe {
            let mut buf: [u8; MAX] = mem::uninitialized();
            macro_rules! write_buf {
                ($val:expr) => {
                    ptr::write(buf.get_unchecked_mut(len), $val);
                    len += 1;
                }
            }

            for rank in (0..NUM).rev().map(Rank::from) {
                let mut n: u8 = 0;
                for file in (0..NUM).map(File::from) {
                    let square = Square::new(file, rank);
                    if let Some(&pc) = self.get(square) {
                        if n != 0 {
                            write_buf!(b'0' + n);
                            n = 0;
                        }
                        write_buf!(char::from(pc) as u8);
                    } else {
                        n += 1;
                    }
                }
                if n != 0 {
                    write_buf!(b'0' + n);
                }
                if rank != Rank::One {
                    write_buf!(b'/');
                }
            }

            f(str::from_utf8_unchecked_mut(buf.get_unchecked_mut(..len)))
        }
    }

    /// Returns an owned [FEN] string representation of `self`.
    ///
    /// [FEN]: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
    #[cfg(feature = "std")]
    pub fn to_fen(&self) -> String {
        self.map_fen(|s| String::from(s as &str))
    }

    /// Returns an iterator visiting all square-piece pairs in order.
    #[inline]
    pub fn iter(&self) -> Iter { self.into_iter() }

    /// Returns an iterator visiting all square-piece pairs mutably in order.
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut { self.into_iter() }

    /// Returns a view into the bytes of the map.
    ///
    /// # Values
    ///
    /// - Bytes with values less than 12 refer to a valid `Piece` instance.
    /// - Empty slots have a value of 12.
    ///
    /// You may safely assume that that no values greater than 12 exist.
    #[inline]
    pub fn as_bytes(&self) -> &[u8; 64] {
        unsafe { &self.0.array }
    }

    /// Returns a mutable view into the bytes of the map.
    ///
    /// For more information, see [`as_bytes`](#method.as_bytes).
    ///
    /// # Safety
    ///
    /// Internal operations rely on certain assumptions about the contents of
    /// this buffer. Mutating these bytes such that piece values become invalid
    /// will cause [undefined behavior][ub].
    ///
    /// [ub]: https://en.wikipedia.org/wiki/Undefined_behavior
    #[inline]
    pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8; 64] {
        &mut self.0.array
    }

    /// A reference to the inner SIMD vector for `self`.
    ///
    /// Requires enabling the `simd` feature.
    #[cfg(feature = "simd")]
    #[inline]
    pub fn as_vector(&self) -> &u8x64 {
        unsafe { &self.0.simd }
    }

    /// A mutable reference to the inner SIMD vector for `self`.
    ///
    /// Requires enabling the `simd` feature.
    ///
    /// # Safety
    ///
    /// See [`PieceMap::as_bytes_mut`](#method.as_bytes_mut) for how to handle
    /// safely writing to the vector.
    #[cfg(feature = "simd")]
    #[inline]
    pub unsafe fn as_vector_mut(&mut self) -> &mut u8x64 {
        &mut self.0.simd
    }
}

impl<'a> Contained<&'a PieceMap> for Square {
    #[inline]
    fn contained_in(self, map: &PieceMap) -> bool {
        map.as_bytes()[self as usize] != NONE
    }
}

impl<'a> Contained<&'a PieceMap> for Piece {
    #[inline]
    fn contained_in(self, map: &PieceMap) -> bool {
        #[cfg(feature = "simd")]
        {
            (*map.as_vector()).eq(u8x64::splat(self as u8)).any()
        }
        #[cfg(not(feature = "simd"))]
        {
            map.find(self).is_some()
        }
    }
}

/// A type whose instances may be used to swap values in a
/// [`PieceMap`](struct.PieceMap.html).
pub trait Swap {
    /// Swaps the values at `i` and `j` in `map`.
    fn swap(i: Self, j: Self, map: &mut PieceMap);
}

impl Swap for Square {
    #[inline]
    fn swap(i: Square, j: Square, map: &mut PieceMap) {
        unsafe { map.0.array.swap(i as usize, j as usize) };
    }
}

impl Swap for Rank {
    #[inline]
    fn swap(i: Rank, j: Rank, map: &mut PieceMap) {
        map.inner_2d_mut().swap(i as usize, j as usize);
    }
}