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
use std::{borrow::Cow, io::Write, slice::from_ref};

use crate::{bytecast, tags::Type, TiffError, TiffFormatError, TiffResult};

use super::writer::TiffWriter;

/// Trait for types that can be encoded in a tiff file
pub trait TiffValue {
    const BYTE_LEN: u8;
    const FIELD_TYPE: Type;
    fn count(&self) -> usize;
    fn bytes(&self) -> usize {
        self.count() * usize::from(Self::BYTE_LEN)
    }

    /// Access this value as an contiguous sequence of bytes.
    /// If their is no trivial representation, allocate it on the heap.
    fn data(&self) -> Cow<[u8]>;

    /// Write this value to a TiffWriter.
    /// While the default implementation will work in all cases, it may require unnecessary allocations.
    /// The written bytes of any custom implementation MUST be the same as yielded by `self.data()`.
    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_bytes(&self.data())?;
        Ok(())
    }
}

impl TiffValue for [u8] {
    const BYTE_LEN: u8 = 1;
    const FIELD_TYPE: Type = Type::BYTE;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(self)
    }
}

impl TiffValue for [i8] {
    const BYTE_LEN: u8 = 1;
    const FIELD_TYPE: Type = Type::SBYTE;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::i8_as_ne_bytes(self))
    }
}

impl TiffValue for [u16] {
    const BYTE_LEN: u8 = 2;
    const FIELD_TYPE: Type = Type::SHORT;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::u16_as_ne_bytes(self))
    }
}

impl TiffValue for [i16] {
    const BYTE_LEN: u8 = 2;
    const FIELD_TYPE: Type = Type::SSHORT;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::i16_as_ne_bytes(self))
    }
}

impl TiffValue for [u32] {
    const BYTE_LEN: u8 = 4;
    const FIELD_TYPE: Type = Type::LONG;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::u32_as_ne_bytes(self))
    }
}

impl TiffValue for [i32] {
    const BYTE_LEN: u8 = 4;
    const FIELD_TYPE: Type = Type::SLONG;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::i32_as_ne_bytes(self))
    }
}

impl TiffValue for [u64] {
    const BYTE_LEN: u8 = 8;
    const FIELD_TYPE: Type = Type::LONG8;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::u64_as_ne_bytes(self))
    }
}

impl TiffValue for [i64] {
    const BYTE_LEN: u8 = 8;
    const FIELD_TYPE: Type = Type::SLONG8;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::i64_as_ne_bytes(self))
    }
}

impl TiffValue for [f32] {
    const BYTE_LEN: u8 = 4;
    const FIELD_TYPE: Type = Type::FLOAT;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        // We write using native endian so this should be safe
        Cow::Borrowed(bytecast::f32_as_ne_bytes(self))
    }
}

impl TiffValue for [f64] {
    const BYTE_LEN: u8 = 8;
    const FIELD_TYPE: Type = Type::DOUBLE;

    fn count(&self) -> usize {
        self.len()
    }

    fn data(&self) -> Cow<[u8]> {
        // We write using native endian so this should be safe
        Cow::Borrowed(bytecast::f64_as_ne_bytes(self))
    }
}

impl TiffValue for u8 {
    const BYTE_LEN: u8 = 1;
    const FIELD_TYPE: Type = Type::BYTE;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_u8(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(from_ref(self))
    }
}

impl TiffValue for i8 {
    const BYTE_LEN: u8 = 1;
    const FIELD_TYPE: Type = Type::SBYTE;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_i8(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::i8_as_ne_bytes(from_ref(self)))
    }
}

impl TiffValue for u16 {
    const BYTE_LEN: u8 = 2;
    const FIELD_TYPE: Type = Type::SHORT;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_u16(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::u16_as_ne_bytes(from_ref(self)))
    }
}

impl TiffValue for i16 {
    const BYTE_LEN: u8 = 2;
    const FIELD_TYPE: Type = Type::SSHORT;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_i16(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::i16_as_ne_bytes(from_ref(self)))
    }
}

impl TiffValue for u32 {
    const BYTE_LEN: u8 = 4;
    const FIELD_TYPE: Type = Type::LONG;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_u32(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::u32_as_ne_bytes(from_ref(self)))
    }
}

impl TiffValue for i32 {
    const BYTE_LEN: u8 = 4;
    const FIELD_TYPE: Type = Type::SLONG;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_i32(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::i32_as_ne_bytes(from_ref(self)))
    }
}

impl TiffValue for u64 {
    const BYTE_LEN: u8 = 8;
    const FIELD_TYPE: Type = Type::LONG8;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_u64(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::u64_as_ne_bytes(from_ref(self)))
    }
}

impl TiffValue for i64 {
    const BYTE_LEN: u8 = 8;
    const FIELD_TYPE: Type = Type::SLONG8;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_i64(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::i64_as_ne_bytes(from_ref(self)))
    }
}

impl TiffValue for f32 {
    const BYTE_LEN: u8 = 4;
    const FIELD_TYPE: Type = Type::FLOAT;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_f32(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::f32_as_ne_bytes(from_ref(self)))
    }
}

impl TiffValue for f64 {
    const BYTE_LEN: u8 = 8;
    const FIELD_TYPE: Type = Type::DOUBLE;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_f64(*self)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::f64_as_ne_bytes(from_ref(self)))
    }
}

impl TiffValue for Ifd {
    const BYTE_LEN: u8 = 4;
    const FIELD_TYPE: Type = Type::IFD;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_u32(self.0)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::u32_as_ne_bytes(from_ref(&self.0)))
    }
}

impl TiffValue for Ifd8 {
    const BYTE_LEN: u8 = 8;
    const FIELD_TYPE: Type = Type::IFD8;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_u64(self.0)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Borrowed(bytecast::u64_as_ne_bytes(from_ref(&self.0)))
    }
}

impl TiffValue for Rational {
    const BYTE_LEN: u8 = 8;
    const FIELD_TYPE: Type = Type::RATIONAL;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_u32(self.n)?;
        writer.write_u32(self.d)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Owned({
            let first_dword = bytecast::u32_as_ne_bytes(from_ref(&self.n));
            let second_dword = bytecast::u32_as_ne_bytes(from_ref(&self.d));
            [first_dword, second_dword].concat()
        })
    }
}

impl TiffValue for SRational {
    const BYTE_LEN: u8 = 8;
    const FIELD_TYPE: Type = Type::SRATIONAL;

    fn count(&self) -> usize {
        1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        writer.write_i32(self.n)?;
        writer.write_i32(self.d)?;
        Ok(())
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Owned({
            let first_dword = bytecast::i32_as_ne_bytes(from_ref(&self.n));
            let second_dword = bytecast::i32_as_ne_bytes(from_ref(&self.d));
            [first_dword, second_dword].concat()
        })
    }
}

impl TiffValue for str {
    const BYTE_LEN: u8 = 1;
    const FIELD_TYPE: Type = Type::ASCII;

    fn count(&self) -> usize {
        self.len() + 1
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        if self.is_ascii() && !self.bytes().any(|b| b == 0) {
            writer.write_bytes(self.as_bytes())?;
            writer.write_u8(0)?;
            Ok(())
        } else {
            Err(TiffError::FormatError(TiffFormatError::InvalidTag))
        }
    }

    fn data(&self) -> Cow<[u8]> {
        Cow::Owned({
            if self.is_ascii() && !self.bytes().any(|b| b == 0) {
                let bytes: &[u8] = self.as_bytes();
                [bytes, &[0]].concat()
            } else {
                vec![]
            }
        })
    }
}

impl<'a, T: TiffValue + ?Sized> TiffValue for &'a T {
    const BYTE_LEN: u8 = T::BYTE_LEN;
    const FIELD_TYPE: Type = T::FIELD_TYPE;

    fn count(&self) -> usize {
        (*self).count()
    }

    fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
        (*self).write(writer)
    }

    fn data(&self) -> Cow<[u8]> {
        T::data(self)
    }
}

macro_rules! impl_tiff_value_for_contiguous_sequence {
    ($inner_type:ty; $bytes:expr; $field_type:expr) => {
        impl $crate::encoder::TiffValue for [$inner_type] {
            const BYTE_LEN: u8 = $bytes;
            const FIELD_TYPE: Type = $field_type;

            fn count(&self) -> usize {
                self.len()
            }

            fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
                for x in self {
                    x.write(writer)?;
                }
                Ok(())
            }

            fn data(&self) -> Cow<[u8]> {
                let mut buf: Vec<u8> = Vec::with_capacity(Self::BYTE_LEN as usize * self.len());
                for x in self {
                    buf.extend_from_slice(&x.data());
                }
                Cow::Owned(buf)
            }
        }
    };
}

impl_tiff_value_for_contiguous_sequence!(Ifd; 4; Type::IFD);
impl_tiff_value_for_contiguous_sequence!(Ifd8; 8; Type::IFD8);
impl_tiff_value_for_contiguous_sequence!(Rational; 8; Type::RATIONAL);
impl_tiff_value_for_contiguous_sequence!(SRational; 8; Type::SRATIONAL);

/// Type to represent tiff values of type `IFD`
#[derive(Clone)]
pub struct Ifd(pub u32);

/// Type to represent tiff values of type `IFD8`
#[derive(Clone)]
pub struct Ifd8(pub u64);

/// Type to represent tiff values of type `RATIONAL`
#[derive(Clone)]
pub struct Rational {
    pub n: u32,
    pub d: u32,
}

/// Type to represent tiff values of type `SRATIONAL`
#[derive(Clone)]
pub struct SRational {
    pub n: i32,
    pub d: i32,
}