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
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
//! Defines the `Image` container, with flexibly type-safe layout.
//!
//! Besides the main type, [`Image`], which is an owned buffer of particular layout there are some
//! supporting types that represent other ways in which layouts interact with buffers. Note that
//! the layout is flexible in the sense that it is up to the user to ultimately ensure correct
//! typing. The type definition will _help_ you by not providing the tools for strong types but
//! it's always _allowed_/_valid_ to refer to the same bytes by a different layout. This makes it
//! possible to use your own texel/pixel wrapper types regardless of the underlying byte
//! representation. Indeed, the byte buffer need not even represent a pixel matrix (but it's
//! advised, probably very common, and the only 'supported' use-case).
// Distributed under The MIT License (MIT)
//
// Copyright (c) 2019, 2020 The `image-rs` developers
use core::{fmt, ops};

use crate::buf::{buf, Buffer, Cog};
use crate::layout::{
    Bytes, Decay, DynLayout, Layout, Mend, Raster, RasterMut, SliceLayout, Take, TryMend,
};
use crate::texel::MAX_ALIGN;
use crate::{BufferReuseError, Texel, TexelBuffer};

pub use crate::stride::{StridedBufferMut, StridedBufferRef};

/// A container of allocated bytes, parameterized over the layout.
///
/// This type permits user defined layouts of any kind and does not unsafely depend on the validity
/// of the layouts. Correctness is achieved in the common case by discouraging methods that would
/// lead to a diverging size of the memory buffer and the layout. Hence, access to the image pixels
/// should not lead to panic unless an incorrectly implemented layout is used.
///
/// It possible to convert the layout to a less strictly typed one without reallocating the buffer.
/// For example, all standard layouts such as `Matrix` can be weakened to `DynLayout`. The reverse
/// can not be done unchecked but is possible with fallible conversions.
///
/// Indeed, the image can _arbitrarily_ change its own layout—different `ImageRef` and
/// `ImageMut` may even chose _conflicting layouts—and thus overwrite the content with completely
/// different types and layouts. This is intended to maximize the flexibility for users. In
/// complicated cases it could be hard for the type system to reflect the compatibility of a custom
/// pixel layout and a standard one. It is solely the user's responsibility to use the interface
/// sensibly. The _soundness_ of standard channel types (e.g. `u8` or `u32`) is not impacted by
/// this as any byte content is valid for them.
///
/// ## Examples
///
/// Initialize a matrix as computed `[u8; 4]` rga pixels:
///
/// ```
/// # fn test() -> Option<()> {
/// use image_texel::{Image, Matrix};
///
/// let mut image = Image::from(Matrix::<[u8; 4]>::with_width_and_height(400, 400));
///
/// image.shade(|x, y, rgba| {
///     rgba[0] = x as u8;
///     rgba[1] = y as u8;
///     rgba[3] = 0xff;
/// });
///
/// # Some(()) }
/// # let _ = test();
/// ```
///
/// # Design
///
/// Since a `Image` can not unsafely rely on the layout behaving correctly, direct accessors may
/// have suboptimal behaviour and perform a few (seemingly) redundant checks. More optimal, but
/// much more specialized, wrappers can be provided in other types that first reduce to a
/// first-party layout and byte buffer and then preserve this invariant by never calling
/// second/third-party code from traits. Some of these may be offered in this crate in the future.
///
/// Note also that `Image` provides fallible operations, some of them are meant to modify the
/// type. This can obviously not be performed in-place, in the manner with which it would be common
/// if the type did not change. Instead we approximate at least the result type by transferring the
/// buffer on success while leaving it unchanged in case of failure. An example signature for this is:
///
/// > [`fn mend<M>(&mut self, with: L::Item) -> Option<Image<M>>`][`mend`]
///
/// [`mend`]: #method.mend
#[derive(Clone, PartialEq, Eq)]
pub struct Image<Layout = Bytes> {
    inner: RawImage<Buffer, Layout>,
}

/// An owned or borrowed image, parameterized over the layout.
///
/// The buffer is either owned or _mutably_ borrowed from another `Image`. Some allocating methods
/// may lead to an implicit change from a borrowed to an owned buffer. These methods are documented
/// as performing a fallible allocation. Other method calls on the previously borrowing image will
/// afterwards no longer change the bytes of the image it was borrowed from.
///
/// FIXME: figure out if this is 'right' to expose in this crate.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct CopyOnGrow<'buf, Layout = Bytes> {
    inner: RawImage<Cog<'buf>, Layout>,
}

/// A read-only view of an image.
///
/// Note that this requires its underlying buffer to be highly aligned! For that reason it is not
/// possible to take a reference at an arbitrary number of bytes.
#[derive(Clone, PartialEq, Eq)]
pub struct ImageRef<'buf, Layout = &'buf Bytes> {
    inner: RawImage<&'buf buf, Layout>,
}

/// A writeable reference to an image buffer.
#[derive(PartialEq, Eq)]
pub struct ImageMut<'buf, Layout = &'buf mut Bytes> {
    inner: RawImage<&'buf mut buf, Layout>,
}

/// Describes an image coordinate.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Coord(pub u32, pub u32);

impl Coord {
    pub fn x(self) -> u32 {
        self.0
    }

    pub fn y(self) -> u32 {
        self.1
    }

    pub fn yx(self) -> (u32, u32) {
        (self.1, self.0)
    }

    pub fn xy(self) -> (u32, u32) {
        (self.0, self.1)
    }
}

/// Inner buffer implementation.
///
/// Not exposed to avoid leaking the implementation detail of the `Buf` type parameter. This allows
/// a single implementation for borrowed and owned buffers while keeping `buf`, `Cog` etc. private.
#[derive(Default, Clone, PartialEq, Eq)]
pub(crate) struct RawImage<Buf, Layout> {
    buffer: Buf,
    layout: Layout,
}

pub(crate) trait BufferLike: ops::Deref<Target = buf> {
    fn into_owned(self) -> Buffer;
    fn take(&mut self) -> Self;
}

pub(crate) trait BufferMut: BufferLike + ops::DerefMut {}

pub(crate) trait Growable: BufferLike {
    fn grow_to(&mut self, _: usize);
}

/// Image methods for all layouts.
impl<L: Layout> Image<L> {
    /// Create a new image for a specific layout.
    pub fn new(layout: L) -> Self {
        RawImage::<Buffer, L>::new(layout).into()
    }

    /// Create a new image with initial byte content.
    pub fn with_bytes(layout: L, bytes: &[u8]) -> Self {
        RawImage::with_contents(bytes, layout).into()
    }

    /// Create a new image with initial texel contents.
    ///
    /// The memory is reused as much as possible. If the layout is too large for the buffer then
    /// the remainder is filled up with zeroed bytes.
    pub fn with_buffer<T>(layout: L, bytes: TexelBuffer<T>) -> Self {
        RawImage::with_buffer(Bytes(0), bytes.into_inner())
            .with_layout(layout)
            .into()
    }

    /// Get a reference to those bytes used by the layout.
    pub fn as_bytes(&self) -> &[u8] {
        self.inner.as_bytes()
    }

    /// Get a mutable reference to those bytes used by the layout.
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        self.inner.as_bytes_mut()
    }

    /// If necessary, reallocate the buffer to fit the layout.
    ///
    /// Call this method after having mutated a layout with [`Image::layout_mut_unguarded`]
    /// whenever you are not sure that the layout did not grow. This will ensure the contract that
    /// the internal buffer is large enough for the layout.
    ///
    /// # Panics
    ///
    /// This method panics when the allocation of the new buffer fails.
    pub fn ensure_layout(&mut self) {
        self.inner.mutate_layout(|_| ());
    }

    /// Change the layer of the image.
    ///
    /// Reallocates the buffer when growing a layout. Call [`Image::fits`] to check this property.
    pub fn with_layout<M>(self, layout: M) -> Image<M>
    where
        M: Layout,
    {
        self.inner.with_layout(layout).into()
    }

    /// Decay into a image with less specific layout.
    ///
    /// See the [`Decay`] trait for an explanation of this operation.
    ///
    /// # Example
    ///
    /// The common layouts define ways to decay into a dynamically typed variant.
    ///
    /// ```
    /// # use image_texel::{Image, Matrix, layout};
    /// let matrix = Matrix::<u8>::with_width_and_height(400, 400);
    /// let image: Image<layout::Matrix<u8>> = Image::from(matrix);
    ///
    /// // to turn hide the `u8` type but keep width, height, texel layout
    /// let image: Image<layout::MatrixBytes> = image.decay();
    /// assert_eq!(image.layout().width(), 400);
    /// assert_eq!(image.layout().height(), 400);
    /// ```
    ///
    /// See also [`Image::mend`] and [`Image::try_mend`] for operations that reverse the effects.
    ///
    /// Can also be used to forget specifics of the layout, turning the image into a more general
    /// container type. For example, to use a uniform type as an allocated buffer waiting on reuse.
    ///
    /// ```
    /// # use image_texel::{Image, Matrix, layout};
    /// let matrix = Matrix::<u8>::with_width_and_height(400, 400);
    ///
    /// // Can always decay to a byte buffer.
    /// let bytes: Image = Image::from(matrix).decay();
    /// let _: &layout::Bytes = bytes.layout();
    /// ```
    ///
    /// [`Decay`]: ../layout/trait.Decay.html
    pub fn decay<M>(self) -> Image<M>
    where
        M: Decay<L>,
        M: Layout,
    {
        self.inner.decay().into()
    }

    /// Move the buffer into a new image.
    pub fn take(&mut self) -> Image<L>
    where
        L: Take,
    {
        self.inner.take().into()
    }

    /// Strengthen the layout of the image.
    ///
    /// See the [`Mend`] trait for an explanation of this operation.
    ///
    /// [`Mend`]: ../layout/trait.Mend.html
    pub fn mend<Item>(self, mend: Item) -> Image<Item::Into>
    where
        Item: Mend<L>,
        L: Take,
    {
        let new_layout = mend.mend(self.inner.layout());
        self.inner.reinterpret_unguarded(|_| new_layout).into()
    }

    /// Strengthen the layout of the image.
    ///
    /// See the [`Mend`] trait for an explanation of this operation.
    ///
    /// This is a fallible operation. In case of success returns `Ok` and the byte buffer of the
    /// image is moved into the result. When mending fails this method returns `Err` and the buffer
    /// is kept by this image.
    ///
    /// [`Mend`]: ../layout/trait.Mend.html
    pub fn try_mend<Item>(&mut self, mend: Item) -> Result<Image<Item::Into>, Item::Err>
    where
        Item: TryMend<L>,
        L: Take,
    {
        let new_layout = mend.try_mend(self.inner.layout())?;
        Ok(self
            .inner
            .take()
            .reinterpret_unguarded(|_| new_layout)
            .into())
    }
}

/// Image methods that do not require a layout.
impl<L> Image<L> {
    /// Check if the buffer could accommodate another layout without reallocating.
    pub fn fits(&self, other: &impl Layout) -> bool {
        self.inner.fits(other)
    }

    /// Get a reference to the unstructured bytes of the image.
    ///
    /// Note that this may return more bytes than required for the specific layout for various
    /// reasons. See also [`as_bytes`].
    ///
    /// [`as_bytes`]: #method.as_bytes
    pub fn as_capacity_bytes(&self) -> &[u8] {
        self.inner.as_capacity_bytes()
    }

    /// Get a mutable reference to the unstructured bytes of the image.
    ///
    /// Note that this may return more bytes than required for the specific layout for various
    /// reasons. See also [`as_bytes_mut`].
    ///
    /// [`as_bytes_mut`]: #method.as_bytes_mut
    pub fn as_capacity_bytes_mut(&mut self) -> &mut [u8] {
        self.inner.as_capacity_bytes_mut()
    }

    /// View this buffer as a slice of pixels.
    ///
    /// This reinterprets the bytes of the buffer. It can be used to view the buffer as any kind of
    /// pixel, regardless of its association with the layout. Use it with care.
    ///
    /// An alternative way to get a slice of texels when a layout has an inherent texel type is
    /// [`Self::as_slice`].
    pub fn as_texels<P>(&self, pixel: Texel<P>) -> &[P]
    where
        L: Layout,
    {
        pixel.cast_buf(self.inner.as_buf())
    }

    /// View this buffer as a slice of pixels.
    ///
    /// This reinterprets the bytes of the buffer. It can be used to view the buffer as any kind of
    /// pixel, regardless of its association with the layout. Use it with care.
    ///
    /// An alternative way to get a slice of texels when a layout has an inherent texel type is
    /// [`Self::as_mut_slice`].
    pub fn as_mut_texels<P>(&mut self, pixel: Texel<P>) -> &mut [P]
    where
        L: Layout,
    {
        pixel.cast_mut_buf(self.inner.as_mut_buf())
    }

    /// Get a reference to the layout.
    pub fn layout(&self) -> &L {
        self.inner.layout()
    }

    /// Get a mutable reference to the layout.
    ///
    /// Be mindful not to modify the layout to exceed the allocated size. This does not cause any
    /// unsoundness but might lead to panics when calling other methods.
    pub fn layout_mut_unguarded(&mut self) -> &mut L {
        self.inner.layout_mut_unguarded()
    }

    /// Get a view of this image.
    pub fn as_ref(&self) -> ImageRef<'_, &'_ L> {
        self.inner.borrow().into()
    }

    /// Get a view of this image, if the alternate layout fits.
    pub fn try_to_ref<M: Layout>(&self, layout: M) -> Option<ImageRef<'_, M>> {
        self.as_ref().with_layout(layout)
    }

    /// Get a mutable view of this image.
    pub fn as_mut(&mut self) -> ImageMut<'_, &'_ mut L> {
        self.inner.borrow_mut().into()
    }

    /// Get a mutable view under an alternate layout.
    pub fn to_mut<M: Layout>(&mut self, layout: M) -> ImageMut<'_, M> {
        self.inner.as_reinterpreted(layout).into()
    }

    /// Get a mutable view of this image, if the alternate layout fits.
    pub fn try_to_mut<M: Layout>(&mut self, layout: M) -> Option<ImageMut<'_, M>> {
        self.as_mut().with_layout(layout)
    }

    /// Get a single texel from a raster image.
    pub fn get_texel<P>(&self, coord: Coord) -> Option<P>
    where
        L: Raster<P>,
    {
        L::get(self.as_ref(), coord)
    }

    /// Put a single texel to a raster image.
    pub fn put_texel<P>(&mut self, coord: Coord, texel: P)
    where
        L: RasterMut<P>,
    {
        L::put(self.as_mut(), coord, texel)
    }

    /// Call a function on each texel of this raster image.
    ///
    /// The order of evaluation is _not_ defined although certain layouts may offer more specific
    /// guarantees. In general, one can expect that layouts call the function in a cache-efficient
    /// manner if they are aware of a better iteration strategy.
    pub fn shade<P>(&mut self, f: impl FnMut(u32, u32, &mut P))
    where
        L: RasterMut<P>,
    {
        L::shade(self.as_mut(), f)
    }
}

/// Image methods for layouts based on pod samples.
impl<L: SliceLayout> Image<L> {
    /// Interpret an existing buffer as a pixel image.
    ///
    /// The data already contained within the buffer is not modified so that prior initialization
    /// can be performed or one array of samples reinterpreted for an image of other sample type.
    /// This method will never reallocate data.
    ///
    /// # Panics
    ///
    /// This function will panic if the buffer is shorter than the layout.
    pub fn from_buffer(buffer: TexelBuffer<L::Sample>, layout: L) -> Self {
        assert!(buffer.byte_len() >= layout.byte_len());
        RawImage::from_buffer(buffer, layout).into()
    }

    /// Get a slice of the individual samples in the layout.
    ///
    /// An alternative way to get a slice of texels when a layout does _not_ have an inherent texel
    /// _type_ is [`Self::as_texels`].
    pub fn as_slice(&self) -> &[L::Sample] {
        self.inner.as_slice()
    }

    /// Get a mutable slice of the individual samples in the layout.
    ///
    /// An alternative way to get a slice of texels when a layout does _not_ have an inherent texel
    /// _type_ is [`Self::as_mut_texels`].
    pub fn as_mut_slice(&mut self) -> &mut [L::Sample] {
        self.inner.as_mut_slice()
    }

    /// Convert into an vector-like of sample types.
    pub fn into_buffer(self) -> TexelBuffer<L::Sample> {
        self.inner.into_buffer()
    }
}

impl<'data, L> ImageRef<'data, L> {
    /// Get a reference to those bytes used by the layout.
    pub fn as_bytes(&self) -> &[u8]
    where
        L: Layout,
    {
        self.inner.as_bytes()
    }

    pub fn layout(&self) -> &L {
        &self.inner.layout
    }

    /// Get a view of this image.
    pub fn as_ref(&self) -> ImageRef<'_, &'_ L> {
        self.inner.borrow().into()
    }

    /// Check if a call to [`ImageRef::with_layout`] would succeed.
    pub fn fits(&self, other: &impl Layout) -> bool {
        self.inner.fits(other)
    }

    /// Change this view to a different layout.
    ///
    /// This returns `Some` if the layout fits the underlying data, and `None` otherwise. Use
    /// [`ImageRef::fits`] to check this property in a separate call. Note that the new layout
    /// need not be related to the old layout in any other way.
    ///
    /// # Usage
    ///
    /// ```rust
    /// # fn not_main() -> Option<()> {
    /// use image_texel::{Image, Matrix, layout::Bytes};
    /// let image = Image::from(Matrix::<[u8; 4]>::with_width_and_height(10, 10));
    ///
    /// let reference = image.as_ref();
    ///
    /// let as_bytes = reference.with_layout(Bytes(400))?;
    /// assert!(matches!(as_bytes.layout(), Bytes(400)));
    ///
    /// // But not if we request too much.
    /// assert!(as_bytes.with_layout(Bytes(500)).is_none());
    ///
    /// # Some(()) }
    /// # fn main() { not_main(); }
    /// ```
    pub fn with_layout<M>(self, layout: M) -> Option<ImageRef<'data, M>>
    where
        M: Layout,
    {
        let image = self.inner.try_reinterpret(layout).ok()?;
        Some(image.into())
    }

    /// Decay into a image with less specific layout.
    ///
    /// See [`Image::decay`].
    pub fn decay<M>(self) -> Option<ImageRef<'data, M>>
    where
        M: Decay<L>,
        M: Layout,
    {
        let layout = M::decay(self.inner.layout);
        let image = RawImage {
            layout,
            buffer: self.inner.buffer,
        };
        if image.fits(&image.layout) {
            Some(image.into())
        } else {
            None
        }
    }

    /// Copy all bytes to a newly allocated image.
    pub fn to_owned(&self) -> Image<L>
    where
        L: Layout + Clone,
    {
        Image::with_bytes(self.inner.layout.clone(), self.inner.as_bytes())
    }

    /// Get a slice of the individual samples in the layout.
    pub fn as_slice(&self) -> &[L::Sample]
    where
        L: SliceLayout,
    {
        self.inner.as_slice()
    }

    /// View this buffer as a slice of pixels.
    ///
    /// This reinterprets the bytes of the buffer. It can be used to view the buffer as any kind of
    /// pixel, regardless of its association with the layout. Use it with care.
    ///
    /// An alternative way to get a slice of texels when a layout has an inherent texel type is
    /// [`Self::as_slice`].
    pub fn as_texels<P>(&self, pixel: Texel<P>) -> &[P]
    where
        L: Layout,
    {
        pixel.cast_buf(self.inner.as_buf())
    }

    /// Turn into a slice of the individual samples in the layout.
    ///
    /// This preserves the lifetime with which the layout is borrowed from the underlying image,
    /// and the `ImageMut` need not stay alive.
    pub fn into_slice(self) -> &'data [L::Sample]
    where
        L: SliceLayout,
    {
        let buf = self.inner.buffer.truncate(self.inner.layout.len());
        self.inner.layout.sample().cast_buf(buf)
    }

    /// Retrieve a single texel from a raster image.
    pub fn get_texel<P>(&self, coord: Coord) -> Option<P>
    where
        L: Raster<P>,
    {
        L::get(self.as_ref(), coord)
    }

    /// Split off all unused bytes at the tail of the layout.
    pub fn split_layout(&mut self) -> ImageRef<'data, Bytes>
    where
        L: Layout,
    {
        // Need to roundup to correct alignment.
        let size = self.inner.layout.byte_len();
        let round_up = (size.wrapping_neg() & !(MAX_ALIGN - 1)).wrapping_neg();

        if round_up > self.inner.buffer.len() {
            return RawImage::with_buffer(Bytes(0), buf::new(&[])).into();
        }

        let (initial, next) = self.inner.buffer.split_at(round_up);
        self.inner.buffer = initial;

        RawImage::with_buffer(Bytes(next.len()), next).into()
    }
}

impl<'data, L> ImageMut<'data, L> {
    /// Get a reference to those bytes used by the layout.
    pub fn as_bytes(&self) -> &[u8]
    where
        L: Layout,
    {
        self.inner.as_bytes()
    }

    /// Get a mutable reference to those bytes used by the layout.
    pub fn as_bytes_mut(&mut self) -> &mut [u8]
    where
        L: Layout,
    {
        self.inner.as_bytes_mut()
    }

    pub fn layout(&self) -> &L {
        &self.inner.layout
    }

    /// Get a view of this image.
    pub fn as_ref(&self) -> ImageRef<'_, &'_ L> {
        self.inner.borrow().into()
    }

    /// Get a mutable view of this image.
    pub fn as_mut(&mut self) -> ImageMut<'_, &'_ mut L> {
        self.inner.borrow_mut().into()
    }

    /// Convert to a view of this image.
    pub fn into_ref(self) -> ImageRef<'data, L> {
        RawImage {
            layout: self.inner.layout,
            buffer: &*self.inner.buffer,
        }
        .into()
    }

    /// Check if a call to [`ImageMut::with_layout`] would succeed, without consuming this reference.
    pub fn fits(&self, other: &impl Layout) -> bool {
        self.inner.fits(other)
    }

    /// Change this view to a different layout.
    ///
    /// This returns `Some` if the layout fits the underlying data, and `None` otherwise. Use
    /// [`ImageMut::fits`] to check this property in a separate call. Note that the new layout
    /// need not be related to the old layout in any other way.
    ///
    /// # Usage
    ///
    /// ```rust
    /// # fn not_main() -> Option<()> {
    /// use image_texel::{Image, Matrix, layout::Bytes};
    /// let mut image = Image::from(Matrix::<[u8; 4]>::with_width_and_height(10, 10));
    ///
    /// let reference = image.as_mut();
    ///
    /// let as_bytes = reference.with_layout(Bytes(400))?;
    /// assert!(matches!(as_bytes.layout(), Bytes(400)));
    ///
    /// // But not if we request too much.
    /// assert!(as_bytes.with_layout(Bytes(500)).is_none());
    ///
    /// # Some(()) }
    /// # fn main() { not_main(); }
    /// ```
    pub fn with_layout<M>(self, layout: M) -> Option<ImageMut<'data, M>>
    where
        M: Layout,
    {
        let image = self.inner.try_reinterpret(layout).ok()?;
        Some(image.into())
    }

    /// Decay into a image with less specific layout.
    ///
    /// See [`Image::decay`].
    pub fn decay<M>(self) -> Option<ImageMut<'data, M>>
    where
        M: Decay<L>,
        M: Layout,
    {
        let layout = M::decay(self.inner.layout);
        let image = RawImage {
            layout,
            buffer: self.inner.buffer,
        };
        if image.fits(&image.layout) {
            Some(image.into())
        } else {
            None
        }
    }

    /// Copy the bytes and layout to an owned container.
    pub fn to_owned(&self) -> Image<L>
    where
        L: Layout + Clone,
    {
        Image::with_bytes(self.inner.layout.clone(), self.inner.as_bytes())
    }

    /// Get a slice of the individual samples in the layout.
    pub fn as_slice(&self) -> &[L::Sample]
    where
        L: SliceLayout,
    {
        self.inner.as_slice()
    }

    /// Get a mutable slice of the individual samples in the layout.
    pub fn as_mut_slice(&mut self) -> &mut [L::Sample]
    where
        L: SliceLayout,
    {
        self.inner.as_mut_slice()
    }

    /// View this buffer as a slice of pixels.
    ///
    /// This reinterprets the bytes of the buffer. It can be used to view the buffer as any kind of
    /// pixel, regardless of its association with the layout. Use it with care.
    ///
    /// An alternative way to get a slice of texels when a layout has an inherent texel type is
    /// [`Self::as_slice`].
    pub fn as_texels<P>(&self, pixel: Texel<P>) -> &[P]
    where
        L: Layout,
    {
        pixel.cast_buf(self.inner.as_buf())
    }

    /// View this buffer as a slice of pixels.
    ///
    /// This reinterprets the bytes of the buffer. It can be used to view the buffer as any kind of
    /// pixel, regardless of its association with the layout. Use it with care.
    ///
    /// An alternative way to get a slice of texels when a layout has an inherent texel type is
    /// [`Self::as_mut_slice`].
    pub fn as_mut_texels<P>(&mut self, pixel: Texel<P>) -> &mut [P]
    where
        L: Layout,
    {
        pixel.cast_mut_buf(self.inner.as_mut_buf())
    }

    /// Turn into a slice of the individual samples in the layout.
    ///
    /// This preserves the lifetime with which the layout is borrowed from the underlying image,
    /// and the `ImageMut` need not stay alive.
    pub fn into_slice(self) -> &'data [L::Sample]
    where
        L: SliceLayout,
    {
        let buf = self.inner.buffer.truncate(self.inner.layout.len());
        self.inner.layout.sample().cast_buf(buf)
    }

    /// Turn into a mutable slice of the individual samples in the layout.
    ///
    /// This preserves the lifetime with which the layout is borrowed from the underlying image,
    /// and the `ImageMut` need not stay alive.
    pub fn into_mut_slice(self) -> &'data mut [L::Sample]
    where
        L: SliceLayout,
    {
        let buf = self.inner.buffer.truncate_mut(self.inner.layout.len());
        self.inner.layout.sample().cast_mut_buf(buf)
    }

    /// Retrieve a single texel from a raster image.
    pub fn get_texel<P>(&self, coord: Coord) -> Option<P>
    where
        L: Raster<P>,
    {
        L::get(self.as_ref(), coord)
    }

    /// Put a single texel to a raster image.
    pub fn put_texel<P>(&mut self, coord: Coord, texel: P)
    where
        L: RasterMut<P>,
    {
        L::put(self.as_mut(), coord, texel)
    }

    /// Call a function on each texel of this raster image.
    ///
    /// The order of evaluation is _not_ defined although certain layouts may offer more specific
    /// guarantees. In general, one can expect that layouts call the function in a cache-efficient
    /// manner if they are aware of a better iteration strategy.
    pub fn shade<P>(&mut self, f: impl FnMut(u32, u32, &mut P))
    where
        L: RasterMut<P>,
    {
        L::shade(self.as_mut(), f)
    }

    /// Split off unused bytes at the tail of the layout.
    pub fn split_layout(&mut self) -> ImageMut<'data, Bytes>
    where
        L: Layout,
    {
        // Need to roundup to correct alignment.
        let size = self.inner.layout.byte_len();
        let round_up = (size.wrapping_neg() & !(MAX_ALIGN - 1)).wrapping_neg();

        let empty = buf::new_mut(&mut []);
        if round_up > self.inner.buffer.len() {
            return RawImage::with_buffer(Bytes(0), empty).into();
        }

        let buffer = core::mem::replace(&mut self.inner.buffer, empty);
        let (initial, next) = buffer.split_at_mut(round_up);
        self.inner.buffer = initial;

        RawImage::with_buffer(Bytes(next.len()), next).into()
    }
}

// TODO: how to expose?
// This is used internally in `RasterMut::shade` however only for the special case of
// * `&mut &mut L` -> `&mut L`
// * `&&mut L` -> `&L`
// which we know are semantically equivalent. In the general case these would go through checks
// that ensure the new layout is consistent with the data.
impl<'data, 'l, L: Layout> ImageRef<'data, &'l L> {
    pub(crate) fn as_deref(self) -> ImageRef<'data, &'l L::Target>
    where
        L: core::ops::Deref,
        L::Target: Layout,
    {
        self.inner.reinterpret_unguarded(|l| &**l).into()
    }
}

impl<'data, 'l, L: Layout> ImageMut<'data, &'l mut L> {
    pub(crate) fn as_deref_mut(self) -> ImageMut<'data, &'l mut L::Target>
    where
        L: core::ops::DerefMut,
        L::Target: Layout,
    {
        self.inner.reinterpret_unguarded(|l| &mut **l).into()
    }
}

/// Layout oblivious methods that can allocate and change to another buffer.
impl<B: Growable, L> RawImage<B, L> {
    /// Grow the buffer, preparing for another layout.
    ///
    /// This may allocate a new buffer and thus disassociate the image from the currently borrowed
    /// underlying buffer.
    ///
    /// # Panics
    /// This function will panic if an allocation is necessary but fails.
    pub(crate) fn grow(&mut self, layout: &impl Layout) {
        Growable::grow_to(&mut self.buffer, layout.byte_len());
    }

    /// Convert the inner layout.
    ///
    /// This method expects that the converted layout is compatible with the current layout.
    ///
    /// # Panics
    /// This method panics if the new layout requires more bytes and allocation fails.
    pub(crate) fn decay<Other>(mut self) -> RawImage<B, Other>
    where
        Other: Decay<L>,
    {
        let layout = Other::decay(self.layout);
        Growable::grow_to(&mut self.buffer, layout.byte_len());
        RawImage {
            buffer: self.buffer,
            layout,
        }
    }

    /// Convert the inner layout to a dynamic one.
    ///
    /// This is mostly convenience. Also not that `DynLayout` is of course not _completely_ generic
    /// but tries to emulate a large number of known layouts.
    ///
    /// # Panics
    /// This method panics if the new layout requires more bytes and allocation fails.
    pub(crate) fn into_dynamic(self) -> RawImage<B, DynLayout>
    where
        DynLayout: Decay<L>,
    {
        self.decay()
    }

    /// Change the layout, reusing and growing the buffer.
    ///
    /// # Panics
    /// This method panics if the new layout requires more bytes and allocation fails.
    pub(crate) fn with_layout<Other: Layout>(mut self, layout: Other) -> RawImage<B, Other> {
        Growable::grow_to(&mut self.buffer, layout.byte_len());
        RawImage {
            buffer: self.buffer,
            layout,
        }
    }

    /// Mutably borrow this image with another arbitrary layout.
    ///
    /// The other layout could be completely incompatible and perform arbitrary mutations. This
    /// seems counter intuitive at first, but recall that these mutations are not unsound as they
    /// can not invalidate the bytes themselves and only write unexpected values. This provides
    /// more flexibility for 'transmutes' than easily expressible in the type system.
    ///
    /// # Panics
    /// This method panics if the new layout requires more bytes and allocation fails.
    pub(crate) fn as_reinterpreted<Other>(&mut self, other: Other) -> RawImage<&'_ mut buf, Other>
    where
        B: BufferMut,
        Other: Layout,
    {
        self.grow(&other);
        RawImage {
            buffer: &mut self.buffer,
            layout: other,
        }
    }

    /// Change the layout and then resize the buffer so that it still fits.
    pub(crate) fn mutate_layout<T>(&mut self, f: impl FnOnce(&mut L) -> T) -> T
    where
        L: Layout,
    {
        let t = f(&mut self.layout);
        self.buffer.grow_to(self.layout.byte_len());
        t
    }
}

/// Layout oblivious methods, these also never allocate or panic.
impl<B: BufferLike, L> RawImage<B, L> {
    /// Get a mutable reference to the unstructured bytes of the image.
    ///
    /// Note that this may return more bytes than required for the specific layout for various
    /// reasons. See also [`as_layout_bytes_mut`].
    ///
    /// [`as_layout_bytes_mut`]: #method.as_layout_bytes_mut
    pub(crate) fn as_capacity_bytes_mut(&mut self) -> &mut [u8]
    where
        B: BufferMut,
    {
        self.buffer.as_bytes_mut()
    }

    /// Take ownership of the image's bytes.
    ///
    /// # Panics
    /// This method panics if allocation fails.
    pub(crate) fn into_owned(self) -> RawImage<Buffer, L> {
        RawImage {
            buffer: BufferLike::into_owned(self.buffer),
            layout: self.layout,
        }
    }
}

/// Methods specifically with a dynamic layout.
impl<B> RawImage<B, DynLayout> {
    pub(crate) fn try_from_dynamic<Other>(self, layout: Other) -> Result<RawImage<B, Other>, Self>
    where
        Other: Into<DynLayout> + Clone,
    {
        let reference = layout.clone().into();
        if self.layout == reference {
            Ok(RawImage {
                buffer: self.buffer,
                layout,
            })
        } else {
            Err(self)
        }
    }
}

impl<B, L> RawImage<B, L> {
    /// Allocate a buffer for a particular layout.
    pub(crate) fn new(layout: L) -> Self
    where
        L: Layout,
        B: From<Buffer>,
    {
        let bytes = layout.byte_len();
        RawImage {
            buffer: Buffer::new(bytes).into(),
            layout,
        }
    }

    /// Create a image from a byte slice specifying the contents.
    ///
    /// If the layout requires more bytes then the remaining bytes are zero initialized.
    pub(crate) fn with_contents(buffer: &[u8], layout: L) -> Self
    where
        L: Layout,
        B: From<Buffer>,
    {
        let mut buffer = Buffer::from(buffer);
        buffer.grow_to(layout.byte_len());
        RawImage {
            buffer: buffer.into(),
            layout,
        }
    }

    pub(crate) fn with_buffer(layout: L, buffer: B) -> Self
    where
        B: ops::Deref<Target = buf>,
        L: Layout,
    {
        assert!(buffer.as_ref().len() <= layout.byte_len());
        RawImage { buffer, layout }
    }

    /// Get a reference to the layout.
    pub(crate) fn layout(&self) -> &L {
        &self.layout
    }

    /// Get a mutable reference to the layout.
    ///
    /// Be mindful not to modify the layout to exceed the allocated size.
    pub(crate) fn layout_mut_unguarded(&mut self) -> &mut L {
        &mut self.layout
    }

    /// Get a reference to the unstructured bytes of the image.
    ///
    /// Note that this may return more bytes than required for the specific layout for various
    /// reasons. See also [`as_layout_bytes`].
    ///
    /// [`as_layout_bytes`]: #method.as_layout_bytes
    pub(crate) fn as_capacity_bytes(&self) -> &[u8]
    where
        B: ops::Deref<Target = buf>,
    {
        self.buffer.as_bytes()
    }

    /// Get a reference to those bytes used by the layout.
    pub(crate) fn as_bytes(&self) -> &[u8]
    where
        B: ops::Deref<Target = buf>,
        L: Layout,
    {
        &self.as_capacity_bytes()[..self.layout.byte_len()]
    }

    pub fn as_buf(&self) -> &buf
    where
        B: ops::Deref<Target = buf>,
        L: Layout,
    {
        let byte_len = self.layout.byte_len();
        self.buffer.truncate(byte_len)
    }

    pub fn as_mut_buf(&mut self) -> &mut buf
    where
        B: ops::DerefMut<Target = buf>,
        L: Layout,
    {
        let byte_len = self.layout.byte_len();
        self.buffer.truncate_mut(byte_len)
    }

    pub(crate) fn as_slice(&self) -> &[L::Sample]
    where
        B: ops::Deref<Target = buf>,
        L: SliceLayout,
    {
        let texel = self.layout.sample();
        texel.cast_buf(self.as_buf())
    }

    /// Borrow the buffer with the same layout.
    pub(crate) fn borrow(&self) -> RawImage<&'_ buf, &'_ L>
    where
        B: ops::Deref<Target = buf>,
    {
        RawImage {
            buffer: &self.buffer,
            layout: &self.layout,
        }
    }

    /// Borrow the buffer mutably with the same layout.
    pub(crate) fn borrow_mut(&mut self) -> RawImage<&'_ mut buf, &'_ mut L>
    where
        B: ops::DerefMut<Target = buf>,
    {
        RawImage {
            buffer: &mut self.buffer,
            layout: &mut self.layout,
        }
    }

    pub(crate) fn fits(&self, other: &impl Layout) -> bool
    where
        B: ops::Deref<Target = buf>,
    {
        other.byte_len() <= self.as_capacity_bytes().len()
    }

    /// Change the layout without checking the buffer.
    pub(crate) fn reinterpret_unguarded<Other: Layout>(
        self,
        layout: impl FnOnce(L) -> Other,
    ) -> RawImage<B, Other> {
        RawImage {
            buffer: self.buffer,
            layout: layout(self.layout),
        }
    }

    /// Reinterpret the bits in another layout.
    ///
    /// This method fails if the layout requires more bytes than are currently allocated.
    pub(crate) fn try_reinterpret<Other>(self, layout: Other) -> Result<RawImage<B, Other>, Self>
    where
        B: ops::Deref<Target = buf>,
        Other: Layout,
    {
        if self.buffer.len() < layout.byte_len() {
            Err(self)
        } else {
            Ok(RawImage {
                buffer: self.buffer,
                layout,
            })
        }
    }
}

/// Methods for all `Layouts` (the trait).
impl<B: BufferLike, L: Layout> RawImage<B, L> {
    /// Get a mutable reference to those bytes used by the layout.
    pub(crate) fn as_bytes_mut(&mut self) -> &mut [u8]
    where
        B: BufferMut,
    {
        let len = self.layout.byte_len();
        &mut self.as_capacity_bytes_mut()[..len]
    }

    /// Reuse the buffer for a new image layout of the same type.
    pub(crate) fn try_reuse(&mut self, layout: L) -> Result<(), BufferReuseError> {
        if self.as_capacity_bytes().len() >= layout.byte_len() {
            self.layout = layout;
            Ok(())
        } else {
            Err(BufferReuseError {
                capacity: self.as_capacity_bytes().len(),
                requested: Some(layout.byte_len()),
            })
        }
    }

    /// Change the layout but require that the new layout fits the buffer, never reallocate.
    pub(crate) fn mutate_inplace<T>(&mut self, f: impl FnOnce(&mut L) -> T) -> T
    where
        L: Layout,
    {
        let t = f(&mut self.layout);
        assert!(
            self.layout.byte_len() <= self.buffer.len(),
            "Modification required buffer allocation, was not in-place"
        );
        t
    }

    /// Take the buffer and layout from this image, moving content into a new instance.
    ///
    /// Asserts that the moved-from container can hold the emptied layout.
    pub(crate) fn take(&mut self) -> Self
    where
        L: Take,
    {
        let buffer = self.buffer.take();
        let layout = self.mutate_inplace(Take::take);
        RawImage::with_buffer(layout, buffer)
    }
}

/// Methods for layouts that are slices of individual samples.
impl<B: BufferLike, L: SliceLayout> RawImage<B, L> {
    /// Interpret an existing buffer as a pixel image.
    ///
    /// The data already contained within the buffer is not modified so that prior initialization
    /// can be performed or one array of samples reinterpreted for an image of other sample type.
    /// However, the `TexelBuffer` will be logically resized which will zero-initialize missing elements if
    /// the current buffer is too short.
    ///
    /// # Panics
    ///
    /// This function will panic if resizing causes a reallocation that fails.
    pub(crate) fn from_buffer(buffer: TexelBuffer<L::Sample>, layout: L) -> Self
    where
        B: From<Buffer>,
    {
        let buffer = buffer.into_inner();
        assert!(buffer.len() >= layout.byte_len());
        Self {
            buffer: buffer.into(),
            layout,
        }
    }

    pub(crate) fn as_mut_slice(&mut self) -> &mut [L::Sample]
    where
        B: BufferMut,
    {
        self.layout.sample().cast_mut_buf(self.as_mut_buf())
    }

    /// Convert back into an vector-like of sample types.
    pub(crate) fn into_buffer(self) -> TexelBuffer<L::Sample> {
        let sample = self.layout.sample();
        // Avoid calling any method of `Layout` after this. Not relevant for safety but might be in
        // the future, if we want to avoid the extra check in `resize`.
        let count = self.as_slice().len();
        let buffer = self.buffer.into_owned();
        let mut rec = TexelBuffer::from_buffer(buffer, sample);
        // This should never reallocate at this point but we don't really know or care.
        rec.resize(count);
        rec
    }
}

impl<'lt, L: Layout + Clone> From<Image<&'lt L>> for Image<L> {
    fn from(image: Image<&'lt L>) -> Self {
        let layout: L = (*image.layout()).clone();
        RawImage::with_buffer(layout, image.inner.buffer).into()
    }
}

impl<'lt, L: Layout + Clone> From<Image<&'lt mut L>> for Image<L> {
    fn from(image: Image<&'lt mut L>) -> Self {
        let layout: L = (*image.layout()).clone();
        RawImage::with_buffer(layout, image.inner.buffer).into()
    }
}

impl<'lt, L> From<&'lt Image<L>> for ImageRef<'lt, &'lt L> {
    fn from(image: &'lt Image<L>) -> Self {
        image.as_ref()
    }
}

impl<'lt, L> From<&'lt mut Image<L>> for ImageMut<'lt, &'lt mut L> {
    fn from(image: &'lt mut Image<L>) -> Self {
        image.as_mut()
    }
}

impl<'lt, L: Layout + Clone> From<&'lt Image<L>> for ImageRef<'lt, L> {
    fn from(image: &'lt Image<L>) -> Self {
        image.as_ref().into()
    }
}

impl<'lt, L: Layout + Clone> From<&'lt mut Image<L>> for ImageMut<'lt, L> {
    fn from(image: &'lt mut Image<L>) -> Self {
        image.as_mut().into()
    }
}

/* FIXME: decide if this should be an explicit method. */
impl<'lt, L: Layout + Clone> From<ImageRef<'lt, &'_ L>> for ImageRef<'lt, L> {
    fn from(image: ImageRef<'lt, &'_ L>) -> Self {
        let layout: L = (*image.layout()).clone();
        RawImage::with_buffer(layout, image.inner.buffer).into()
    }
}

impl<'lt, L: Layout + Clone> From<ImageRef<'lt, &'_ mut L>> for ImageRef<'lt, L> {
    fn from(image: ImageRef<'lt, &'_ mut L>) -> Self {
        let layout: L = (*image.layout()).clone();
        RawImage::with_buffer(layout, image.inner.buffer).into()
    }
}

impl<'lt, L: Layout + Clone> From<ImageMut<'lt, &'_ L>> for ImageMut<'lt, L> {
    fn from(image: ImageMut<'lt, &'_ L>) -> Self {
        let layout: L = (*image.layout()).clone();
        RawImage::with_buffer(layout, image.inner.buffer).into()
    }
}

impl<'lt, L: Layout + Clone> From<ImageMut<'lt, &'_ mut L>> for ImageMut<'lt, L> {
    fn from(image: ImageMut<'lt, &'_ mut L>) -> Self {
        let layout: L = (*image.layout()).clone();
        RawImage::with_buffer(layout, image.inner.buffer).into()
    }
}
/* FIXME: until here */

impl<L> From<RawImage<Buffer, L>> for Image<L> {
    fn from(image: RawImage<Buffer, L>) -> Self {
        Image { inner: image }
    }
}

impl<'lt, L> From<RawImage<&'lt buf, L>> for ImageRef<'lt, L> {
    fn from(image: RawImage<&'lt buf, L>) -> Self {
        ImageRef { inner: image }
    }
}

impl<'lt, L> From<RawImage<&'lt mut buf, L>> for ImageMut<'lt, L> {
    fn from(image: RawImage<&'lt mut buf, L>) -> Self {
        ImageMut { inner: image }
    }
}

impl BufferLike for Cog<'_> {
    fn into_owned(self) -> Buffer {
        Cog::into_owned(self)
    }

    fn take(&mut self) -> Self {
        core::mem::replace(self, Cog::Owned(Default::default()))
    }
}

impl BufferLike for Buffer {
    fn into_owned(self) -> Self {
        self
    }

    fn take(&mut self) -> Self {
        core::mem::take(self)
    }
}

impl BufferLike for &'_ mut buf {
    fn into_owned(self) -> Buffer {
        Buffer::from(self.as_bytes())
    }

    fn take(&mut self) -> Self {
        core::mem::take(self)
    }
}

impl Growable for Cog<'_> {
    fn grow_to(&mut self, bytes: usize) {
        Cog::grow_to(self, bytes);
    }
}

impl Growable for Buffer {
    fn grow_to(&mut self, bytes: usize) {
        Buffer::grow_to(self, bytes);
    }
}

impl BufferMut for Cog<'_> {}

impl BufferMut for Buffer {}

impl BufferMut for &'_ mut buf {}

impl<Layout: Clone> Clone for RawImage<Cog<'_>, Layout> {
    fn clone(&self) -> Self {
        use alloc::borrow::ToOwned;
        RawImage {
            buffer: Cog::Owned(self.buffer.to_owned()),
            layout: self.layout.clone(),
        }
    }
}

impl<Layout: Default> Default for Image<Layout> {
    fn default() -> Self {
        Image {
            inner: RawImage {
                buffer: Buffer::default(),
                layout: Layout::default(),
            },
        }
    }
}

impl<Layout: Default> Default for CopyOnGrow<'_, Layout> {
    fn default() -> Self {
        CopyOnGrow {
            inner: RawImage {
                buffer: Cog::Owned(Buffer::default()),
                layout: Layout::default(),
            },
        }
    }
}

impl<L> fmt::Debug for Image<L>
where
    L: SliceLayout + fmt::Debug,
    L::Sample: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Image")
            .field("layout", &self.inner.layout)
            .field("content", &self.inner.as_slice())
            .finish()
    }
}