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
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::cmp;
use std::io::{self, Error, ErrorKind, Read, Write};
use super::icontype::{Encoding, IconType, OSType};
use super::image::{Image, PixelFormat};
const ICON_ELEMENT_HEADER_LENGTH: u32 = 8;
#[cfg(feature = "pngio")]
const JPEG_2000_FILE_MAGIC_NUMBER: [u8; 12] = [
0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A,
];
pub struct IconElement {
pub ostype: OSType,
pub data: Vec<u8>,
}
impl IconElement {
pub fn new(ostype: OSType, data: Vec<u8>) -> IconElement {
IconElement { ostype, data }
}
pub fn encode_image_with_type(image: &Image, icon_type: IconType) -> io::Result<IconElement> {
let width = icon_type.pixel_width();
let height = icon_type.pixel_height();
if image.width() != width || image.height() != height {
let msg = format!(
"image has wrong dimensions for {:?} ({}x{} \
instead of {}x{}))",
icon_type,
image.width(),
image.height(),
width,
height
);
return Err(Error::new(ErrorKind::InvalidInput, msg));
}
let mut data: Vec<u8>;
match icon_type.encoding() {
#[cfg(feature = "pngio")]
Encoding::JP2PNG => {
data = Vec::new();
image.write_png(&mut data)?;
}
#[cfg(not(feature = "pngio"))]
Encoding::JP2PNG => unimplemented!(),
Encoding::RLE24 => {
let num_pixels = (width * height) as usize;
match image.pixel_format() {
PixelFormat::RGBA => {
data = encode_rle(image.data(), 4, num_pixels);
}
PixelFormat::RGB => {
data = encode_rle(image.data(), 3, num_pixels);
}
_ => {
let image = image.convert_to(PixelFormat::RGB);
data = encode_rle(image.data(), 3, num_pixels);
}
}
}
Encoding::Mask8 => {
let image = image.convert_to(PixelFormat::Alpha);
data = image.into_data().into_vec();
}
}
Ok(IconElement::new(icon_type.ostype(), data))
}
pub fn decode_image(&self) -> io::Result<Image> {
let icon_type = self.icon_type().ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
format!("unsupported OSType: {}", self.ostype),
)
})?;
let width = icon_type.pixel_width();
let height = icon_type.pixel_width();
match icon_type.encoding() {
#[cfg(feature = "pngio")]
Encoding::JP2PNG => {
if self.data.starts_with(&JPEG_2000_FILE_MAGIC_NUMBER) {
let msg = "element to be decoded contains JPEG 2000 \
data, which is not yet supported";
return Err(Error::new(ErrorKind::InvalidInput, msg));
}
let image = Image::read_png(io::Cursor::new(&self.data))?;
if image.width() != width || image.height() != height {
let msg = format!(
"decoded PNG has wrong dimensions \
({}x{} instead of {}x{})",
image.width(),
image.height(),
width,
height
);
return Err(Error::new(ErrorKind::InvalidData, msg));
}
Ok(image)
}
#[cfg(not(feature = "pngio"))]
Encoding::JP2PNG => unimplemented!(),
Encoding::RLE24 => {
let mut image = Image::new(PixelFormat::RGB, width, height);
decode_rle(&self.data, 3, image.data_mut())?;
Ok(image)
}
Encoding::Mask8 => {
let num_pixels = width * height;
if self.data.len() as u32 != num_pixels {
let msg = format!(
"wrong data payload length ({} \
instead of {})",
self.data.len(),
num_pixels
);
return Err(Error::new(ErrorKind::InvalidData, msg));
}
let mut image = Image::new(PixelFormat::Alpha, width, height);
image.data_mut().clone_from_slice(&self.data);
Ok(image)
}
}
}
pub fn decode_image_with_mask(&self, mask: &IconElement) -> io::Result<Image> {
let icon_type = self.icon_type().ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
format!("unsupported OSType: {}", self.ostype),
)
})?;
let mask_type = icon_type.mask_type().ok_or_else(|| {
let msg = format!("icon type {:?} does not use a mask", icon_type);
Error::new(ErrorKind::InvalidInput, msg)
})?;
assert_eq!(icon_type.encoding(), Encoding::RLE24);
if mask.ostype != mask_type.ostype() {
let msg = format!(
"wrong OSType for mask ('{}' instead of '{}')",
mask.ostype,
mask_type.ostype()
);
return Err(Error::new(ErrorKind::InvalidInput, msg));
}
let width = icon_type.pixel_width();
let height = icon_type.pixel_height();
let num_pixels = (width * height) as usize;
if mask.data.len() != num_pixels {
let msg = format!(
"wrong mask data payload length ({} instead \
of {})",
mask.data.len(),
num_pixels
);
return Err(Error::new(ErrorKind::InvalidInput, msg));
}
let mut image = Image::new(PixelFormat::RGBA, width, height);
decode_rle(&self.data, 4, image.data_mut())?;
for (i, &alpha) in mask.data.iter().enumerate() {
image.data_mut()[4 * i + 3] = alpha;
}
Ok(image)
}
pub fn icon_type(&self) -> Option<IconType> {
IconType::from_ostype(self.ostype)
}
pub fn read<R: Read>(mut reader: R) -> io::Result<IconElement> {
let mut raw_ostype = [0u8; 4];
reader.read_exact(&mut raw_ostype)?;
let element_length = reader.read_u32::<BigEndian>()?;
if element_length < ICON_ELEMENT_HEADER_LENGTH {
return Err(Error::new(ErrorKind::InvalidData, "invalid element length"));
}
let data_length = element_length - ICON_ELEMENT_HEADER_LENGTH;
let mut data = vec![0u8; data_length as usize];
reader.read_exact(&mut data)?;
Ok(IconElement::new(OSType(raw_ostype), data))
}
pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
let OSType(ref raw_ostype) = self.ostype;
writer.write_all(raw_ostype)?;
writer.write_u32::<BigEndian>(self.total_length())?;
writer.write_all(&self.data)?;
Ok(())
}
pub fn total_length(&self) -> u32 {
ICON_ELEMENT_HEADER_LENGTH + (self.data.len() as u32)
}
}
fn encode_rle(input: &[u8], num_input_channels: usize, num_pixels: usize) -> Vec<u8> {
assert!(num_input_channels == 3 || num_input_channels == 4);
let mut output = Vec::new();
if num_pixels == 128 * 128 {
output.extend_from_slice(&[0, 0, 0, 0]);
}
for channel in 0..3 {
let mut pixel: usize = 0;
let mut literal_start: usize = 0;
while pixel < num_pixels {
let value = input[num_input_channels * pixel + channel];
let mut run_length = 1;
while pixel + run_length < num_pixels
&& input[num_input_channels * (pixel + run_length) + channel] == value
&& run_length < 130
{
run_length += 1;
}
if run_length >= 3 {
while literal_start < pixel {
let literal_length = cmp::min(128, pixel - literal_start);
output.push((literal_length - 1) as u8);
for i in 0..literal_length {
output.push(input[num_input_channels * (literal_start + i) + channel]);
}
literal_start += literal_length;
}
output.push((run_length + 125) as u8);
output.push(value);
pixel += run_length;
literal_start = pixel;
} else {
pixel += run_length;
}
}
while literal_start < pixel {
let literal_length = cmp::min(128, pixel - literal_start);
output.push((literal_length - 1) as u8);
for i in 0..literal_length {
output.push(input[num_input_channels * (literal_start + i) + channel]);
}
literal_start += literal_length;
}
}
output
}
fn decode_rle(input: &[u8], num_output_channels: usize, output: &mut [u8]) -> io::Result<()> {
assert!(num_output_channels == 3 || num_output_channels == 4);
assert_eq!(output.len() % num_output_channels, 0);
let num_pixels = output.len() / num_output_channels;
let skip: usize = if input.starts_with(&[0, 0, 0, 0]) {
4
} else {
0
};
let input = &input[skip..input.len()];
let mut iter = input.iter();
let mut remaining: usize = 0;
let mut within_run = false;
let mut run_value: u8 = 0;
for channel in 0..3 {
for pixel in 0..num_pixels {
if remaining == 0 {
let next: u8 = *iter.next().ok_or_else(rle_error)?;
if next < 128 {
remaining = (next as usize) + 1;
within_run = false;
} else {
remaining = (next as usize) - 125;
within_run = true;
run_value = *iter.next().ok_or_else(rle_error)?;
}
}
output[num_output_channels * pixel + channel] = if within_run {
run_value
} else {
*iter.next().ok_or_else(rle_error)?
};
remaining -= 1;
}
if remaining != 0 {
return Err(rle_error());
}
}
if iter.next().is_some() {
Err(rle_error())
} else {
Ok(())
}
}
fn rle_error() -> Error {
Error::new(ErrorKind::InvalidData, "invalid RLE-compressed data")
}
#[cfg(test)]
mod tests {
use super::super::icontype::{IconType, OSType};
use super::super::image::{Image, PixelFormat};
use super::*;
#[test]
fn encode_rle() {
let mut image = Image::new(PixelFormat::Gray, 16, 16);
image.data_mut()[0] = 44;
image.data_mut()[1] = 55;
image.data_mut()[2] = 66;
image.data_mut()[3] = 66;
image.data_mut()[4] = 66;
let element = IconElement::encode_image_with_type(&image, IconType::RGB24_16x16)
.expect("failed to encode image");
assert_eq!(element.ostype, OSType(*b"is32"));
assert_eq!(element.data[0..5], [1, 44, 55, 128, 66]);
}
#[test]
fn decode_rle() {
let data: Vec<u8> = vec![
0, 12, 255, 0, 250, 0, 128, 34, 255, 0, 248, 0, 1, 56, 99, 255, 0, 249, 0,
];
let element = IconElement::new(OSType(*b"is32"), data);
let image = element.decode_image().expect("failed to decode image");
assert_eq!(image.pixel_format(), PixelFormat::RGB);
assert_eq!(image.width(), 16);
assert_eq!(image.height(), 16);
assert_eq!(image.data()[0], 12);
assert_eq!(image.data()[1], 34);
assert_eq!(image.data()[2], 56);
}
#[test]
fn decode_rle_skip_extra_zeros() {
let data: Vec<u8> = vec![
0, 0, 0, 0, 0, 12, 255, 0, 250, 0, 128, 34, 255, 0, 248, 0, 1, 56, 99, 255, 0, 249, 0,
];
let element = IconElement::new(OSType(*b"is32"), data);
let image = element.decode_image().expect("failed to decode image");
assert_eq!(image.data()[0], 12);
assert_eq!(image.data()[1], 34);
assert_eq!(image.data()[2], 56);
}
#[test]
fn encode_mask() {
let mut image = Image::new(PixelFormat::Alpha, 16, 16);
image.data_mut()[2] = 127;
let element = IconElement::encode_image_with_type(&image, IconType::Mask8_16x16)
.expect("failed to encode image");
assert_eq!(element.ostype, OSType(*b"s8mk"));
assert_eq!(element.data[2], 127);
}
#[test]
fn decode_mask() {
let mut data = vec![0u8; 256];
data[2] = 127;
let element = IconElement::new(OSType(*b"s8mk"), data);
let image = element.decode_image().expect("failed to decode image");
assert_eq!(image.pixel_format(), PixelFormat::Alpha);
assert_eq!(image.width(), 16);
assert_eq!(image.height(), 16);
assert_eq!(image.data()[2], 127);
}
#[test]
fn decode_rle_with_mask() {
let color_data: Vec<u8> = vec![
0, 12, 255, 0, 250, 0, 128, 34, 255, 0, 248, 0, 1, 56, 99, 255, 0, 249, 0,
];
let color_element = IconElement::new(OSType(*b"is32"), color_data);
let mask_data = vec![78u8; 256];
let mask_element = IconElement::new(OSType(*b"s8mk"), mask_data);
let image = color_element
.decode_image_with_mask(&mask_element)
.expect("failed to decode image");
assert_eq!(image.pixel_format(), PixelFormat::RGBA);
assert_eq!(image.width(), 16);
assert_eq!(image.height(), 16);
assert_eq!(image.data()[0], 12);
assert_eq!(image.data()[1], 34);
assert_eq!(image.data()[2], 56);
assert_eq!(image.data()[3], 78);
}
}