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
use super::*;

/// Way the function is defined in.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum FunctionType {
    /// A function that is derived from a set of sampled data.
    Sampled,
    /// A exponential function.
    Exponential,
    /// A composite function made up of multiple other functions.
    Stitching,
    /// A postscript function.
    PostScript,
}

impl FunctionType {
    pub(crate) fn to_int(self) -> i32 {
        match self {
            Self::Sampled => 0,
            Self::Exponential => 2,
            Self::Stitching => 3,
            Self::PostScript => 4,
        }
    }
}

macro_rules! common_func_methods {
    () => {
        /// Write the `/Domain` attribute to set where the function is defined.
        /// Required.
        pub fn domain(&mut self, domain: impl IntoIterator<Item = f32>) -> &mut Self {
            self.insert(Name(b"Domain")).array().items(domain);
            self
        }

        /// Write the `/Range` attribute.
        ///
        /// Required for sampled and PostScript functions.
        pub fn range(&mut self, range: impl IntoIterator<Item = f32>) -> &mut Self {
            self.insert(Name(b"Range")).array().items(range);
            self
        }
    };
}

/// Writer for a _sampled function stream_. PDF 1.2+.
///
/// This struct is created by [`Chunk::sampled_function`].
pub struct SampledFunction<'a> {
    stream: Stream<'a>,
}

impl<'a> SampledFunction<'a> {
    /// Create a new sampled function writer.
    pub(crate) fn start(mut stream: Stream<'a>) -> Self {
        stream.pair(Name(b"FunctionType"), FunctionType::Sampled.to_int());
        Self { stream }
    }

    common_func_methods!();

    /// Write the `/Size` attribute.
    ///
    /// Sets the number of input samples per dimension. Required.
    pub fn size(&mut self, size: impl IntoIterator<Item = i32>) -> &mut Self {
        self.insert(Name(b"Size")).array().items(size);
        self
    }

    /// Write the `/BitsPerSample` attribute.
    ///
    /// Sets the number of bits per input sample. Required.
    pub fn bits_per_sample(&mut self, bits: i32) -> &mut Self {
        self.pair(Name(b"BitsPerSample"), bits);
        self
    }

    /// Write the `/Order` attribute.
    ///
    /// Choose the implementation kind.
    pub fn order(&mut self, order: InterpolationOrder) -> &mut Self {
        self.pair(Name(b"Order"), order.to_int());
        self
    }

    /// Write the `/Encode` attribute.
    ///
    /// For each sample, define how the input is mapped to the domain range.
    pub fn encode(&mut self, encode: impl IntoIterator<Item = f32>) -> &mut Self {
        self.insert(Name(b"Encode")).array().items(encode);
        self
    }

    /// Write the `/Decode` attribute.
    ///
    /// For each sample, define how the output is mapped to the output range.
    pub fn decode(&mut self, decode: impl IntoIterator<Item = f32>) -> &mut Self {
        self.insert(Name(b"Decode")).array().items(decode);
        self
    }
}

deref!('a, SampledFunction<'a> => Stream<'a>, stream);

/// How to interpolate between the samples in a function of the
/// sampled type.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum InterpolationOrder {
    /// Linear spline interpolation.
    Linear,
    /// Cubic spline interpolation.
    Cubic,
}

impl InterpolationOrder {
    pub(crate) fn to_int(self) -> i32 {
        match self {
            Self::Linear => 1,
            Self::Cubic => 3,
        }
    }
}

/// Writer for an _exponential function dictionary_. PDF 1.3+.
///
/// The function result is `y_i = C0_i + x^N * (C1_i - C0_i)` where `i` is the
/// current dimension.
///
/// This struct is created by [`Chunk::exponential_function`] and
/// [`writers::Separation::tint_exponential`].
pub struct ExponentialFunction<'a> {
    dict: Dict<'a>,
}

writer!(ExponentialFunction: |obj| {
    let mut dict = obj.dict();
    dict.pair(Name(b"FunctionType"), FunctionType::Exponential.to_int());
    Self { dict }
});

impl<'a> ExponentialFunction<'a> {
    common_func_methods!();

    /// Write the `/C0` array.
    ///
    /// Function result when input is zero. Default is `0.0`.
    pub fn c0(&mut self, c0: impl IntoIterator<Item = f32>) -> &mut Self {
        self.insert(Name(b"C0")).array().items(c0);
        self
    }

    /// Write the `/C1` array.
    ///
    /// Function result when input is one. Default is `1.0`.
    pub fn c1(&mut self, c1: impl IntoIterator<Item = f32>) -> &mut Self {
        self.insert(Name(b"C1")).array().items(c1);
        self
    }

    /// Write the `/N` attribute.
    ///
    /// The interpolation exponent. Required.
    pub fn n(&mut self, n: f32) -> &mut Self {
        self.pair(Name(b"N"), n);
        self
    }
}

deref!('a, ExponentialFunction<'a> => Dict<'a>, dict);

/// Writer for a _stitching function dictionary_. PDF 1.3+.
///
/// The function result is `y_i = C0_i + x^N * (C1_i - C0_i)` where `i` is the
/// current dimension.
///
/// This struct is created by [`Chunk::stitching_function`] and
/// [`writers::Separation::tint_stitching`].
pub struct StitchingFunction<'a> {
    dict: Dict<'a>,
}

writer!(StitchingFunction: |obj| {
    let mut dict = obj.dict();
    dict.pair(Name(b"FunctionType"), FunctionType::Stitching.to_int());
    Self { dict }
});

impl<'a> StitchingFunction<'a> {
    common_func_methods!();

    /// Write the `/Functions` array.
    ///
    /// The functions to be stitched. Required.
    pub fn functions(&mut self, functions: impl IntoIterator<Item = Ref>) -> &mut Self {
        self.insert(Name(b"Functions")).array().items(functions);
        self
    }

    /// Write the `/Bounds` array.
    ///
    /// The boundaries of the intervals that each function is called in. The
    /// array has one less entry than there are stiched functions. Required.
    pub fn bounds(&mut self, bounds: impl IntoIterator<Item = f32>) -> &mut Self {
        self.insert(Name(b"Bounds")).array().items(bounds);
        self
    }

    /// Write the `/Encode` array.
    ///
    /// Pair of values for each function that maps the stitching domain subsets
    /// to the function domain. Required.
    pub fn encode(&mut self, encode: impl IntoIterator<Item = f32>) -> &mut Self {
        self.insert(Name(b"Encode")).array().items(encode);
        self
    }
}

deref!('a, StitchingFunction<'a> => Dict<'a>, dict);

/// Writer for a _PostScript function stream_. PDF 1.3+.
///
/// This struct is created by [`Chunk::post_script_function`].
pub struct PostScriptFunction<'a> {
    stream: Stream<'a>,
}

impl<'a> PostScriptFunction<'a> {
    /// Create a new postscript function writer.
    pub(crate) fn start(mut stream: Stream<'a>) -> Self {
        stream.pair(Name(b"FunctionType"), FunctionType::PostScript.to_int());
        Self { stream }
    }

    common_func_methods!();
}

deref!('a, PostScriptFunction<'a> => Stream<'a>, stream);

/// PostScript operators for use in Type 4 functions.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PostScriptOp<'a> {
    /// Push a real number.
    Real(f32),
    /// Push an integer number.
    Integer(i32),

    /// Absolute value. One number argument.
    Abs,
    /// Addition. Two number arguments.
    Add,
    /// Arc tangent. One number argument.
    Atan,
    /// Round up to the nearest integer. One number argument.
    Ceiling,
    /// Cosine. One number argument.
    Cos,
    /// Convert to integer. One real number argument.
    Cvi,
    /// Convert to real. One integer argument.
    Cvr,
    /// Divide. Two number arguments.
    Div,
    /// Raise the base to the exponent. Two number arguments.
    Exp,
    /// Round down to the nearest integer. One number argument.
    Floor,
    /// Integer division. Two integer arguments.
    Idiv,
    /// Natural logarithm. One number argument.
    Ln,
    /// Logarithm base 10. One number argument.
    Log,
    /// Modulo. Two integer arguments.
    Mod,
    /// Multiply. Two number arguments.
    Mul,
    /// Negate. One number argument.
    Neg,
    /// Round to the nearest integer. One number argument.
    Round,
    /// Sine. One number argument.
    Sin,
    /// Square root. One number argument.
    Sqrt,
    /// Subtract. Two number arguments.
    Sub,
    /// Remove fractional part. One number argument.
    Truncate,

    /// Logical bitwise And. Two integer or boolean arguments.
    And,
    /// Bitwise shift left. Negative shifts possible. Two integer arguments.
    Bitshift,
    /// Equals. Any two arguments of the same type.
    Eq,
    /// Constant false.
    False,
    /// Greater than or equal. Two number arguments.
    Ge,
    /// Greater than. Two number arguments.
    Gt,
    /// Less than or equal. Two number arguments.
    Le,
    /// Less than. Two number arguments.
    Lt,
    /// Not equals. Any two arguments of the same type.
    Ne,
    /// Bitwise logical not. One integer or boolean argument.
    Not,
    /// Bitwise logical or. Two integer or boolean arguments.
    Or,
    /// Constant true.
    True,
    /// Bitwise logical exclusive or. Two integer or boolean arguments.
    Xor,

    /// Conditional. Runs if boolean argument is true.
    If(&'a [Self]),
    /// Conditional. Decides which branch to run depending on boolean argument.
    IfElse(&'a [Self], &'a [Self]),

    /// Copy the top elements. One integer argument.
    Copy,
    /// Duplicate the top element.
    Dup,
    /// Exchange the two top elements.
    Exch,
    /// Duplicate any element. One integer argument.
    Index,
    /// Discard the top element.
    Pop,
    /// Roll `n` elements up `j` times. Two integer arguments.
    Roll,
}

impl<'a> PostScriptOp<'a> {
    /// Encode a slice of operations into a byte stream.
    pub fn encode(ops: &[Self]) -> Vec<u8> {
        let mut buf = Vec::new();
        Self::write_slice(ops, &mut buf);
        buf
    }

    fn write_slice(ops: &[Self], buf: &mut Vec<u8>) {
        buf.push(b'{');
        if ops.len() > 1 {
            buf.push(b'\n');
        }
        for op in ops {
            op.write(buf);
            buf.push(b'\n');
        }
        if ops.len() == 1 {
            buf.pop();
        }
        buf.push(b'}');
    }

    fn write(&self, buf: &mut Vec<u8>) {
        match *self {
            Self::Real(r) => buf.push_decimal(r),
            Self::Integer(i) => buf.push_val(i),
            Self::If(ops) => {
                Self::write_slice(ops, buf);
                buf.push(b'\n');
                buf.extend(self.operator());
            }
            Self::IfElse(ops1, ops2) => {
                Self::write_slice(ops1, buf);
                buf.push(b'\n');
                Self::write_slice(ops2, buf);
                buf.push(b'\n');
                buf.extend(self.operator());
            }
            _ => buf.extend(self.operator()),
        }
    }

    fn operator(&self) -> &'static [u8] {
        match self {
            Self::Real(_) | Self::Integer(_) => b"",
            Self::Abs => b"abs",
            Self::Add => b"add",
            Self::Atan => b"atan",
            Self::Ceiling => b"ceiling",
            Self::Cos => b"cos",
            Self::Cvi => b"cvi",
            Self::Cvr => b"cvr",
            Self::Div => b"div",
            Self::Exp => b"exp",
            Self::Floor => b"floor",
            Self::Idiv => b"idiv",
            Self::Ln => b"ln",
            Self::Log => b"log",
            Self::Mod => b"mod",
            Self::Mul => b"mul",
            Self::Neg => b"neg",
            Self::Round => b"round",
            Self::Sin => b"sin",
            Self::Sqrt => b"sqrt",
            Self::Sub => b"sub",
            Self::Truncate => b"truncate",
            Self::And => b"and",
            Self::Bitshift => b"bitshift",
            Self::Eq => b"eq",
            Self::False => b"false",
            Self::Ge => b"ge",
            Self::Gt => b"gt",
            Self::Le => b"le",
            Self::Lt => b"lt",
            Self::Ne => b"ne",
            Self::Not => b"not",
            Self::Or => b"or",
            Self::True => b"true",
            Self::Xor => b"xor",
            Self::If(_) => b"if",
            Self::IfElse(_, _) => b"ifelse",
            Self::Copy => b"copy",
            Self::Dup => b"dup",
            Self::Exch => b"exch",
            Self::Index => b"index",
            Self::Pop => b"pop",
            Self::Roll => b"roll",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_post_script_encoding() {
        use PostScriptOp::*;

        let ops = [
            Real(3.0),
            Real(2.0),
            Mul,
            Exch,
            Dup,
            Real(0.0),
            Ge,
            IfElse(&[Real(1.0), Add], &[Neg]),
            Add,
        ];

        assert_eq!(
            PostScriptOp::encode(&ops),
            b"{\n3.0\n2.0\nmul\nexch\ndup\n0.0\nge\n{\n1.0\nadd\n}\n{neg}\nifelse\nadd\n}"
        );
    }
}