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
use flate2::read::GzDecoder;
use super::super::DataValue;
use super::dithering::RAND_VALUES;
use super::rice::RICEDecoder;
use super::{
F32Keywords, F64Keywords, I16Keywords, I32Keywords, Keywords, Quantiz, TileDesc, U8Keywords,
};
use crate::error::Error;
use crate::hdu::header::extension::bintable::{BinTable, TileCompressedImage, ZCmpType, ZQuantiz};
use crate::hdu::header::{Bitpix, Header};
use crate::{TableData, TableRowData};
use std::io::{Read, Seek, SeekFrom};
#[derive(Debug)]
pub enum Pixels<R> {
U8(It<R, U8Keywords>),
I16(It<R, I16Keywords>),
I32(It<R, I32Keywords>),
F32(It<R, F32Keywords>),
F64(It<R, F64Keywords>),
}
impl<R> Pixels<R> {
pub fn new(
data: TableData<R>,
header: &Header<BinTable>,
config: &TileCompressedImage,
) -> Self {
match config.z_bitpix {
Bitpix::U8 => Self::U8(It::new(header, data, config)),
Bitpix::I16 => Self::I16(It::new(header, data, config)),
Bitpix::I32 => Self::I32(It::new(header, data, config)),
Bitpix::F32 => Self::F32(It::new(header, data, config)),
Bitpix::F64 => Self::F64(It::new(header, data, config)),
_ => unreachable!(),
}
}
}
#[derive(Debug)]
pub struct It<R, K>
where
K: Keywords,
{
/// An iterator over the row of a binary table
pub row_it: TableRowData<R>,
/// A buffer for storing uncompressed data from GZIP1, GZIP2 or RICE
buf: Vec<u8>,
/// Current tile pointer
desc: TileDesc<K>,
z_tile: Box<[usize]>,
//z_naxis: Box<[usize]>,
z_cmp_type: ZCmpType,
data_compressed_idx: usize,
}
impl<R, K> It<R, K>
where
K: Keywords,
{
fn get_reader(&mut self) -> &mut R {
self.row_it.get_reader()
}
}
impl<R, K> It<R, K>
where
K: Keywords,
{
pub(crate) fn new(
header: &Header<BinTable>,
mut data: TableData<R>,
config: &TileCompressedImage,
) -> Self {
// This buffer is only used if tile compressed image in the gzip compression is to be found
let TileCompressedImage {
z_tilen,
z_cmp_type,
data_compressed_idx,
..
} = config;
// Allocation of a buffer at init of the iterator that is the size of the biggest tiles we can found
// on the tile compressed image. This is simply given by the ZTILEi keyword.
// Some tiles found on the border of the image can be smaller
let n_elems_max = z_tilen.iter().product::<usize>();
// FIXME
// A little precision. The gzdecoder from flate2 seems to unzip data in a stream of u32 i.e. even if the type of data
// to uncompress is byte or short, the result will be cast in a u32. I thus allocate for gzip compression, a buffer of
// n_elems_max * size_in_bytes of u32.
// It seems to be the same for RICE, so the latter rice decompression code is called on i32
let num_bytes_max_tile = n_elems_max * std::mem::size_of::<u32>();
let buf = vec![0_u8; num_bytes_max_tile];
let desc = TileDesc::new(header, config);
// do not read the heap, we will manage our way decompressing the tiles
data.read_the_heap(false);
Self {
buf,
row_it: data.row_iter(),
desc,
data_compressed_idx: *data_compressed_idx,
//z_naxis: z_naxisn.clone(),
z_tile: z_tilen.clone(),
z_cmp_type: *z_cmp_type,
}
}
}
/*
/// Compute the size of the tile from its row position inside the compressed data column
/// FIXME: optimize this computation by using memoization
pub(crate) fn tile_size_from_row_idx(
z_tile: &[usize],
z_naxis: &[usize],
n: usize,
) -> Box<[usize]> {
let d = z_tile.len();
if d == 0 {
// There must be at least one dimension
unreachable!();
} else {
let mut u = vec![0_usize; z_tile.len()];
let s = z_naxis
.iter()
.zip(z_tile.iter())
.map(|(naxisi, tilei)| naxisi.div_ceil(*tilei))
.collect::<Vec<_>>();
// Compute the position inside the first dimension
u[0] = n % s[0];
for i in 1..d {
u[i] = n
- u[0]
- (1..i)
.map(|k| {
let prod_sk = s.iter().take(k).product::<usize>();
u[k] * prod_sk
})
.sum::<usize>();
let prod_si = s.iter().take(i).product::<usize>();
u[i] = (u[i] / prod_si) % s[i];
}
u.iter()
.zip(z_naxis.iter().zip(z_tile.iter()))
.map(|(&u_i, (&naxis, &tilez))| tilez.min(naxis - u_i * tilez))
.collect()
}
}
*/
use std::fmt::Debug;
impl<R> Iterator for It<R, U8Keywords>
where
R: Read + Seek + Debug,
{
// Return a vec of fields because to take into account the repeat count value for that field
type Item = u8;
fn next(&mut self) -> Option<Self::Item> {
// We first retrieve the whole row from the row data iterator
if self.desc.remaining_pixels == 0 {
let row_data = self.row_it.next()?;
let (_, byte_offset) = match row_data[self.data_compressed_idx] {
DataValue::VariableLengthArray32 {
num_elems,
offset_byte,
} => (num_elems as u64, offset_byte as u64),
DataValue::VariableLengthArray64 {
num_elems,
offset_byte,
} => (num_elems, offset_byte),
_ => unreachable!(),
};
let ctx = self.row_it.get_ctx();
let row_idx = self.row_it.get_row_idx();
// Update the tile compressed currently decompressed
let num_pixels = self.z_tile.iter().product::<usize>() as u64;
self.desc.n_pixels = num_pixels;
self.desc.remaining_pixels = num_pixels;
// We jump to the heap at the position of the tile
// Then we decomp the tile and store it into out internal buf
// Finally we go back to the main data table location before jumping to the heap
let main_data_table_offset = row_idx * (ctx.naxis1 as usize);
let off =
// go back to the beginning of the main table data block
- (main_data_table_offset as i64)
// from the beginning of the main table go to the beginning of the heap
+ ctx.theap as i64
// from the beginning of the heap go to the start of the array
+ byte_offset as i64;
self.jump_to_location(
|s| {
let It { buf, row_it, .. } = s;
let reader = row_it.get_reader();
match s.z_cmp_type {
// For GZIP2, the byte shuffling is done in the next method
ZCmpType::Gzip1 | ZCmpType::Gzip2 => {
let mut gz = GzDecoder::new(reader);
gz.read_exact(&mut buf[..])?;
}
// FIXME support bytepix
ZCmpType::Rice { blocksize, .. } => {
let mut rice = RICEDecoder::<_, i32>::new(
reader,
blocksize as i32,
num_pixels as i32,
);
rice.read_exact(&mut buf[..])?;
}
// Other compression not supported, when parsing the bintable extension keywords
// we ensured that z_image is `None` for other compressions than GZIP or RICE
_ => unreachable!(),
}
Ok(())
},
SeekFrom::Current(off),
)
.ok()?;
}
// There is remaining pixels inside our buffer, we simply return the current one
let idx = (self.desc.n_pixels - self.desc.remaining_pixels) as usize;
let value = match self.z_cmp_type {
ZCmpType::Gzip1 | ZCmpType::Gzip2 => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
let off = 4 * idx;
// read from BigEndian, i.e. the most significant byte is at first and the least one is at last position
self.buf[off + 3]
}
ZCmpType::Rice { .. } => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
let off = 4 * idx;
self.buf[off]
}
// Not supported compression/bitpix results in parsing the binary table as normal and thus this part is not reachable
_ => unreachable!(),
};
self.desc.remaining_pixels -= 1;
Some(value)
}
}
impl<R> Iterator for It<R, I16Keywords>
where
R: Read + Seek + Debug,
{
// Return a vec of fields because to take into account the repeat count value for that field
type Item = i16;
fn next(&mut self) -> Option<Self::Item> {
// We first retrieve the whole row from the row data iterator
if self.desc.remaining_pixels == 0 {
let row_data = self.row_it.next()?;
let (_, byte_offset) = match row_data[self.data_compressed_idx] {
DataValue::VariableLengthArray32 {
num_elems,
offset_byte,
} => (num_elems as u64, offset_byte as u64),
DataValue::VariableLengthArray64 {
num_elems,
offset_byte,
} => (num_elems, offset_byte),
_ => unreachable!(),
};
let ctx = self.row_it.get_ctx();
let row_idx = self.row_it.get_row_idx();
// Update the tile compressed currently decompressed
let num_pixels = self.z_tile.iter().product::<usize>() as u64;
self.desc.n_pixels = num_pixels;
self.desc.remaining_pixels = num_pixels;
// We jump to the heap at the position of the tile
// Then we decomp the tile and store it into out internal buf
// Finally we go back to the main data table location before jumping to the heap
let main_data_table_offset = row_idx * (ctx.naxis1 as usize);
let off =
// go back to the beginning of the main table data block
- (main_data_table_offset as i64)
// from the beginning of the main table go to the beginning of the heap
+ ctx.theap as i64
// from the beginning of the heap go to the start of the array
+ byte_offset as i64;
self.jump_to_location(
|s| {
let It { buf, row_it, .. } = s;
let reader = row_it.get_reader();
match s.z_cmp_type {
// For GZIP2, the byte shuffling is done in the next method
ZCmpType::Gzip1 | ZCmpType::Gzip2 => {
let mut gz = GzDecoder::new(reader);
gz.read_exact(&mut buf[..])?;
}
// FIXME support bytepix
ZCmpType::Rice { blocksize, .. } => {
let mut rice = RICEDecoder::<_, i32>::new(
reader,
blocksize as i32,
num_pixels as i32,
);
rice.read_exact(&mut buf[..])?;
}
// Other compression not supported, when parsing the bintable extension keywords
// we ensured that z_image is `None` for other compressions than GZIP or RICE
_ => unreachable!(),
}
Ok(())
},
SeekFrom::Current(off),
)
.ok()?;
}
// There is remaining pixels inside our buffer, we simply return the current one
let idx = (self.desc.n_pixels - self.desc.remaining_pixels) as usize;
let value = match self.z_cmp_type {
ZCmpType::Gzip1 => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
// read from BigEndian, i.e. the most significant byte is at first and the least one is at last position
let off = 4 * idx;
(self.buf[off + 3] as i16) | ((self.buf[off + 2] as i16) << 8)
}
ZCmpType::Gzip2 => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
// read from BigEndian, i.e. the most significant byte is at first and the least one is at last position
let num_bytes = self.buf.len();
let step_msb = num_bytes / 4;
(self.buf[3 * step_msb + idx] as i16) | ((self.buf[2 * step_msb + idx] as i16) << 8)
}
ZCmpType::Rice { .. } => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
let off = 4 * idx;
(self.buf[off] as i16) | ((self.buf[off + 1] as i16) << 8)
}
// Not supported compression/bitpix results in parsing the binary table as normal and thus this part is not reachable
_ => unreachable!(),
};
self.desc.remaining_pixels -= 1;
Some(value)
}
}
impl<R> Iterator for It<R, I32Keywords>
where
R: Read + Seek + Debug,
{
// Return a vec of fields because to take into account the repeat count value for that field
type Item = i32;
fn next(&mut self) -> Option<Self::Item> {
// We first retrieve the whole row from the row data iterator
if self.desc.remaining_pixels == 0 {
let row_data = self.row_it.next()?;
let (_, byte_offset) = match row_data[self.data_compressed_idx] {
DataValue::VariableLengthArray32 {
num_elems,
offset_byte,
} => (num_elems as u64, offset_byte as u64),
DataValue::VariableLengthArray64 {
num_elems,
offset_byte,
} => (num_elems, offset_byte),
_ => unreachable!(),
};
let ctx = self.row_it.get_ctx();
let row_idx = self.row_it.get_row_idx();
// Update the tile compressed currently decompressed
let num_pixels = self.z_tile.iter().product::<usize>() as u64;
self.desc.n_pixels = num_pixels;
self.desc.remaining_pixels = num_pixels;
// We jump to the heap at the position of the tile
// Then we decomp the tile and store it into out internal buf
// Finally we go back to the main data table location before jumping to the heap
let main_data_table_offset = row_idx * (ctx.naxis1 as usize);
let off =
// go back to the beginning of the main table data block
- (main_data_table_offset as i64)
// from the beginning of the main table go to the beginning of the heap
+ ctx.theap as i64
// from the beginning of the heap go to the start of the array
+ byte_offset as i64;
self.jump_to_location(
|s| {
let It { buf, row_it, .. } = s;
let reader = row_it.get_reader();
match s.z_cmp_type {
// For GZIP2, the byte shuffling is done in the next method
ZCmpType::Gzip1 | ZCmpType::Gzip2 => {
let mut gz = GzDecoder::new(reader);
gz.read_exact(&mut buf[..])?;
}
// FIXME support bytepix
ZCmpType::Rice { blocksize, .. } => {
let mut rice = RICEDecoder::<_, i32>::new(
reader,
blocksize as i32,
num_pixels as i32,
);
rice.read_exact(&mut buf[..])?;
}
// Other compression not supported, when parsing the bintable extension keywords
// we ensured that z_image is `None` for other compressions than GZIP or RICE
_ => unreachable!(),
}
Ok(())
},
SeekFrom::Current(off),
)
.ok()?;
}
// There is remaining pixels inside our buffer, we simply return the current one
let idx = (self.desc.n_pixels - self.desc.remaining_pixels) as usize;
let value = match self.z_cmp_type {
ZCmpType::Gzip1 => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
let off = 4 * idx;
i32::from_be_bytes([
self.buf[off],
self.buf[off + 1],
self.buf[off + 2],
self.buf[off + 3],
])
}
ZCmpType::Gzip2 => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
// read from BigEndian, i.e. the most significant byte is at first and the least one is at last position
let num_bytes = self.buf.len();
let step_msb = num_bytes / 4;
((self.buf[idx] as i32) << 24)
| ((self.buf[idx + step_msb] as i32) << 16)
| ((self.buf[idx + 2 * step_msb] as i32) << 8)
| (self.buf[idx + 3 * step_msb] as i32)
}
ZCmpType::Rice { .. } => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
let off = 4 * idx;
i32::from_ne_bytes([
self.buf[off],
self.buf[off + 1],
self.buf[off + 2],
self.buf[off + 3],
])
}
// Not supported compression/bitpix results in parsing the binary table as normal and thus this part is not reachable
_ => unreachable!(),
};
self.desc.remaining_pixels -= 1;
Some(value)
}
}
impl<R> Iterator for It<R, F32Keywords>
where
R: Read + Seek + Debug,
{
// Return a vec of fields because to take into account the repeat count value for that field
type Item = f32;
fn next(&mut self) -> Option<Self::Item> {
// We first retrieve the whole row from the row data iterator
if self.desc.remaining_pixels == 0 {
let row_data = self.row_it.next()?;
let (_, byte_offset) = match row_data[self.data_compressed_idx] {
DataValue::VariableLengthArray32 {
num_elems,
offset_byte,
} => (num_elems as u64, offset_byte as u64),
DataValue::VariableLengthArray64 {
num_elems,
offset_byte,
} => (num_elems, offset_byte),
_ => unreachable!(),
};
let ctx = self.row_it.get_ctx();
let row_idx = self.row_it.get_row_idx();
// Update the tile compressed currently decompressed
let num_pixels = self.z_tile.iter().product::<usize>() as u64;
self.desc.n_pixels = num_pixels;
self.desc.remaining_pixels = num_pixels;
let TileDesc {
keywords:
F32Keywords {
z_scale_idx,
z_zero_idx,
scale,
zero,
z_dither_0,
z_quantiz,
quantiz,
z_blank_idx,
z_blank,
},
..
} = &mut self.desc;
*quantiz = match z_quantiz {
ZQuantiz::SubtractiveDither1 => {
let i0 = (row_idx - 1 + ((*z_dither_0) as usize)) % 10000;
let i1 = (RAND_VALUES[i0] * 500.0).floor() as usize;
Quantiz::SubtractiveDither1 { i1 }
}
ZQuantiz::SubtractiveDither2 => {
let i0 = (row_idx - 1 + (*z_dither_0 as usize)) % 10000;
let i1 = (RAND_VALUES[i0] * 500.0).floor() as usize;
Quantiz::SubtractiveDither2 { i1 }
}
_ => Quantiz::NoDither,
};
*scale = match row_data[*z_scale_idx] {
DataValue::Float { value, .. } => value,
DataValue::Double { value, .. } => value as f32,
_ => unreachable!(),
};
*zero = match row_data[*z_zero_idx] {
DataValue::Float { value, .. } => value,
DataValue::Double { value, .. } => value as f32,
_ => unreachable!(),
};
if let Some(idx) = z_blank_idx {
*z_blank = match row_data[*idx] {
DataValue::UnsignedByte { value, .. } => Some(value as i32),
DataValue::Short { value, .. } => Some(value as i32),
DataValue::Integer { value, .. } => Some(value),
DataValue::Long { value, .. } => Some(value as i32),
_ => unreachable!(),
}
}
// We jump to the heap at the position of the tile
// Then we decomp the tile and store it into out internal buf
// Finally we go back to the main data table location before jumping to the heap
let main_data_table_offset = row_idx * (ctx.naxis1 as usize);
let off =
// go back to the beginning of the main table data block
- (main_data_table_offset as i64)
// from the beginning of the main table go to the beginning of the heap
+ ctx.theap as i64
// from the beginning of the heap go to the start of the array
+ byte_offset as i64;
self.jump_to_location(
|s| {
let It { buf, row_it, .. } = s;
let reader = row_it.get_reader();
match s.z_cmp_type {
// For GZIP2, the byte shuffling is done in the next method
ZCmpType::Gzip1 | ZCmpType::Gzip2 => {
let mut gz = GzDecoder::new(reader);
gz.read_exact(&mut buf[..])?;
}
// FIXME support bytepix
ZCmpType::Rice { blocksize, .. } => {
let mut rice = RICEDecoder::<_, i32>::new(
reader,
blocksize as i32,
num_pixels as i32,
);
rice.read_exact(&mut buf[..])?;
}
// Other compression not supported, when parsing the bintable extension keywords
// we ensured that z_image is `None` for other compressions than GZIP or RICE
_ => unreachable!(),
}
Ok(())
},
SeekFrom::Current(off),
)
.ok()?;
}
// There is remaining pixels inside our buffer, we simply return the current one
let idx = (self.desc.n_pixels - self.desc.remaining_pixels) as usize;
let value = match self.z_cmp_type {
// 32-bit floating point
ZCmpType::Gzip1 => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
let off = 4 * idx;
let value = i32::from_be_bytes([
self.buf[off],
self.buf[off + 1],
self.buf[off + 2],
self.buf[off + 3],
]);
self.desc.keywords.unquantize(value)
}
ZCmpType::Gzip2 => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
// read from BigEndian, i.e. the most significant byte is at first and the least one is at last position
let num_bytes = self.buf.len();
let step_msb = num_bytes / 4;
let value = ((self.buf[idx] as i32) << 24)
| ((self.buf[idx + step_msb] as i32) << 16)
| ((self.buf[idx + 2 * step_msb] as i32) << 8)
| (self.buf[idx + 3 * step_msb] as i32);
self.desc.keywords.unquantize(value)
}
// 32-bit floating point
ZCmpType::Rice { .. } => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
let off = 4 * idx;
let value = i32::from_ne_bytes([
self.buf[off],
self.buf[off + 1],
self.buf[off + 2],
self.buf[off + 3],
]);
self.desc.keywords.unquantize(value)
}
// Not supported compression/bitpix results in parsing the binary table as normal and thus this part is not reachable
_ => unreachable!(),
};
self.desc.remaining_pixels -= 1;
Some(value)
}
}
impl<R> Iterator for It<R, F64Keywords>
where
R: Read + Seek + Debug,
{
// Return a vec of fields because to take into account the repeat count value for that field
type Item = f32;
fn next(&mut self) -> Option<Self::Item> {
// We first retrieve the whole row from the row data iterator
if self.desc.remaining_pixels == 0 {
let row_data = self.row_it.next()?;
let (_, byte_offset) = match row_data[self.data_compressed_idx] {
DataValue::VariableLengthArray32 {
num_elems,
offset_byte,
} => (num_elems as u64, offset_byte as u64),
DataValue::VariableLengthArray64 {
num_elems,
offset_byte,
} => (num_elems, offset_byte),
_ => unreachable!(),
};
let ctx = self.row_it.get_ctx();
let row_idx = self.row_it.get_row_idx();
// Update the tile compressed currently decompressed
let num_pixels = self.z_tile.iter().product::<usize>() as u64;
self.desc.n_pixels = num_pixels;
self.desc.remaining_pixels = num_pixels;
let TileDesc {
keywords:
F64Keywords {
z_scale_idx,
z_zero_idx,
scale,
zero,
z_dither_0,
z_quantiz,
quantiz,
z_blank_idx,
z_blank,
},
..
} = &mut self.desc;
*quantiz = match z_quantiz {
ZQuantiz::SubtractiveDither1 => {
let i0 = (row_idx - 1 + ((*z_dither_0) as usize)) % 10000;
let i1 = (RAND_VALUES[i0] * 500.0).floor() as usize;
Quantiz::SubtractiveDither1 { i1 }
}
ZQuantiz::SubtractiveDither2 => {
let i0 = (row_idx - 1 + (*z_dither_0 as usize)) % 10000;
let i1 = (RAND_VALUES[i0] * 500.0).floor() as usize;
Quantiz::SubtractiveDither2 { i1 }
}
_ => Quantiz::NoDither,
};
*scale = match row_data[*z_scale_idx] {
DataValue::Float { value, .. } => value,
DataValue::Double { value, .. } => value as f32,
_ => unreachable!(),
};
*zero = match row_data[*z_zero_idx] {
DataValue::Float { value, .. } => value,
DataValue::Double { value, .. } => value as f32,
_ => unreachable!(),
};
if let Some(idx) = z_blank_idx {
*z_blank = match row_data[*idx] {
DataValue::UnsignedByte { value, .. } => Some(value as i32),
DataValue::Short { value, .. } => Some(value as i32),
DataValue::Integer { value, .. } => Some(value),
DataValue::Long { value, .. } => Some(value as i32),
_ => unreachable!(),
}
}
// We jump to the heap at the position of the tile
// Then we decomp the tile and store it into out internal buf
// Finally we go back to the main data table location before jumping to the heap
let main_data_table_offset = row_idx * (ctx.naxis1 as usize);
let off =
// go back to the beginning of the main table data block
- (main_data_table_offset as i64)
// from the beginning of the main table go to the beginning of the heap
+ ctx.theap as i64
// from the beginning of the heap go to the start of the array
+ byte_offset as i64;
self.jump_to_location(
|s| {
let It { buf, row_it, .. } = s;
let reader = row_it.get_reader();
match s.z_cmp_type {
// For GZIP2, the byte shuffling is done in the next method
ZCmpType::Gzip1 | ZCmpType::Gzip2 => {
let mut gz = GzDecoder::new(reader);
gz.read_exact(&mut buf[..])?;
}
// FIXME support bytepix
ZCmpType::Rice { blocksize, .. } => {
let mut rice = RICEDecoder::<_, i32>::new(
reader,
blocksize as i32,
num_pixels as i32,
);
rice.read_exact(&mut buf[..])?;
}
// Other compression not supported, when parsing the bintable extension keywords
// we ensured that z_image is `None` for other compressions than GZIP or RICE
_ => unreachable!(),
}
Ok(())
},
SeekFrom::Current(off),
)
.ok()?;
}
// There is remaining pixels inside our buffer, we simply return the current one
let idx = (self.desc.n_pixels - self.desc.remaining_pixels) as usize;
let value = match self.z_cmp_type {
// 32-bit floating point
ZCmpType::Gzip1 => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
let off = 4 * idx;
let value = i32::from_be_bytes([
self.buf[off],
self.buf[off + 1],
self.buf[off + 2],
self.buf[off + 3],
]);
self.desc.keywords.unquantize(value)
}
ZCmpType::Gzip2 => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
// read from BigEndian, i.e. the most significant byte is at first and the least one is at last position
let num_bytes = self.buf.len();
let step_msb = num_bytes / 4;
let value = ((self.buf[idx] as i32) << 24)
| ((self.buf[idx + step_msb] as i32) << 16)
| ((self.buf[idx + 2 * step_msb] as i32) << 8)
| (self.buf[idx + 3 * step_msb] as i32);
self.desc.keywords.unquantize(value)
}
// 32-bit floating point
ZCmpType::Rice { .. } => {
// We need to get the byte index in the buffer storing u32, i.e. 4 bytes per elements
let off = 4 * idx;
let value = i32::from_ne_bytes([
self.buf[off],
self.buf[off + 1],
self.buf[off + 2],
self.buf[off + 3],
]);
self.desc.keywords.unquantize(value)
}
// Not supported compression/bitpix results in parsing the binary table as normal and thus this part is not reachable
_ => unreachable!(),
};
self.desc.remaining_pixels -= 1;
Some(value)
}
}
impl<R, K> It<R, K>
where
R: Seek,
K: Keywords,
{
/// Jump to a specific location of the reader, perform an operation and jumps back to the original position
pub(crate) fn jump_to_location<F>(&mut self, f: F, pos: SeekFrom) -> Result<(), Error>
where
F: FnOnce(&mut Self) -> Result<(), Error>,
{
let old_pos = SeekFrom::Start(self.get_reader().stream_position()?);
self.get_reader().seek(pos)?;
f(self)?;
let _ = self.get_reader().seek(old_pos)?;
Ok(())
}
}