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
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
//! This is a library for pushing pixels on the CPU.
//!
//! It uses SIMD where possible, so it's pretty fast. Run the benchmarks to
//! decide if it's fast enough for your use-case. The intent is more for smaller
//! resolution situations like a retro console would have, but you _can_ do
//! 1080p if you want. Even _without_ SIMD the indexed color mode at least can
//! run at basically any resolution you want.
//!
//! Note that this library _will not_ put your pixels on the screen itself. You
//! still have to use a GPU library of some sort to get stuff displayed.
//! Examples are provided of how you might do that with `glutin` and `gl`, but
//! you're free to use anything else if you want.
//!
//! All of the real work is done via traits, and you can create image slices to
//! wrap around your existing image data. This allows you to quickly connect the
//! library onto your existing image types if you need to. If you don't have
//! existing image types, there is a `VecImage` type provided. There's also an
//! example of an array-backed type, allowing you to use the library in a
//! `no_std` situation (requires nightly). In the future, it's hoped that this
//! library will include feature flags to automatically support other crates,
//! but not yet.

#![cfg_attr(not(feature = "std"), no_std)]
// we need this to sqrt without std (alternately, SIMD)
#![cfg_attr(not(feature = "std"), feature(core_intrinsics))]
#![forbid(missing_debug_implementations)]
#![warn(missing_docs)]
//#![allow(dead_code)]
//#![allow(unused_imports)]

#[cfg(feature = "std")]
extern crate core;
use core::marker::PhantomData;
use core::mem::swap;
pub(crate) use core::ops::*;

#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;

pub(crate) const SSE_LANE_WIDTH: usize = 4;
pub(crate) const SSE_LANE_WIDTH_I: isize = SSE_LANE_WIDTH as isize;

pub(crate) const AVX_LANE_WIDTH: usize = 8;
pub(crate) const AVX_LANE_WIDTH_I: isize = AVX_LANE_WIDTH as isize;

#[cfg(not(feature = "std"))]
pub(crate) fn sqrt(f: f32) -> f32 {
  unsafe { ::core::intrinsics::sqrtf32(f) }
}
#[cfg(feature = "std")]
pub(crate) fn sqrt(f: f32) -> f32 {
  f.sqrt()
}

#[cfg(not(feature = "std"))]
pub(crate) fn square(f: f32) -> f32 {
  f * f // same ASM as `f.powi(2)`, i checked
}
#[cfg(feature = "std")]
pub(crate) fn square(f: f32) -> f32 {
  f.powi(2)
}

#[macro_use]
pub mod macros;
pub use macros::*;

pub mod palettes;
pub use palettes::*;

pub mod u16_ext;
pub use u16_ext::*;

pub mod u32_ext;
pub use u32_ext::*;

/// Trait for anything that can be read as if it was an image.
///
/// An image is here defined as being a `height` long series of "pixel" slices
/// (each `width` in length) that are evenly spaced out by a particular `pitch`
/// value (the offset from the start of one slice to the start of the next
/// slice). The type of data held in a pixel often doesn't matter, most
/// operations don't examine the data itself. Things that do examine the data
/// use "where" bounds so that they are always appropriate to the pixel type.
pub trait ReadableImage<P>: Index<(usize, usize), Output = P> {
  /// Can't exceed `isize::MAX`
  fn width(&self) -> usize;

  /// Can't exceed `isize::MAX`
  fn height(&self) -> usize;

  /// Offset from the start of one row to the start of the next row.
  fn pitch(&self) -> isize;

  /// Raw const pointer to the data.
  fn as_ptr(&self) -> *const P;

  /// Performs an optional indexing by reference, gives `None` for out of bounds.
  fn get(&self, loc: (usize, usize)) -> Option<&P> {
    if loc.0 < self.width() && loc.1 < self.height() {
      Some(&self[loc])
    } else {
      None
    }
  }

  /// Grabs out a sub-slice of the data.
  ///
  /// # Panics
  ///
  /// If either end of the requested portion is out of bounds.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let vi: VecImage<u8> = VecImage::new(10,15);
  ///
  /// let whole_slice = vi.slice( (0,0) .. (vi.width(),vi.height()) );
  /// assert_eq!(whole_slice.width(), vi.width());
  /// assert_eq!(whole_slice.height(), vi.height());
  /// assert_eq!(whole_slice.pitch(), vi.pitch());
  /// assert_eq!(whole_slice.as_ptr(), vi.as_ptr());
  ///
  /// let partial_slice = whole_slice.slice( (3,3) .. (7,8) );
  /// assert_eq!(partial_slice.width(), 4);
  /// assert_eq!(partial_slice.height(), 5);
  /// assert_eq!(partial_slice.pitch(), vi.pitch());
  /// assert_eq!(partial_slice.as_ptr(), unsafe { vi.as_ptr().offset(3 + (3 * vi.pitch())) } );
  /// ```
  fn slice(&self, r: Range<(usize, usize)>) -> ImageSlice<P> {
    // TODO: better explanation in the docs.
    let r = (r.start.0.min(r.end.0), r.start.1.min(r.end.1))..(r.start.0.max(r.end.0), r.start.1.max(r.end.1));
    if r.end.0 <= self.width() && r.end.1 <= self.height() && r.start.0 < r.end.0 && r.start.1 < r.end.1 {
      let width = r.end.0 - r.start.0;
      let height = r.end.1 - r.start.1;
      let ptr = unsafe { self.as_ptr().offset(r.start.0 as isize + (r.start.1 as isize * self.pitch())) };
      let pitch = self.pitch();
      ImageSlice {
        width,
        height,
        ptr,
        pitch,
        _marker: PhantomData,
      }
    } else {
      panic!(
        "ReadableImage::slice Out Of Bounds: Requested: {:?}, Actual: {:?}",
        r,
        (self.width(), self.height())
      );
    }
  }

  /// Lets you iterate any image by reference.
  fn iter(&self) -> ImageRefIter<P> {
    // TODO: split `iter` concept (pixels only) and `enumerate_pixels` (location + pixel)
    ImageRefIter {
      ptr: self.as_ptr(),
      next_x: 0,
      next_y: 0,
      width: self.width(),
      height: self.height(),
      pitch: self.pitch(),
      _marker: PhantomData,
    }
  }

  /// This is like `to_owned`, you get your own version of the data.
  ///
  /// The actual `ToOwned` trait has some conflicts because we're not using
  /// normal references, so we just have this instead.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let mut source: VecImage<u8> = VecImage::new(5,5);
  /// let a = source.to_vecimage();
  /// let b = source.slice((0,0)..(5,5)).to_vecimage();
  /// let c = source.slice_mut((0,0)..(5,5)).to_vecimage();
  ///
  /// assert_eq!(a, b);
  /// assert_eq!(a, c);
  /// ```
  #[cfg(feature = "std")]
  fn to_vecimage(&self) -> VecImage<P>
  where
    Self: Sized,
    P: Default + Clone,
  {
    let mut output = VecImage::new(self.width(), self.height());
    for (x, y, r) in self.iter() {
      output[(x, y)] = (*r).clone();
    }
    output
  }

  /// Scales up into a new `VecImage` by the given amount.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let mut source = VecImage::new(2,2);
  /// source[(0,1)] = 5u8;
  ///
  /// let scaled = source.upscale(2);
  ///
  /// for (x,y,&p) in scaled.iter() {
  ///   match (x,y) {
  ///     (0,2) | (0,3) | (1,2) | (1,3) => assert_eq!(p, 5),
  ///     _ => assert_eq!(p, 0),
  ///   }
  /// }
  /// ```
  #[cfg(feature = "std")]
  fn upscale(&self, scale: usize) -> VecImage<P>
  where
    P: Copy + Default,
  {
    let mut output = VecImage::new(self.width() * scale, self.height() * scale);
    for (x, y, &p) in self.iter() {
      for y_sub in 0..scale {
        for x_sub in 0..scale {
          output[(x * scale + x_sub, y * scale + y_sub)] = p;
        }
      }
    }
    output
  }

  // TODO: iter_scanlines
}

/// The trait for anything that can be written to as if it was an image.
pub trait WritableImage<P>: ReadableImage<P> + IndexMut<(usize, usize), Output = P> {
  /// Raw mut pointer to the data.
  fn as_mut_ptr(&mut self) -> *mut P;

  /// Performs an optional indexing by mut reference, gives `None` for out of bounds.
  fn get_mut(&mut self, loc: (usize, usize)) -> Option<&mut P> {
    // TODO: doc-tests
    if loc.0 < self.width() && loc.1 < self.height() {
      Some(&mut self[loc])
    } else {
      None
    }
  }

  /// Grabs out a mutable sub-slice of the data.
  ///
  /// # Panics
  ///
  /// If either end of the requested portion is out of bounds.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let width = 10;
  /// let height = 15;
  /// let mut vi: VecImage<u8> = VecImage::new(width,height);
  /// let base_ptr = vi.as_ptr();
  /// let base_pitch = vi.pitch();
  ///
  /// let mut whole_slice = vi.slice_mut( (0,0) .. (width,height) );
  /// assert_eq!(whole_slice.width(), width);
  /// assert_eq!(whole_slice.height(), height);
  /// assert_eq!(whole_slice.pitch(), base_pitch);
  /// assert_eq!(whole_slice.as_ptr(), base_ptr);
  ///
  /// let partial_slice = whole_slice.slice_mut( (3,3) .. (7,8) );
  /// assert_eq!(partial_slice.width(), 4);
  /// assert_eq!(partial_slice.height(), 5);
  /// assert_eq!(partial_slice.pitch(), base_pitch);
  /// assert_eq!(partial_slice.as_ptr(), unsafe { base_ptr.offset(3 + (3 * base_pitch)) } );
  /// ```
  fn slice_mut(&mut self, r: Range<(usize, usize)>) -> ImageMutSlice<P> {
    // TODO: better doc explanations
    let r = (r.start.0.min(r.end.0), r.start.1.min(r.end.1))..(r.start.0.max(r.end.0), r.start.1.max(r.end.1));
    if r.end.0 <= self.width() && r.end.1 <= self.height() && r.start.0 < r.end.0 && r.start.1 < r.end.1 {
      let width = r.end.0 - r.start.0;
      let height = r.end.1 - r.start.1;
      let ptr = unsafe { self.as_mut_ptr().offset(r.start.0 as isize + (r.start.1 as isize * self.pitch())) };
      let pitch = self.pitch();
      ImageMutSlice {
        width,
        height,
        ptr,
        pitch,
        _marker: PhantomData,
      }
    } else {
      panic!(
        "WritableImage::slice_mut Out Of Bounds: Requested: {:?}, Actual: {:?}",
        r,
        (self.width(), self.height())
      );
    }
  }

  /// Lets you mutably iterate over any writable form of image.
  fn iter_mut(&mut self) -> ImageMutRefIter<P> {
    // TODO: split `iter_mut` concept from `enumerate_pixels_mut`
    ImageMutRefIter {
      ptr: self.as_mut_ptr(),
      next_x: 0,
      next_y: 0,
      width: self.width(),
      height: self.height(),
      pitch: self.pitch(),
      _marker: PhantomData,
    }
  }

  /// Assigns all locations to be the given pixel value.
  fn set_all(&mut self, pixel: P)
  where
    P: Clone,
  {
    // TODO: doc-tests
    for (_x, _y, mut_ref) in self.iter_mut() {
      *mut_ref = pixel.clone();
    }
  }

  /// Directly copies the data from the source image into this image.
  ///
  /// The source image is copied in at the offset given. The resulting region is
  /// automatically clipped to stay within bounds, and you can even specify a
  /// negative offset if you like.
  ///
  /// Because of rust's lifetime rules, and because absolutely no special
  /// processing happens when moving the data between the two images, this just
  /// does a byte-wise `copy_nonoverlapping` operation, so it's pretty zippy.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let mut dest = VecImage::new(5,5);
  /// let mut src = VecImage::new(2,3);
  /// src.set_all(3u8);
  /// src[(0,2)] = 5;
  /// src[(1,2)] = 5;
  ///
  /// dest.direct_copy(&src, (1,-1));
  ///
  /// for y in 0 .. dest.height() {
  ///   for x in 0 .. dest.width() {
  ///     match (x,y) {
  ///       (1,0) | (2,0) => assert_eq!(dest[(x,y)], 3),
  ///       (1,1) | (2,1) => assert_eq!(dest[(x,y)], 5),
  ///       _ => assert_eq!(dest[(x,y)], 0),
  ///     }
  ///   }
  /// }
  /// ```
  fn direct_copy<S>(&mut self, src: &S, offset: (isize, isize))
  where
    S: ReadableImage<P>,
    P: Copy,
  {
    // TODO: determine_overlay!
    let offset_x = offset.0;
    let offset_y = offset.1;
    let self_width = self.width() as isize;
    let self_height = self.height() as isize;
    let src_width = src.width() as isize;
    let src_height = src.height() as isize;
    // establish that we should be drawing something at all
    if offset_x < self_width && offset_y < self_height && -offset_x < src_width && -offset_y < src_height {
      // determine where we'll be copying
      let dest_start_x = (offset_x).max(0);
      let dest_start_y = (offset_y).max(0);
      let src_start_x = (-offset_x).max(0);
      let src_start_y = (-offset_y).max(0);
      let clip_width = (self_width - dest_start_x).min(src_width - src_start_x);
      let clip_height = (self_height - dest_start_y).min(src_height - src_start_y);
      if clip_width > 0 && clip_height > 0 {
        unsafe {
          let dest_pitch = self.pitch();
          let mut dest_ptr = self.as_mut_ptr().offset(dest_start_y * dest_pitch + dest_start_x);
          let src_pitch = src.pitch();
          let mut src_ptr = src.as_ptr().offset(src_start_y * src_pitch + src_start_x);
          let clip_width = clip_width as usize;
          let clip_height = clip_height as usize;
          let mut y = 0;
          while y < clip_height {
            ::core::ptr::copy_nonoverlapping(src_ptr, dest_ptr, clip_width);
            src_ptr = src_ptr.offset(src_pitch);
            dest_ptr = dest_ptr.offset(dest_pitch);
            y += 1;
          }
        }
      }
    }
  }

  /// Flips the image vertically.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let mut im = VecImage::new(2,2);
  /// im[(0,0)] = 5u8;
  /// im[(1,0)] = 5;
  ///
  /// im.flip_vertical();
  ///
  /// assert_eq!(im[(0,0)], 0);
  /// assert_eq!(im[(1,0)], 0);
  /// assert_eq!(im[(0,1)], 5);
  /// assert_eq!(im[(1,1)], 5);
  /// ```
  fn flip_vertical(&mut self) {
    unsafe {
      let swap_count = self.height() / 2;
      let pitch = self.pitch();
      let width = self.width();
      let mut low_ptr = self.as_mut_ptr();
      let mut high_ptr = self.as_mut_ptr().offset(pitch * (self.height() as isize - 1));
      let mut y = 0;
      while y < swap_count {
        let mut x = 0;
        let mut low_ptr_row = low_ptr;
        let mut high_ptr_row = high_ptr;
        while x < width {
          swap(&mut *low_ptr_row, &mut *high_ptr_row);
          low_ptr_row = low_ptr_row.offset(1);
          high_ptr_row = high_ptr_row.offset(1);
          x += 1;
        }
        y += 1;
        low_ptr = low_ptr.offset(pitch);
        high_ptr = high_ptr.offset(-pitch);
      }
    }
  }

  /// Flips the image horizontally.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let mut im = VecImage::new(2,2);
  /// im[(0,0)] = 5u8;
  /// im[(0,1)] = 5;
  ///
  /// im.flip_horizontal();
  ///
  /// assert_eq!(im[(0,0)], 0);
  /// assert_eq!(im[(1,0)], 5);
  /// assert_eq!(im[(0,1)], 0);
  /// assert_eq!(im[(1,1)], 5);
  /// ```
  fn flip_horizontal(&mut self) {
    unsafe {
      let pitch = self.pitch();
      let width = self.width();
      let height = self.height();
      let mut ptr = self.as_mut_ptr();
      let mut y = 0;
      while y < height {
        ::core::slice::from_raw_parts_mut(ptr, width).reverse();
        y += 1;
        ptr = ptr.offset(pitch);
      }
    }
  }

  /// Performs a 90 degrees counter-clockwise rotation, in place.
  ///
  /// # Failure
  ///
  /// The method simply fails with a `None` return if the image isn't square.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let mut im = VecImage::new(3,3);
  /// im[(0,0)] = 5u8;
  /// im[(2,0)] = 6;
  /// im[(2,2)] = 7;
  /// im[(0,2)] = 8;
  ///
  /// assert!(im.inplace_counterclockwise90_square().is_some());
  /// assert_eq!(im[(0,0)], 8);
  /// assert_eq!(im[(2,0)], 5);
  /// assert_eq!(im[(2,2)], 6);
  /// assert_eq!(im[(0,2)], 7);
  ///
  /// assert!(im.slice_mut((0,0)..(3,2)).inplace_counterclockwise90_square().is_none());
  /// ```
  fn inplace_counterclockwise90_square(&mut self) -> Option<()> {
    if self.width() == self.height() {
      unsafe {
        let base_ptr = self.as_mut_ptr();
        let n = self.width() as isize;
        let mut x = 0isize;
        while x < n / 2 {
          let mut y = x;
          while y < n - x - 1 {
            let a = base_ptr.offset((x) as isize + ((y) as isize * self.pitch())).as_mut().unwrap();
            let b = base_ptr.offset((y) as isize + ((n - 1 - x) as isize * self.pitch())).as_mut().unwrap();
            let c = base_ptr
              .offset((n - 1 - x) as isize + ((n - 1 - y) as isize * self.pitch()))
              .as_mut()
              .unwrap();
            let d = base_ptr.offset((n - 1 - y) as isize + ((x) as isize * self.pitch())).as_mut().unwrap();
            ::core::mem::swap(a, b);
            ::core::mem::swap(b, d);
            ::core::mem::swap(c, b);
            //
            y += 1;
          }
          x += 1
        }
        Some(())
      }
    } else {
      None
    }
  }

  /// Modifies this image by overlaying the source image at the offset given.
  ///
  /// For each pixel of overlap between `src` and `dest`, the closure is called
  /// with `|src, dest|` as parameters, and the closure should return the result
  /// to write as the new value for `dest`.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let mut dest = VecImage::new(5,5);
  /// let mut src = VecImage::new(2,3);
  /// dest.set_all(1u8);
  /// src.set_all(3u8);
  /// src[(0,2)] = 5;
  /// src[(1,2)] = 5;
  ///
  /// dest.blit_generic(&src, (1,-1), |src,dest| src+dest );
  ///
  /// for y in 0 .. dest.height() {
  ///   for x in 0 .. dest.width() {
  ///     match (x,y) {
  ///       (1,0) | (2,0) => assert_eq!(dest[(x,y)], 4),
  ///       (1,1) | (2,1) => assert_eq!(dest[(x,y)], 6),
  ///       _ => assert_eq!(dest[(x,y)], 1),
  ///     }
  ///   }
  /// }
  /// ```
  fn blit_generic<RI, F>(&mut self, src: &RI, offset: (isize, isize), op: F)
  where
    RI: ReadableImage<P>,
    F: FnMut(P, P) -> P,
    P: Copy,
  {
    // TODO: make this use the `determine_overlay!` macro.
    // TODO: try and think about if we can relax the bounds on `P`
    let mut op = op;
    let offset_x = offset.0;
    let offset_y = offset.1;
    let self_width = self.width() as isize;
    let self_height = self.height() as isize;
    let src_width = src.width() as isize;
    let src_height = src.height() as isize;
    // establish that we should be drawing something at all
    if offset_x < self_width && offset_y < self_height && -offset_x < src_width && -offset_y < src_height {
      // determine where we'll be copying
      let dest_start_x = (offset_x).max(0);
      let dest_start_y = (offset_y).max(0);
      let src_start_x = (-offset_x).max(0);
      let src_start_y = (-offset_y).max(0);
      let clip_width = (self_width - dest_start_x).min(src_width - src_start_x);
      let clip_height = (self_height - dest_start_y).min(src_height - src_start_y);
      if clip_width > 0 && clip_height > 0 {
        unsafe {
          let dest_pitch = self.pitch();
          let mut dest_ptr = self.as_mut_ptr().offset(dest_start_y * dest_pitch + dest_start_x);
          let src_pitch = src.pitch();
          let mut src_ptr = src.as_ptr().offset(src_start_y * src_pitch + src_start_x);
          let clip_width = clip_width as usize;
          let clip_height = clip_height as usize;
          let mut y = 0;
          while y < clip_height {
            let mut x = 0;
            let mut src_ptr_this_row = src_ptr;
            let mut dest_ptr_this_row = dest_ptr;
            while x < clip_width {
              *dest_ptr_this_row = op(*src_ptr_this_row, *dest_ptr_this_row);
              src_ptr_this_row = src_ptr_this_row.offset(1);
              dest_ptr_this_row = dest_ptr_this_row.offset(1);
              x += 1;
            }
            src_ptr = src_ptr.offset(src_pitch);
            dest_ptr = dest_ptr.offset(dest_pitch);
            y += 1;
          }
        }
      }
    }
  }
}

// // // // //
// Slice Types
// // // // //

/// A shared view of some image data.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ImageSlice<'a, P: 'a> {
  width: usize,
  height: usize,
  pitch: isize,
  ptr: *const P,
  _marker: PhantomData<&'a P>,
}

impl<'a, P: 'a> ImageSlice<'a, P> {
  /// Makes an image slice from the base parts.
  ///
  /// Absolutely no checks are performed, you must not lie to this method.
  pub unsafe fn from_raw_parts(width: usize, height: usize, pitch: isize, ptr: *const P) -> Self {
    ImageSlice {
      width,
      height,
      pitch,
      ptr,
      _marker: PhantomData,
    }
  }

  // TODO: From Slice
}

impl<'a, P: 'a> Index<(usize, usize)> for ImageSlice<'a, P> {
  type Output = P;
  // TODO: doc-tests
  fn index(&self, (x, y): (usize, usize)) -> &Self::Output {
    assert!(x < self.width);
    assert!(y < self.height);
    unsafe { self.ptr.offset(x as isize + (y as isize * self.pitch())).as_ref().unwrap() }
  }
}

impl<'a, P: 'a> ReadableImage<P> for ImageSlice<'a, P> {
  fn width(&self) -> usize {
    self.width
  }
  fn height(&self) -> usize {
    self.height
  }
  fn pitch(&self) -> isize {
    self.pitch
  }
  fn as_ptr(&self) -> *const P {
    self.ptr
  }
}

/// A mutable sub-view of some image data.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ImageMutSlice<'a, P: 'a> {
  width: usize,
  height: usize,
  pitch: isize,
  ptr: *mut P,
  _marker: PhantomData<&'a mut P>,
}

impl<'a, P: 'a> ImageMutSlice<'a, P> {
  /// Makes a mutable image slice from the base parts.
  ///
  /// Absolutely no checks are performed, you must not lie to this method.
  pub unsafe fn from_raw_parts(width: usize, height: usize, pitch: isize, ptr: *mut P) -> Self {
    ImageMutSlice {
      width,
      height,
      pitch,
      ptr,
      _marker: PhantomData,
    }
  }

  // TODO: From Mut Slice
}

impl<'a, P: 'a> Index<(usize, usize)> for ImageMutSlice<'a, P> {
  type Output = P;
  // TODO: doc-tests
  fn index(&self, (x, y): (usize, usize)) -> &Self::Output {
    assert!(x < self.width);
    assert!(y < self.height);
    unsafe { self.ptr.offset(x as isize + (y as isize * self.pitch())).as_ref().unwrap() }
  }
}

impl<'a, P: 'a> ReadableImage<P> for ImageMutSlice<'a, P> {
  fn width(&self) -> usize {
    self.width
  }
  fn height(&self) -> usize {
    self.height
  }
  fn pitch(&self) -> isize {
    self.pitch
  }
  fn as_ptr(&self) -> *const P {
    self.ptr
  }
}

impl<'a, P: 'a> IndexMut<(usize, usize)> for ImageMutSlice<'a, P> {
  // TODO: doc-tests
  fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Self::Output {
    assert!(x < self.width);
    assert!(y < self.height);
    unsafe { self.ptr.offset(x as isize + (y as isize * self.pitch())).as_mut().unwrap() }
  }
}

impl<'a, P: 'a> WritableImage<P> for ImageMutSlice<'a, P> {
  fn as_mut_ptr(&mut self) -> *mut P {
    self.ptr
  }
}
impl<'a> WritableImageU16Ext for ImageMutSlice<'a, u16> {}
impl<'a> WritableImageU32Ext for ImageMutSlice<'a, u32> {}

// // // // //
// Iterators
// // // // //

/// A struct that iterates over pixels of an `Image` by reference.
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct ImageRefIter<'a, P: 'a> {
  ptr: *const P,
  next_x: usize,
  next_y: usize,
  width: usize,
  height: usize,
  pitch: isize,
  _marker: PhantomData<&'a P>,
}

impl<'a, P: 'a> Iterator for ImageRefIter<'a, P> {
  /// (x, y, pixel_ref)
  type Item = (usize, usize, &'a P);

  /// Provides the output, once `None` is seen you'll never see more output.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let image = VecImage::from_vec(2,2,vec![1,2,3,4]);
  /// let mut iter = image.iter();
  /// assert_eq!(iter.next(), Some((0,0,&1)));
  /// assert_eq!(iter.next(), Some((1,0,&2)));
  /// assert_eq!(iter.next(), Some((0,1,&3)));
  /// assert_eq!(iter.next(), Some((1,1,&4)));
  /// assert!(iter.next().is_none());
  /// ```
  fn next(&mut self) -> Option<Self::Item> {
    if self.next_y < self.height {
      let out = Some((self.next_x, self.next_y, unsafe { self.ptr.as_ref().unwrap() }));
      self.ptr = unsafe { self.ptr.offset(1) };
      self.next_x += 1;
      if self.next_x == self.width {
        self.ptr = unsafe { self.ptr.offset(self.pitch - (self.width as isize)) };
        self.next_x = 0;
        self.next_y += 1;
      }
      out
    } else {
      None
    }
  }

  /// Provides an accurate count of the remaining iterations.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let image: VecImage<u8> = VecImage::new(2, 2);
  /// let mut iter = image.iter();
  /// assert_eq!(iter.size_hint(), (4,Some(4)));
  /// iter.next();
  /// assert_eq!(iter.size_hint(), (3,Some(3)));
  /// iter.next();
  /// assert_eq!(iter.size_hint(), (2,Some(2)));
  /// iter.next();
  /// assert_eq!(iter.size_hint(), (1,Some(1)));
  /// iter.next();
  /// assert_eq!(iter.size_hint(), (0,Some(0)));
  /// ```
  fn size_hint(&self) -> (usize, Option<usize>) {
    let total = self.width * self.height;
    let used = self.next_y * self.width + self.next_x;
    let remaining = total.saturating_sub(used);
    (remaining, Some(remaining))
  }
}

impl<'a, P: 'a> IntoIterator for ImageSlice<'a, P> {
  /// (x, y, pixel_ref)
  type Item = (usize, usize, &'a P);

  type IntoIter = ImageRefIter<'a, P>;

  // TODO: doc-tests
  fn into_iter(self) -> Self::IntoIter {
    ImageRefIter {
      ptr: self.ptr,
      next_x: 0,
      next_y: 0,
      width: self.width,
      height: self.height,
      pitch: self.pitch,
      _marker: PhantomData,
    }
  }
}

/// A struct that iterates over pixels of an `Image` by mutable reference.
#[derive(Debug, PartialEq, Eq)]
pub struct ImageMutRefIter<'a, P: 'a> {
  ptr: *mut P,
  next_x: usize,
  next_y: usize,
  width: usize,
  height: usize,
  pitch: isize,
  _marker: PhantomData<&'a mut P>,
}

impl<'a, P: 'a> Iterator for ImageMutRefIter<'a, P> {
  /// (x, y, pixel_mut_ref)
  type Item = (usize, usize, &'a mut P);

  /// Provides the output, once `None` is seen you'll never see more output.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let mut image = VecImage::from_vec(2,2,vec![1,2,3,4]);
  /// let mut iter_mut = image.iter_mut();
  /// assert_eq!(iter_mut.next(), Some((0,0,&mut 1)));
  /// assert_eq!(iter_mut.next(), Some((1,0,&mut 2)));
  /// assert_eq!(iter_mut.next(), Some((0,1,&mut 3)));
  /// assert_eq!(iter_mut.next(), Some((1,1,&mut 4)));
  /// assert!(iter_mut.next().is_none());
  /// ```
  fn next(&mut self) -> Option<Self::Item> {
    if self.next_y < self.height {
      let out = Some((self.next_x, self.next_y, unsafe { self.ptr.as_mut().unwrap() }));
      self.ptr = unsafe { self.ptr.offset(1) };
      self.next_x += 1;
      if self.next_x == self.width {
        self.ptr = unsafe { self.ptr.offset(self.pitch - (self.width as isize)) };
        self.next_x = 0;
        self.next_y += 1;
      }
      out
    } else {
      None
    }
  }

  /// Provides an accurate count of the remaining iterations.
  ///
  /// ```rust
  /// use retro_pixel::*;
  /// let mut image: VecImage<u8> = VecImage::new(2, 2);
  /// let mut iter_mut = image.iter_mut();
  /// assert_eq!(iter_mut.size_hint(), (4,Some(4)));
  /// iter_mut.next();
  /// assert_eq!(iter_mut.size_hint(), (3,Some(3)));
  /// iter_mut.next();
  /// assert_eq!(iter_mut.size_hint(), (2,Some(2)));
  /// iter_mut.next();
  /// assert_eq!(iter_mut.size_hint(), (1,Some(1)));
  /// iter_mut.next();
  /// assert_eq!(iter_mut.size_hint(), (0,Some(0)));
  /// ```
  fn size_hint(&self) -> (usize, Option<usize>) {
    let total = self.width * self.height;
    let used = self.next_y * self.width + self.next_x;
    let remaining = total.saturating_sub(used);
    (remaining, Some(remaining))
  }
}

impl<'a, P: 'a> IntoIterator for ImageMutSlice<'a, P> {
  /// (x, y, pixel_mut_ref)
  type Item = (usize, usize, &'a mut P);

  type IntoIter = ImageMutRefIter<'a, P>;

  // TODO: doc-tests
  fn into_iter(self) -> Self::IntoIter {
    ImageMutRefIter {
      ptr: self.ptr,
      next_x: 0,
      next_y: 0,
      width: self.width,
      height: self.height,
      pitch: self.pitch,
      _marker: PhantomData,
    }
  }
}

// // // // //
// Vector Images
// // // // //

/// An image backed by a `Vec`.
///
/// Not available in `no_std`, obviously.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg(feature = "std")]
pub struct VecImage<P> {
  width: usize,
  height: usize,
  data: Vec<P>,
}

// TODO: IntoIterator

#[cfg(feature = "std")]
impl<P> VecImage<P> {
  /// Creates a VecImage of the given dimensions with the default value in all
  /// positions.
  pub fn new(width: usize, height: usize) -> Self
  where
    P: Default + Clone,
  {
    assert!(width < ::core::isize::MAX as usize);
    assert!(height < ::core::isize::MAX as usize);
    VecImage {
      width,
      height,
      data: vec![P::default(); width * height],
    }
  }

  /// Creates a VecImage from the given vector of pixels.
  pub fn from_vec(width: usize, height: usize, vec: Vec<P>) -> Self {
    assert!(width < ::core::isize::MAX as usize);
    assert!(height < ::core::isize::MAX as usize);
    assert!(width * height == vec.len());
    VecImage { width, height, data: vec }
  }
}

impl<P> Deref for VecImage<P> {
  type Target = [P];

  fn deref(&self) -> &Self::Target {
    &self.data
  }
}

#[cfg(feature = "std")]
impl<P> Index<(usize, usize)> for VecImage<P> {
  type Output = P;
  // TODO: doc-tests
  fn index(&self, (x, y): (usize, usize)) -> &Self::Output {
    assert!(x < self.width);
    assert!(y < self.height);
    &self.data[x + (y * self.width)]
  }
}

#[cfg(feature = "std")]
impl<P> ReadableImage<P> for VecImage<P> {
  fn width(&self) -> usize {
    self.width
  }
  fn height(&self) -> usize {
    self.height
  }
  fn pitch(&self) -> isize {
    self.width as isize
  }
  fn as_ptr(&self) -> *const P {
    self.data.as_ptr()
  }
}

#[cfg(feature = "std")]
impl<P> IndexMut<(usize, usize)> for VecImage<P> {
  // TODO: doc-tests
  fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Self::Output {
    assert!(x < self.width);
    assert!(y < self.height);
    &mut self.data[x + (y * self.width)]
  }
}

#[cfg(feature = "std")]
impl<P> WritableImage<P> for VecImage<P> {
  fn as_mut_ptr(&mut self) -> *mut P {
    self.data.as_mut_ptr()
  }
}
#[cfg(feature = "std")]
impl WritableImageU16Ext for VecImage<u16> {}
#[cfg(feature = "std")]
impl WritableImageU32Ext for VecImage<u32> {}

// // // // //
// Array Images
// // // // //

/// An image the size of an NES screen, backed by an array.
///
/// This is a fairly big thing to have on the stack (~61k), so go easy with it,
/// or stick it in a global somewhere.
#[derive(Clone)]
pub struct NESImage {
  data: [u8; NESImage::WIDTH * NESImage::HEIGHT],
}
impl ::core::fmt::Debug for NESImage {
  fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
    write!(f, "NESImage{{}}")
  }
}
impl NESImage {
  const WIDTH: usize = 256;
  const HEIGHT: usize = 240;
}
impl Default for NESImage {
  fn default() -> Self {
    NESImage {
      data: [0; NESImage::WIDTH * NESImage::HEIGHT],
    }
  }
}

impl Index<(usize, usize)> for NESImage {
  type Output = u8;
  fn index(&self, (x, y): (usize, usize)) -> &Self::Output {
    assert!(x < NESImage::WIDTH);
    assert!(y < NESImage::HEIGHT);
    &self.data[x + (y * NESImage::WIDTH)]
  }
}

impl ReadableImage<u8> for NESImage {
  fn width(&self) -> usize {
    NESImage::WIDTH
  }
  fn height(&self) -> usize {
    NESImage::HEIGHT
  }
  fn pitch(&self) -> isize {
    NESImage::WIDTH as isize
  }
  fn as_ptr(&self) -> *const u8 {
    self.data.as_ptr()
  }
}

impl IndexMut<(usize, usize)> for NESImage {
  fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Self::Output {
    assert!(x < NESImage::WIDTH);
    assert!(y < NESImage::HEIGHT);
    &mut self.data[x + (y * NESImage::WIDTH)]
  }
}

impl WritableImage<u8> for NESImage {
  fn as_mut_ptr(&mut self) -> *mut u8 {
    self.data.as_mut_ptr()
  }
}