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
//! Contains the `MoveList` & `ScoreMoveList` structures, akin to a `Vec<BitMove>` but faster for
//! our purposes.
//!
//! A [`MoveList`] structure is guaranteed to be exactly 512 bytes long, containing a maximum of 256
//! moves. This number was chosen as no possible chess position has been found to contain more than
//! 232 possible moves.
//!
//! This structure is intended to mainly be used for generation of moves for a certain position. If
//! you need to a more versatile collection of moves to manipulate, considering using a `Vec<BitMove>`
//! instead.
//!
//! The [`ScoreMoveList`] is practically the same as the [`MoveList`], but it allows for each move to
//! have a score attached to it as well.
//!
//! [`MoveList`]: struct.MoveList.html
//! [`ScoreMoveList`]: struct.MoveList.html

use std::slice;
use std::ops::{Deref,DerefMut,Index,IndexMut};
use std::iter::{Iterator,IntoIterator,FusedIterator,TrustedLen,ExactSizeIterator,FromIterator};
use super::piece_move::{BitMove, ScoringMove};


#[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), target_feature = "avx2"))]
use std::simd::u16x32;
#[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), target_feature = "avx2"))]
use std::mem::transmute;
#[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), target_feature = "avx2"))]
use super::bitboard::BitBoard;
#[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), target_feature = "avx2"))]
use super::sq::SQ;


pub trait MVPushable: Sized + IndexMut<usize> + Index<usize> + DerefMut {

    /// Adds a `BitMove` to the end of the list.
    ///
    /// # Safety
    ///
    /// If pushing to the list when at capacity, does nothing.
    fn push_mv(&mut self, mv: BitMove);

    /// Adds a `BitMove` to the end of the list.
    ///
    /// # Safety
    ///
    /// Undefined behavior if pushing to the list when `MoveList::len() = 256`.
    unsafe fn unchecked_push_mv(&mut self, mv: BitMove);

    /// Set the length of the list.
    ///
    /// # Safety
    ///
    /// Unsafe due to overwriting the length of the list
    unsafe fn unchecked_set_len(&mut self, len: usize);


    /// Return a pointer to the first (0-th index) element in the list
    ///
    /// # Safety
    ///
    /// Unsafe due to allow modification of elements possibly not inside the length.
    unsafe fn list_ptr(&mut self) -> *mut Self::Output;

    /// Return a pointer to the element next to the last element in the list
    ///
    /// # Safety
    ///
    /// Unsafe due to allow modification of elements possibly not inside the length.
    unsafe fn over_bounds_ptr(&mut self) -> *mut Self::Output;

    #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "avx2"))]
    /// Appends a number of moves from the bits of `dst` to the List, with the src SQ and
    /// flags. Returns a pointer to the next available square.
    ///
    /// # Notes
    ///
    /// This is an experimental feature, attempting to use SIMD to speed-up move generation.
    /// It proved slow, so as of now there is no use for it.
    ///
    /// # Safety,
    ///
    /// As it returns a raw pointer (and takes in one!), this method is completely unsafe to use.
    unsafe fn avx_append(ptr: *mut Self::Output, src: SQ, dst: &mut BitBoard, flags: u16) -> *mut Self::Output;
}

const MAX_MOVES: usize = 256;

/// This is the list of possible moves for a current position. Think of it alike a faster
/// version of `Vec<BitMove>`, as all the data is stored in the Stack rather than the Heap.
pub struct MoveList {
    inner: [BitMove; 256],
    len: usize,
}

impl Default for MoveList {
    #[inline]
    fn default() -> Self {
        MoveList {
            inner: [BitMove::null(); 256],
            len: 0,
        }
    }
}

impl From<Vec<BitMove>> for MoveList {
    fn from(vec: Vec<BitMove>) -> Self {
        let mut list = MoveList::default();
        vec.iter().for_each(|m| list.push(*m));
        list
    }
}


impl From<ScoringMoveList> for MoveList {
    fn from(sc_list: ScoringMoveList) -> Self {
        let mut mv_list = MoveList::default();
        sc_list.iter().for_each(|m| mv_list.push(m.bitmove()));
        mv_list
    }
}

impl Into<Vec<BitMove>> for MoveList {
    #[inline]
    fn into(self) -> Vec<BitMove> {
        self.vec()
    }
}

impl MoveList {
    /// Adds a `BitMove` to the end of the list.
    ///
    /// # Safety
    ///
    /// If pushing to the list when at capacity, does nothing.
    #[inline(always)]
    pub fn push(&mut self, mv: BitMove) {
        self.push_mv(mv);
    }

    /// Returns true if empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use pleco::{BitMove,MoveList};
    ///
    /// let mut list = MoveList::default();
    /// assert!(list.is_empty());
    /// ```
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Creates a `Vec<BitMove>` from this `MoveList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use pleco::{BitMove,MoveList};
    ///
    /// let mut list = MoveList::default();
    /// list.push(BitMove::null());
    ///
    /// let vec: Vec<BitMove> = list.vec();
    /// ```
    pub fn vec(&self) -> Vec<BitMove> {
        let mut vec = Vec::with_capacity(self.len);
        for mov in self.iter() {
            vec.push(*mov);
        }
        assert_eq!(vec.len(),self.len);
        vec
    }

    /// Returns the number of moves inside the list.
    ///
    /// # Examples
    ///
    /// ```
    /// use pleco::{BitMove,MoveList};
    ///
    /// let mut list = MoveList::default();
    /// list.push(BitMove::null());
    /// list.push(BitMove::null());
    /// list.push(BitMove::null());
    /// assert_eq!(list.len(), 3);
    /// ```
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns the `MoveList` as a slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use pleco::{BitMove,MoveList};
    ///
    /// let mut list = MoveList::default();
    /// list.push(BitMove::null());
    ///
    /// let slice: &[BitMove] = list.as_slice();
    /// ```
    #[inline(always)]
    pub fn as_slice(&self) -> &[BitMove] {
        self
    }

    /// Returns the `MoveList` as a mutable slice.
    #[inline(always)]
    pub fn as_mut_slice(&mut self) -> &mut [BitMove] {
        self
    }
}


impl Deref for MoveList {
    type Target = [BitMove];

    #[inline]
    fn deref(&self) -> &[BitMove] {
        unsafe {
            let p = self.inner.as_ptr();
            slice::from_raw_parts(p, self.len)
        }
    }
}

impl DerefMut for MoveList {
    #[inline]
    fn deref_mut(&mut self) -> &mut [BitMove] {
        unsafe {
            let ptr = self.inner.as_mut_ptr();
            slice::from_raw_parts_mut(ptr, self.len)
        }
    }
}

impl Index<usize> for MoveList {
    type Output = BitMove;

    #[inline(always)]
    fn index(&self, index: usize) -> &BitMove {
        &(**self)[index]
    }
}

impl IndexMut<usize> for MoveList {
    #[inline(always)]
    fn index_mut(&mut self, index: usize) -> &mut BitMove {
        &mut (**self)[index]
    }
}


impl MVPushable for MoveList {
    #[inline(always)]
    fn push_mv(&mut self, mv: BitMove) {
        if self.len() < MAX_MOVES {
            unsafe{ self.unchecked_push_mv(mv) }
        }
    }

    #[inline(always)]
    unsafe fn unchecked_push_mv(&mut self, mv: BitMove) {
        let end = self.inner.get_unchecked_mut(self.len);
        *end = mv;
        self.len += 1;
    }

    #[inline(always)]
    unsafe fn unchecked_set_len(&mut self, len: usize) {
        self.len = len
    }

    #[inline(always)]
    unsafe fn list_ptr(&mut self) -> *mut BitMove {
        self.as_mut_ptr()
    }

    #[inline(always)]
    unsafe fn over_bounds_ptr(&mut self) -> *mut BitMove {
        self.as_mut_ptr().add(self.len)
    }


    #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "avx2"))]
    #[doc(hidden)]
    #[inline(always)]
    unsafe fn avx_append(mut ptr: *mut BitMove, src: SQ, dst: &mut BitBoard, flags: u16) -> *mut BitMove {
        let mut i = 0;
        let mut v = u16x32::splat(0);

        while let Some(dst_sq) = dst.pop_some_lsb() {
            v = v.replace_unchecked(i, dst_sq.0 as u16);
            i += 1;
        }

        if i != 0 {
            v <<= 6;
            v |= u16x32::splat(flags << 12 | src.0 as u16);
            for x in 0..i {
                *ptr = transmute(v.extract_unchecked(x));
                ptr = ptr.add(1);
            }
        }

        ptr
    }
}

pub struct MoveIter<'a> {
    movelist: &'a MoveList,
    idx: usize
}

impl<'a> Iterator for MoveIter<'a> {
    type Item = BitMove;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.idx >= self.movelist.len {
            None
        } else {
            unsafe {
                let m = *self.movelist.inner.get_unchecked(self.idx);
                self.idx += 1;
                Some(m)
            }

        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.movelist.len - self.idx, Some(self.movelist.len - self.idx))
    }
}

impl<'a> IntoIterator for &'a MoveList {
    type Item = BitMove;
    type IntoIter = MoveIter<'a>;

    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter {
        MoveIter {
            movelist: self,
            idx: 0,
        }
    }
}

impl<'a> ExactSizeIterator for MoveIter<'a> {}

impl<'a> FusedIterator for MoveIter<'a> {}

unsafe impl<'a> TrustedLen for MoveIter<'a> {}

// Iterator for the `MoveList`.
pub struct MoveIntoIter {
    movelist: MoveList,
    idx: usize
}

impl Iterator for MoveIntoIter {
    type Item = BitMove;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.idx >= self.movelist.len {
            None
        } else {
            unsafe {
                let m = *self.movelist.inner.get_unchecked(self.idx);
                self.idx += 1;
                Some(m)
            }

        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.movelist.len - self.idx, Some(self.movelist.len - self.idx))
    }
}

impl IntoIterator for MoveList {
    type Item = BitMove;
    type IntoIter = MoveIntoIter;

    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter {
        MoveIntoIter {
            movelist: self,
            idx: 0,
        }
    }
}

impl FromIterator<BitMove> for MoveList {
    fn from_iter<T: IntoIterator<Item=BitMove>>(iter: T) -> Self {
        let mut list = MoveList::default();
        for i in iter {
            list.push(i);
        }
        list
    }
}

impl ExactSizeIterator for MoveIntoIter {}

impl FusedIterator for MoveIntoIter {}

unsafe impl TrustedLen for MoveIntoIter {}


/// This is similar to a `MoveList`, but also keeps the scores for each move as well.
pub struct ScoringMoveList {
    inner: [ScoringMove; 256],
    len: usize,
}

impl Default for ScoringMoveList {
    #[inline]
    fn default() -> Self {
        ScoringMoveList {
            inner: [ScoringMove::default(); 256],
            len: 0,
        }
    }
}

impl From<Vec<BitMove>> for ScoringMoveList {
    fn from(vec: Vec<BitMove>) -> Self {
        let mut list = ScoringMoveList::default();
        vec.iter().for_each(|m| list.push(*m));
        list
    }
}

impl From<MoveList> for ScoringMoveList {
    fn from(mv_list: MoveList) -> Self {
        let mut sc_list = ScoringMoveList::default();
        mv_list.iter().for_each(|m| sc_list.push(*m));
        sc_list
    }
}

impl Into<Vec<ScoringMove>> for ScoringMoveList {
    #[inline]
    fn into(self) -> Vec<ScoringMove> {
        self.vec()
    }
}

impl ScoringMoveList {
    /// Adds a `BitMove` to the end of the list.
    ///
    /// # Safety
    ///
    /// If pushing to the list when at capacity, does nothing.
    #[inline(always)]
    pub fn push(&mut self, mov: BitMove) {
        self.push_mv(mov)
    }

    /// Returns true if empty.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Creates a vector from this `MoveList`.
    pub fn vec(&self) -> Vec<ScoringMove> {
        let mut vec = Vec::with_capacity(self.len);
        for pair in self.iter() {
            vec.push(*pair);
        }
        assert_eq!(vec.len(),self.len);
        vec
    }

    /// Pushes a `BitMove` and a score to the list.
    ///
    /// Unlike a normal score, which is a `i32`, the score pushed is of a type `i16`.
    #[inline(always)]
    pub fn push_score(&mut self, mov: BitMove, score: i16) {
        if self.len < MAX_MOVES {
            unsafe {
                self.push_score_unchecked(mov, score);
            }
        }
    }

    #[inline(always)]
    pub unsafe fn push_score_unchecked(&mut self, mov: BitMove, score: i16) {
        let end = self.inner.get_unchecked_mut(self.len);
        *end = ScoringMove::new_score(mov, score);
        self.len += 1;
    }

    /// Returns the number of moves inside the list.
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns the `ScoringMoveList` as a slice.
    #[inline(always)]
    pub fn as_slice(&self) -> &[ScoringMove] {
        self
    }

    /// Returns the `ScoringMoveList` as a mutable slice.
    #[inline(always)]
    pub fn as_mut_slice(&mut self) -> &mut [ScoringMove] {
        self
    }
}


impl Deref for ScoringMoveList {
    type Target = [ScoringMove];

    #[inline]
    fn deref(&self) -> &[ScoringMove] {
        unsafe {
            let p = self.inner.as_ptr();
            slice::from_raw_parts(p, self.len)
        }
    }
}

impl DerefMut for ScoringMoveList {
    #[inline]
    fn deref_mut(&mut self) -> &mut [ScoringMove] {
        unsafe {
            let ptr = self.inner.as_mut_ptr();
            slice::from_raw_parts_mut(ptr, self.len)
        }
    }
}

impl Index<usize> for ScoringMoveList {
    type Output = ScoringMove;

    #[inline(always)]
    fn index(&self, index: usize) -> &ScoringMove {
        &(**self)[index]
    }
}

impl IndexMut<usize> for ScoringMoveList {
    #[inline(always)]
    fn index_mut(&mut self, index: usize) -> &mut ScoringMove {
        &mut (**self)[index]
    }
}

impl MVPushable for ScoringMoveList {
    #[inline(always)]
    fn push_mv(&mut self, mv: BitMove) {
        if self.len() < MAX_MOVES {
            unsafe{ self.unchecked_push_mv(mv) }
        }
    }

    #[inline(always)]
    unsafe fn unchecked_push_mv(&mut self, mv: BitMove) {
        let end = self.inner.get_unchecked_mut(self.len);
        *end = ScoringMove::new(mv);
        self.len += 1;
    }


    #[inline(always)]
    unsafe fn unchecked_set_len(&mut self, len: usize) {
        self.len = len
    }

    #[inline(always)]
    unsafe fn list_ptr(&mut self) -> *mut ScoringMove {
        self.as_mut_ptr()
    }

    #[inline(always)]
    unsafe fn over_bounds_ptr(&mut self) -> *mut ScoringMove {
        self.as_mut_ptr().add(self.len)
    }

    #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "avx2"))]
    #[doc(hidden)]
    #[inline(always)]
    unsafe fn avx_append(mut ptr: *mut ScoringMove, src: SQ, dst: &mut BitBoard, flags: u16) -> *mut ScoringMove {
        let mut i = 0;
        let mut v = u16x32::splat(0);
        while let Some(dst_sq) = dst.pop_some_lsb() {
            v = v.replace_unchecked(i, dst_sq.0 as u16);
            i += 1;
        }

        if i != 0 {
            v *= u16x32::splat(64);
            v |= u16x32::splat(flags << 12 | src.0 as u16);

            for x in 0..i {
                (*ptr).bit_move = transmute(v.extract_unchecked(x));
                ptr = ptr.add(1);
            }
        }
        ptr
    }
}

pub struct ScoreMoveIter<'a> {
    movelist: &'a ScoringMoveList,
    idx: usize
}

impl<'a> Iterator for ScoreMoveIter<'a> {
    type Item = ScoringMove;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.idx >= self.movelist.len {
            None
        } else {
            unsafe {
                let m = *self.movelist.inner.get_unchecked(self.idx);
                self.idx += 1;
                Some(m)
            }

        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.movelist.len - self.idx, Some(self.movelist.len - self.idx))
    }
}

impl<'a> IntoIterator for &'a ScoringMoveList {
    type Item = ScoringMove;
    type IntoIter = ScoreMoveIter<'a>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        ScoreMoveIter {
            movelist: self,
            idx: 0,
        }
    }
}

impl<'a> ExactSizeIterator for ScoreMoveIter<'a> {}

impl<'a> FusedIterator for ScoreMoveIter<'a> {}

unsafe impl<'a> TrustedLen for ScoreMoveIter<'a> {}

// Iterator for the `ScoringMoveList`.
pub struct ScoreMoveIntoIter {
    movelist: ScoringMoveList,
    idx: usize
}

impl Iterator for ScoreMoveIntoIter {
    type Item = ScoringMove;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.idx >= self.movelist.len {
            None
        } else {
            unsafe {
                let m = *self.movelist.inner.get_unchecked(self.idx);
                self.idx += 1;
                Some(m)
            }

        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.movelist.len - self.idx, Some(self.movelist.len - self.idx))
    }
}

impl IntoIterator for ScoringMoveList {
    type Item = ScoringMove;
    type IntoIter = ScoreMoveIntoIter;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        ScoreMoveIntoIter {
            movelist: self,
            idx: 0,
        }
    }
}

impl FromIterator<BitMove> for ScoringMoveList {
    fn from_iter<T: IntoIterator<Item=BitMove>>(iter: T) -> Self {
        let mut list = ScoringMoveList::default();
        for i in iter {
            list.push(i);
        }
        list
    }
}

impl ExactSizeIterator for ScoreMoveIntoIter {}

impl FusedIterator for ScoreMoveIntoIter {}

unsafe impl TrustedLen for ScoreMoveIntoIter {}

#[cfg(test)]
#[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), target_feature = "avx2"))]
mod tests {
    use super::*;

    #[test]
    fn check_avx2() {
        let mut arr = [BitMove::null(); 16];
        let mut bb = BitBoard::FILE_B;
        unsafe {
            MoveList::avx_append(arr.as_mut_ptr(), SQ::A1, &mut bb, 0b1111);
        }
    }
}