/
flat.rs
1712 lines (1538 loc) · 62.2 KB
/
flat.rs
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
//! Image representations for ffi.
//!
//! # Usage
//!
//! Imagine you want to offer a very simple ffi interface: The caller provides an image buffer and
//! your program creates a thumbnail from it and dumps that image as `png`. This module is designed
//! to help you transition from raw memory data to Rust representation.
//!
//! ```no_run
//! use std::ptr;
//! use std::slice;
//! use image::Rgb;
//! use image::flat::{FlatSamples, SampleLayout};
//! use image::imageops::thumbnail;
//!
//! #[no_mangle]
//! pub extern "C" fn store_rgb8_compressed(
//! data: *const u8, len: usize,
//! layout: *const SampleLayout
//! )
//! -> bool
//! {
//! let samples = unsafe { slice::from_raw_parts(data, len) };
//! let layout = unsafe { ptr::read(layout) };
//!
//! let buffer = FlatSamples {
//! samples,
//! layout,
//! color_hint: None,
//! };
//!
//! let view = match buffer.as_view::<Rgb<u8>>() {
//! Err(_) => return false, // Invalid layout.
//! Ok(view) => view,
//! };
//!
//! thumbnail(&view, 64, 64)
//! .save("output.png")
//! .map(|_| true)
//! .unwrap_or_else(|_| false)
//! }
//! ```
//!
use std::marker::PhantomData;
use std::ops::{Deref, Index, IndexMut};
use std::{cmp, error, fmt};
use num_traits::Zero;
use crate::color::ColorType;
use crate::error::{
DecodingError, ImageError, ImageFormatHint, ParameterError, ParameterErrorKind,
UnsupportedError, UnsupportedErrorKind,
};
use crate::image::{GenericImage, GenericImageView};
use crate::traits::{Pixel, PixelWithColorType};
use crate::ImageBuffer;
/// A flat buffer over a (multi channel) image.
///
/// In contrast to `ImageBuffer`, this representation of a sample collection is much more lenient
/// in the layout thereof. It also allows grouping by color planes instead of by pixel as long as
/// the strides of each extent are constant. This struct itself has no invariants on the strides
/// but not every possible configuration can be interpreted as a [`GenericImageView`] or
/// [`GenericImage`]. The methods [`as_view`] and [`as_view_mut`] construct the actual implementors
/// of these traits and perform necessary checks. To manually perform this and other layout checks
/// use [`is_normal`] or [`has_aliased_samples`].
///
/// Instances can be constructed not only by hand. The buffer instances returned by library
/// functions such as [`ImageBuffer::as_flat_samples`] guarantee that the conversion to a generic
/// image or generic view succeeds. A very different constructor is [`with_monocolor`]. It uses a
/// single pixel as the backing storage for an arbitrarily sized read-only raster by mapping each
/// pixel to the same samples by setting some strides to `0`.
///
/// [`GenericImage`]: ../trait.GenericImage.html
/// [`GenericImageView`]: ../trait.GenericImageView.html
/// [`ImageBuffer::as_flat_samples`]: ../struct.ImageBuffer.html#method.as_flat_samples
/// [`is_normal`]: #method.is_normal
/// [`has_aliased_samples`]: #method.has_aliased_samples
/// [`as_view`]: #method.as_view
/// [`as_view_mut`]: #method.as_view_mut
/// [`with_monocolor`]: #method.with_monocolor
#[derive(Clone, Debug)]
pub struct FlatSamples<Buffer> {
/// Underlying linear container holding sample values.
pub samples: Buffer,
/// A `repr(C)` description of the layout of buffer samples.
pub layout: SampleLayout,
/// Supplementary color information.
///
/// You may keep this as `None` in most cases. This is NOT checked in `View` or other
/// converters. It is intended mainly as a way for types that convert to this buffer type to
/// attach their otherwise static color information. A dynamic image representation could
/// however use this to resolve representational ambiguities such as the order of RGB channels.
pub color_hint: Option<ColorType>,
}
/// A ffi compatible description of a sample buffer.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SampleLayout {
/// The number of channels in the color representation of the image.
pub channels: u8,
/// Add this to an index to get to the sample in the next channel.
pub channel_stride: usize,
/// The width of the represented image.
pub width: u32,
/// Add this to an index to get to the next sample in x-direction.
pub width_stride: usize,
/// The height of the represented image.
pub height: u32,
/// Add this to an index to get to the next sample in y-direction.
pub height_stride: usize,
}
/// Helper struct for an unnamed (stride, length) pair.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Dim(usize, usize);
impl SampleLayout {
/// Describe a row-major image packed in all directions.
///
/// The resulting will surely be `NormalForm::RowMajorPacked`. It can therefore be converted to
/// safely to an `ImageBuffer` with a large enough underlying buffer.
///
/// ```
/// # use image::flat::{NormalForm, SampleLayout};
/// let layout = SampleLayout::row_major_packed(3, 640, 480);
/// assert!(layout.is_normal(NormalForm::RowMajorPacked));
/// ```
///
/// # Panics
///
/// On platforms where `usize` has the same size as `u32` this panics when the resulting stride
/// in the `height` direction would be larger than `usize::max_value()`. On other platforms
/// where it can surely accommodate `u8::max_value() * u32::max_value(), this can never happen.
pub fn row_major_packed(channels: u8, width: u32, height: u32) -> Self {
let height_stride = (channels as usize).checked_mul(width as usize).expect(
"Row major packed image can not be described because it does not fit into memory",
);
SampleLayout {
channels,
channel_stride: 1,
width,
width_stride: channels as usize,
height,
height_stride,
}
}
/// Describe a column-major image packed in all directions.
///
/// The resulting will surely be `NormalForm::ColumnMajorPacked`. This is not particularly
/// useful for conversion but can be used to describe such a buffer without pitfalls.
///
/// ```
/// # use image::flat::{NormalForm, SampleLayout};
/// let layout = SampleLayout::column_major_packed(3, 640, 480);
/// assert!(layout.is_normal(NormalForm::ColumnMajorPacked));
/// ```
///
/// # Panics
///
/// On platforms where `usize` has the same size as `u32` this panics when the resulting stride
/// in the `width` direction would be larger than `usize::max_value()`. On other platforms
/// where it can surely accommodate `u8::max_value() * u32::max_value(), this can never happen.
pub fn column_major_packed(channels: u8, width: u32, height: u32) -> Self {
let width_stride = (channels as usize).checked_mul(height as usize).expect(
"Column major packed image can not be described because it does not fit into memory",
);
SampleLayout {
channels,
channel_stride: 1,
height,
height_stride: channels as usize,
width,
width_stride,
}
}
/// Get the strides for indexing matrix-like `[(c, w, h)]`.
///
/// For a row-major layout with grouped samples, this tuple is strictly
/// increasing.
pub fn strides_cwh(&self) -> (usize, usize, usize) {
(self.channel_stride, self.width_stride, self.height_stride)
}
/// Get the dimensions `(channels, width, height)`.
///
/// The interface is optimized for use with `strides_cwh` instead. The channel extent will be
/// before width and height.
pub fn extents(&self) -> (usize, usize, usize) {
(
self.channels as usize,
self.width as usize,
self.height as usize,
)
}
/// Tuple of bounds in the order of coordinate inputs.
///
/// This function should be used whenever working with image coordinates opposed to buffer
/// coordinates. The only difference compared to `extents` is the output type.
pub fn bounds(&self) -> (u8, u32, u32) {
(self.channels, self.width, self.height)
}
/// Get the minimum length of a buffer such that all in-bounds samples have valid indices.
///
/// This method will allow zero strides, allowing compact representations of monochrome images.
/// To check that no aliasing occurs, try `check_alias_invariants`. For compact images (no
/// aliasing and no unindexed samples) this is `width*height*channels`. But for both of the
/// other cases, the reasoning is slightly more involved.
///
/// # Explanation
///
/// Note that there is a difference between `min_length` and the index of the sample
/// 'one-past-the-end`. This is due to strides that may be larger than the dimension below.
///
/// ## Example with holes
///
/// Let's look at an example of a grayscale image with
/// * `width_stride = 1`
/// * `width = 2`
/// * `height_stride = 3`
/// * `height = 2`
///
/// ```text
/// | x x | x x m | $
/// min_length m ^
/// ^ one-past-the-end $
/// ```
///
/// The difference is also extreme for empty images with large strides. The one-past-the-end
/// sample index is still as large as the largest of these strides while `min_length = 0`.
///
/// ## Example with aliasing
///
/// The concept gets even more important when you allow samples to alias each other. Here we
/// have the buffer of a small grayscale image where this is the case, this time we will first
/// show the buffer and then the individual rows below.
///
/// * `width_stride = 1`
/// * `width = 3`
/// * `height_stride = 2`
/// * `height = 2`
///
/// ```text
/// 1 2 3 4 5 m
/// |1 2 3| row one
/// |3 4 5| row two
/// ^ m min_length
/// ^ ??? one-past-the-end
/// ```
///
/// This time 'one-past-the-end' is not even simply the largest stride times the extent of its
/// dimension. That still points inside the image because `height*height_stride = 4` but also
/// `index_of(1, 2) = 4`.
pub fn min_length(&self) -> Option<usize> {
if self.width == 0 || self.height == 0 || self.channels == 0 {
return Some(0);
}
self.index(self.channels - 1, self.width - 1, self.height - 1)
.and_then(|idx| idx.checked_add(1))
}
/// Check if a buffer of length `len` is large enough.
pub fn fits(&self, len: usize) -> bool {
self.min_length().map(|min| len >= min).unwrap_or(false)
}
/// The extents of this array, in order of increasing strides.
fn increasing_stride_dims(&self) -> [Dim; 3] {
// Order extents by strides, then check that each is less equal than the next stride.
let mut grouped: [Dim; 3] = [
Dim(self.channel_stride, self.channels as usize),
Dim(self.width_stride, self.width as usize),
Dim(self.height_stride, self.height as usize),
];
grouped.sort();
let (min_dim, mid_dim, max_dim) = (grouped[0], grouped[1], grouped[2]);
assert!(min_dim.stride() <= mid_dim.stride() && mid_dim.stride() <= max_dim.stride());
grouped
}
/// If there are any samples aliasing each other.
///
/// If this is not the case, it would always be safe to allow mutable access to two different
/// samples at the same time. Otherwise, this operation would need additional checks. When one
/// dimension overflows `usize` with its stride we also consider this aliasing.
pub fn has_aliased_samples(&self) -> bool {
let grouped = self.increasing_stride_dims();
let (min_dim, mid_dim, max_dim) = (grouped[0], grouped[1], grouped[2]);
let min_size = match min_dim.checked_len() {
None => return true,
Some(size) => size,
};
let mid_size = match mid_dim.checked_len() {
None => return true,
Some(size) => size,
};
let _max_size = match max_dim.checked_len() {
None => return true,
Some(_) => (), // Only want to know this didn't overflow.
};
// Each higher dimension must walk over all of one lower dimension.
min_size > mid_dim.stride() || mid_size > max_dim.stride()
}
/// Check if a buffer fulfills the requirements of a normal form.
///
/// Certain conversions have preconditions on the structure of the sample buffer that are not
/// captured (by design) by the type system. These are then checked before the conversion. Such
/// checks can all be done in constant time and will not inspect the buffer content. You can
/// perform these checks yourself when the conversion is not required at this moment but maybe
/// still performed later.
pub fn is_normal(&self, form: NormalForm) -> bool {
if self.has_aliased_samples() {
return false;
}
if form >= NormalForm::PixelPacked && self.channel_stride != 1 {
return false;
}
if form >= NormalForm::ImagePacked {
// has aliased already checked for overflows.
let grouped = self.increasing_stride_dims();
let (min_dim, mid_dim, max_dim) = (grouped[0], grouped[1], grouped[2]);
if 1 != min_dim.stride() {
return false;
}
if min_dim.len() != mid_dim.stride() {
return false;
}
if mid_dim.len() != max_dim.stride() {
return false;
}
}
if form >= NormalForm::RowMajorPacked {
if self.width_stride != self.channels as usize {
return false;
}
if self.width as usize * self.width_stride != self.height_stride {
return false;
}
}
if form >= NormalForm::ColumnMajorPacked {
if self.height_stride != self.channels as usize {
return false;
}
if self.height as usize * self.height_stride != self.width_stride {
return false;
}
}
true
}
/// Check that the pixel and the channel index are in bounds.
///
/// An in-bound coordinate does not yet guarantee that the corresponding calculation of a
/// buffer index does not overflow. However, if such a buffer large enough to hold all samples
/// actually exists in memory, this property of course follows.
pub fn in_bounds(&self, channel: u8, x: u32, y: u32) -> bool {
channel < self.channels && x < self.width && y < self.height
}
/// Resolve the index of a particular sample.
///
/// `None` if the index is outside the bounds or does not fit into a `usize`.
pub fn index(&self, channel: u8, x: u32, y: u32) -> Option<usize> {
if !self.in_bounds(channel, x, y) {
return None;
}
self.index_ignoring_bounds(channel as usize, x as usize, y as usize)
}
/// Get the theoretical position of sample (channel, x, y).
///
/// The 'check' is for overflow during index calculation, not that it is contained in the
/// image. Two samples may return the same index, even when one of them is out of bounds. This
/// happens when all strides are `0`, i.e. the image is an arbitrarily large monochrome image.
pub fn index_ignoring_bounds(&self, channel: usize, x: usize, y: usize) -> Option<usize> {
let idx_c = (channel as usize).checked_mul(self.channel_stride);
let idx_x = (x as usize).checked_mul(self.width_stride);
let idx_y = (y as usize).checked_mul(self.height_stride);
let (idx_c, idx_x, idx_y) = match (idx_c, idx_x, idx_y) {
(Some(idx_c), Some(idx_x), Some(idx_y)) => (idx_c, idx_x, idx_y),
_ => return None,
};
Some(0usize)
.and_then(|b| b.checked_add(idx_c))
.and_then(|b| b.checked_add(idx_x))
.and_then(|b| b.checked_add(idx_y))
}
/// Get an index provided it is inbouds.
///
/// Assumes that the image is backed by some sufficiently large buffer. Then computation can
/// not overflow as we could represent the maximum coordinate. Since overflow is defined either
/// way, this method can not be unsafe.
pub fn in_bounds_index(&self, c: u8, x: u32, y: u32) -> usize {
let (c_stride, x_stride, y_stride) = self.strides_cwh();
(y as usize * y_stride) + (x as usize * x_stride) + (c as usize * c_stride)
}
/// Shrink the image to the minimum of current and given extents.
///
/// This does not modify the strides, so that the resulting sample buffer may have holes
/// created by the shrinking operation. Shrinking could also lead to an non-aliasing image when
/// samples had aliased each other before.
pub fn shrink_to(&mut self, channels: u8, width: u32, height: u32) {
self.channels = self.channels.min(channels);
self.width = self.width.min(width);
self.height = self.height.min(height);
}
}
impl Dim {
fn stride(self) -> usize {
self.0
}
/// Length of this dimension in memory.
fn checked_len(self) -> Option<usize> {
self.0.checked_mul(self.1)
}
fn len(self) -> usize {
self.0 * self.1
}
}
impl<Buffer> FlatSamples<Buffer> {
/// Get the strides for indexing matrix-like `[(c, w, h)]`.
///
/// For a row-major layout with grouped samples, this tuple is strictly
/// increasing.
pub fn strides_cwh(&self) -> (usize, usize, usize) {
self.layout.strides_cwh()
}
/// Get the dimensions `(channels, width, height)`.
///
/// The interface is optimized for use with `strides_cwh` instead. The channel extent will be
/// before width and height.
pub fn extents(&self) -> (usize, usize, usize) {
self.layout.extents()
}
/// Tuple of bounds in the order of coordinate inputs.
///
/// This function should be used whenever working with image coordinates opposed to buffer
/// coordinates. The only difference compared to `extents` is the output type.
pub fn bounds(&self) -> (u8, u32, u32) {
self.layout.bounds()
}
/// Get a reference based version.
pub fn as_ref<T>(&self) -> FlatSamples<&[T]>
where
Buffer: AsRef<[T]>,
{
FlatSamples {
samples: self.samples.as_ref(),
layout: self.layout,
color_hint: self.color_hint,
}
}
/// Get a mutable reference based version.
pub fn as_mut<T>(&mut self) -> FlatSamples<&mut [T]>
where
Buffer: AsMut<[T]>,
{
FlatSamples {
samples: self.samples.as_mut(),
layout: self.layout,
color_hint: self.color_hint,
}
}
/// Copy the data into an owned vector.
pub fn to_vec<T>(&self) -> FlatSamples<Vec<T>>
where
T: Clone,
Buffer: AsRef<[T]>,
{
FlatSamples {
samples: self.samples.as_ref().to_vec(),
layout: self.layout,
color_hint: self.color_hint,
}
}
/// Get a reference to a single sample.
///
/// This more restrictive than the method based on `std::ops::Index` but guarantees to properly
/// check all bounds and not panic as long as `Buffer::as_ref` does not do so.
///
/// ```
/// # use image::{RgbImage};
/// let flat = RgbImage::new(480, 640).into_flat_samples();
///
/// // Get the blue channel at (10, 10).
/// assert!(flat.get_sample(1, 10, 10).is_some());
///
/// // There is no alpha channel.
/// assert!(flat.get_sample(3, 10, 10).is_none());
/// ```
///
/// For cases where a special buffer does not provide `AsRef<[T]>`, consider encapsulating
/// bounds checks with `min_length` in a type similar to `View`. Then you may use
/// `in_bounds_index` as a small speedup over the index calculation of this method which relies
/// on `index_ignoring_bounds` since it can not have a-priori knowledge that the sample
/// coordinate is in fact backed by any memory buffer.
pub fn get_sample<T>(&self, channel: u8, x: u32, y: u32) -> Option<&T>
where
Buffer: AsRef<[T]>,
{
self.index(channel, x, y)
.and_then(|idx| self.samples.as_ref().get(idx))
}
/// Get a mutable reference to a single sample.
///
/// This more restrictive than the method based on `std::ops::IndexMut` but guarantees to
/// properly check all bounds and not panic as long as `Buffer::as_ref` does not do so.
/// Contrary to conversion to `ViewMut`, this does not require that samples are packed since it
/// does not need to convert samples to a color representation.
///
/// **WARNING**: Note that of course samples may alias, so that the mutable reference returned
/// here can in fact modify more than the coordinate in the argument.
///
/// ```
/// # use image::{RgbImage};
/// let mut flat = RgbImage::new(480, 640).into_flat_samples();
///
/// // Assign some new color to the blue channel at (10, 10).
/// *flat.get_mut_sample(1, 10, 10).unwrap() = 255;
///
/// // There is no alpha channel.
/// assert!(flat.get_mut_sample(3, 10, 10).is_none());
/// ```
///
/// For cases where a special buffer does not provide `AsRef<[T]>`, consider encapsulating
/// bounds checks with `min_length` in a type similar to `View`. Then you may use
/// `in_bounds_index` as a small speedup over the index calculation of this method which relies
/// on `index_ignoring_bounds` since it can not have a-priori knowledge that the sample
/// coordinate is in fact backed by any memory buffer.
pub fn get_mut_sample<T>(&mut self, channel: u8, x: u32, y: u32) -> Option<&mut T>
where
Buffer: AsMut<[T]>,
{
match self.index(channel, x, y) {
None => None,
Some(idx) => self.samples.as_mut().get_mut(idx),
}
}
/// View this buffer as an image over some type of pixel.
///
/// This first ensures that all in-bounds coordinates refer to valid indices in the sample
/// buffer. It also checks that the specified pixel format expects the same number of channels
/// that are present in this buffer. Neither are larger nor a smaller number will be accepted.
/// There is no automatic conversion.
pub fn as_view<P>(&self) -> Result<View<&[P::Subpixel], P>, Error>
where
P: PixelWithColorType,
Buffer: AsRef<[P::Subpixel]>,
{
if self.layout.channels != P::CHANNEL_COUNT {
return Err(Error::WrongColor(P::COLOR_TYPE));
}
let as_ref = self.samples.as_ref();
if !self.layout.fits(as_ref.len()) {
return Err(Error::TooLarge);
}
Ok(View {
inner: FlatSamples {
samples: as_ref,
layout: self.layout,
color_hint: self.color_hint,
},
phantom: PhantomData,
})
}
/// View this buffer but keep mutability at a sample level.
///
/// This is similar to `as_view` but subtly different from `as_view_mut`. The resulting type
/// can be used as a `GenericImage` with the same prior invariants needed as for `as_view`.
/// It can not be used as a mutable `GenericImage` but does not need channels to be packed in
/// their pixel representation.
///
/// This first ensures that all in-bounds coordinates refer to valid indices in the sample
/// buffer. It also checks that the specified pixel format expects the same number of channels
/// that are present in this buffer. Neither are larger nor a smaller number will be accepted.
/// There is no automatic conversion.
///
/// **WARNING**: Note that of course samples may alias, so that the mutable reference returned
/// for one sample can in fact modify other samples as well. Sometimes exactly this is
/// intended.
pub fn as_view_with_mut_samples<P>(&mut self) -> Result<View<&mut [P::Subpixel], P>, Error>
where
P: PixelWithColorType,
Buffer: AsMut<[P::Subpixel]>,
{
if self.layout.channels != P::CHANNEL_COUNT {
return Err(Error::WrongColor(P::COLOR_TYPE));
}
let as_mut = self.samples.as_mut();
if !self.layout.fits(as_mut.len()) {
return Err(Error::TooLarge);
}
Ok(View {
inner: FlatSamples {
samples: as_mut,
layout: self.layout,
color_hint: self.color_hint,
},
phantom: PhantomData,
})
}
/// Interpret this buffer as a mutable image.
///
/// To succeed, the pixels in this buffer may not alias each other and the samples of each
/// pixel must be packed (i.e. `channel_stride` is `1`). The number of channels must be
/// consistent with the channel count expected by the pixel format.
///
/// This is similar to an `ImageBuffer` except it is a temporary view that is not normalized as
/// strongly. To get an owning version, consider copying the data into an `ImageBuffer`. This
/// provides many more operations, is possibly faster (if not you may want to open an issue) is
/// generally polished. You can also try to convert this buffer inline, see
/// `ImageBuffer::from_raw`.
pub fn as_view_mut<P>(&mut self) -> Result<ViewMut<&mut [P::Subpixel], P>, Error>
where
P: PixelWithColorType,
Buffer: AsMut<[P::Subpixel]>,
{
if !self.layout.is_normal(NormalForm::PixelPacked) {
return Err(Error::NormalFormRequired(NormalForm::PixelPacked));
}
if self.layout.channels != P::CHANNEL_COUNT {
return Err(Error::WrongColor(P::COLOR_TYPE));
}
let as_mut = self.samples.as_mut();
if !self.layout.fits(as_mut.len()) {
return Err(Error::TooLarge);
}
Ok(ViewMut {
inner: FlatSamples {
samples: as_mut,
layout: self.layout,
color_hint: self.color_hint,
},
phantom: PhantomData,
})
}
/// View the samples as a slice.
///
/// The slice is not limited to the region of the image and not all sample indices are valid
/// indices into this buffer. See `image_mut_slice` as an alternative.
pub fn as_slice<T>(&self) -> &[T]
where
Buffer: AsRef<[T]>,
{
self.samples.as_ref()
}
/// View the samples as a slice.
///
/// The slice is not limited to the region of the image and not all sample indices are valid
/// indices into this buffer. See `image_mut_slice` as an alternative.
pub fn as_mut_slice<T>(&mut self) -> &mut [T]
where
Buffer: AsMut<[T]>,
{
self.samples.as_mut()
}
/// Return the portion of the buffer that holds sample values.
///
/// This may fail when the coordinates in this image are either out-of-bounds of the underlying
/// buffer or can not be represented. Note that the slice may have holes that do not correspond
/// to any sample in the image represented by it.
pub fn image_slice<T>(&self) -> Option<&[T]>
where
Buffer: AsRef<[T]>,
{
let min_length = match self.min_length() {
None => return None,
Some(index) => index,
};
let slice = self.samples.as_ref();
if slice.len() < min_length {
return None;
}
Some(&slice[..min_length])
}
/// Mutable portion of the buffer that holds sample values.
pub fn image_mut_slice<T>(&mut self) -> Option<&mut [T]>
where
Buffer: AsMut<[T]>,
{
let min_length = match self.min_length() {
None => return None,
Some(index) => index,
};
let slice = self.samples.as_mut();
if slice.len() < min_length {
return None;
}
Some(&mut slice[..min_length])
}
/// Move the data into an image buffer.
///
/// This does **not** convert the sample layout. The buffer needs to be in packed row-major form
/// before calling this function. In case of an error, returns the buffer again so that it does
/// not release any allocation.
pub fn try_into_buffer<P>(self) -> Result<ImageBuffer<P, Buffer>, (Error, Self)>
where
P: PixelWithColorType + 'static,
P::Subpixel: 'static,
Buffer: Deref<Target = [P::Subpixel]>,
{
if !self.is_normal(NormalForm::RowMajorPacked) {
return Err((Error::NormalFormRequired(NormalForm::RowMajorPacked), self));
}
if self.layout.channels != P::CHANNEL_COUNT {
return Err((Error::WrongColor(P::COLOR_TYPE), self));
}
if !self.fits(self.samples.deref().len()) {
return Err((Error::TooLarge, self));
}
Ok(
ImageBuffer::from_raw(self.layout.width, self.layout.height, self.samples)
.unwrap_or_else(|| {
panic!("Preconditions should have been ensured before conversion")
}),
)
}
/// Get the minimum length of a buffer such that all in-bounds samples have valid indices.
///
/// This method will allow zero strides, allowing compact representations of monochrome images.
/// To check that no aliasing occurs, try `check_alias_invariants`. For compact images (no
/// aliasing and no unindexed samples) this is `width*height*channels`. But for both of the
/// other cases, the reasoning is slightly more involved.
///
/// # Explanation
///
/// Note that there is a difference between `min_length` and the index of the sample
/// 'one-past-the-end`. This is due to strides that may be larger than the dimension below.
///
/// ## Example with holes
///
/// Let's look at an example of a grayscale image with
/// * `width_stride = 1`
/// * `width = 2`
/// * `height_stride = 3`
/// * `height = 2`
///
/// ```text
/// | x x | x x m | $
/// min_length m ^
/// ^ one-past-the-end $
/// ```
///
/// The difference is also extreme for empty images with large strides. The one-past-the-end
/// sample index is still as large as the largest of these strides while `min_length = 0`.
///
/// ## Example with aliasing
///
/// The concept gets even more important when you allow samples to alias each other. Here we
/// have the buffer of a small grayscale image where this is the case, this time we will first
/// show the buffer and then the individual rows below.
///
/// * `width_stride = 1`
/// * `width = 3`
/// * `height_stride = 2`
/// * `height = 2`
///
/// ```text
/// 1 2 3 4 5 m
/// |1 2 3| row one
/// |3 4 5| row two
/// ^ m min_length
/// ^ ??? one-past-the-end
/// ```
///
/// This time 'one-past-the-end' is not even simply the largest stride times the extent of its
/// dimension. That still points inside the image because `height*height_stride = 4` but also
/// `index_of(1, 2) = 4`.
pub fn min_length(&self) -> Option<usize> {
self.layout.min_length()
}
/// Check if a buffer of length `len` is large enough.
pub fn fits(&self, len: usize) -> bool {
self.layout.fits(len)
}
/// If there are any samples aliasing each other.
///
/// If this is not the case, it would always be safe to allow mutable access to two different
/// samples at the same time. Otherwise, this operation would need additional checks. When one
/// dimension overflows `usize` with its stride we also consider this aliasing.
pub fn has_aliased_samples(&self) -> bool {
self.layout.has_aliased_samples()
}
/// Check if a buffer fulfills the requirements of a normal form.
///
/// Certain conversions have preconditions on the structure of the sample buffer that are not
/// captured (by design) by the type system. These are then checked before the conversion. Such
/// checks can all be done in constant time and will not inspect the buffer content. You can
/// perform these checks yourself when the conversion is not required at this moment but maybe
/// still performed later.
pub fn is_normal(&self, form: NormalForm) -> bool {
self.layout.is_normal(form)
}
/// Check that the pixel and the channel index are in bounds.
///
/// An in-bound coordinate does not yet guarantee that the corresponding calculation of a
/// buffer index does not overflow. However, if such a buffer large enough to hold all samples
/// actually exists in memory, this property of course follows.
pub fn in_bounds(&self, channel: u8, x: u32, y: u32) -> bool {
self.layout.in_bounds(channel, x, y)
}
/// Resolve the index of a particular sample.
///
/// `None` if the index is outside the bounds or does not fit into a `usize`.
pub fn index(&self, channel: u8, x: u32, y: u32) -> Option<usize> {
self.layout.index(channel, x, y)
}
/// Get the theoretical position of sample (x, y, channel).
///
/// The 'check' is for overflow during index calculation, not that it is contained in the
/// image. Two samples may return the same index, even when one of them is out of bounds. This
/// happens when all strides are `0`, i.e. the image is an arbitrarily large monochrome image.
pub fn index_ignoring_bounds(&self, channel: usize, x: usize, y: usize) -> Option<usize> {
self.layout.index_ignoring_bounds(channel, x, y)
}
/// Get an index provided it is inbouds.
///
/// Assumes that the image is backed by some sufficiently large buffer. Then computation can
/// not overflow as we could represent the maximum coordinate. Since overflow is defined either
/// way, this method can not be unsafe.
pub fn in_bounds_index(&self, channel: u8, x: u32, y: u32) -> usize {
self.layout.in_bounds_index(channel, x, y)
}
/// Shrink the image to the minimum of current and given extents.
///
/// This does not modify the strides, so that the resulting sample buffer may have holes
/// created by the shrinking operation. Shrinking could also lead to an non-aliasing image when
/// samples had aliased each other before.
pub fn shrink_to(&mut self, channels: u8, width: u32, height: u32) {
self.layout.shrink_to(channels, width, height)
}
}
impl<'buf, Subpixel> FlatSamples<&'buf [Subpixel]> {
/// Create a monocolor image from a single pixel.
///
/// This can be used as a very cheap source of a `GenericImageView` with an arbitrary number of
/// pixels of a single color, without any dynamic allocation.
///
/// ## Examples
///
/// ```
/// # fn paint_something<T>(_: T) {}
/// use image::{flat::FlatSamples, GenericImage, RgbImage, Rgb};
///
/// let background = Rgb([20, 20, 20]);
/// let bg = FlatSamples::with_monocolor(&background, 200, 200);;
///
/// let mut image = RgbImage::new(200, 200);
/// paint_something(&mut image);
///
/// // Reset the canvas
/// image.copy_from(&bg.as_view().unwrap(), 0, 0);
/// ```
pub fn with_monocolor<P>(pixel: &'buf P, width: u32, height: u32) -> Self
where
P: Pixel<Subpixel = Subpixel>,
Subpixel: crate::Primitive,
{
FlatSamples {
samples: pixel.channels(),
layout: SampleLayout {
channels: P::CHANNEL_COUNT,
channel_stride: 1,
width,
width_stride: 0,
height,
height_stride: 0,
},
// TODO this value is never set. It should be set in all places where the Pixel type implements PixelWithColorType
color_hint: None,
}
}
}
/// A flat buffer that can be used as an image view.
///
/// This is a nearly trivial wrapper around a buffer but at least sanitizes by checking the buffer
/// length first and constraining the pixel type.
///
/// Note that this does not eliminate panics as the `AsRef<[T]>` implementation of `Buffer` may be
/// unreliable, i.e. return different buffers at different times. This of course is a non-issue for
/// all common collections where the bounds check once must be enough.
///
/// # Inner invariants
///
/// * For all indices inside bounds, the corresponding index is valid in the buffer
/// * `P::channel_count()` agrees with `self.inner.layout.channels`
///
#[derive(Clone, Debug)]
pub struct View<Buffer, P: Pixel>
where
Buffer: AsRef<[P::Subpixel]>,
{
inner: FlatSamples<Buffer>,
phantom: PhantomData<P>,
}
/// A mutable owning version of a flat buffer.
///
/// While this wraps a buffer similar to `ImageBuffer`, this is mostly intended as a utility. The
/// library endorsed normalized representation is still `ImageBuffer`. Also, the implementation of
/// `AsMut<[P::Subpixel]>` must always yield the same buffer. Therefore there is no public way to
/// construct this with an owning buffer.
///
/// # Inner invariants
///
/// * For all indices inside bounds, the corresponding index is valid in the buffer
/// * There is no aliasing of samples
/// * The samples are packed, i.e. `self.inner.layout.sample_stride == 1`
/// * `P::channel_count()` agrees with `self.inner.layout.channels`
///
#[derive(Clone, Debug)]
pub struct ViewMut<Buffer, P: Pixel>
where
Buffer: AsMut<[P::Subpixel]>,
{
inner: FlatSamples<Buffer>,
phantom: PhantomData<P>,
}