immeta/generic.rs
1use std::io::{BufRead, Cursor, Seek, SeekFrom, BufReader};
2use std::fs::File;
3use std::path::Path;
4use std::result;
5
6use types::{Result, Dimensions};
7use traits::LoadableMetadata;
8use formats::{jpeg, png, gif, webp};
9use generic::markers::MetadataMarker;
10
11/// Contains metadata marker types.
12///
13/// Metadata markers is a convenient way to access metadata loading functions for particular
14/// image types. They are also integrated with `GenericMetadata`, providing a convenient
15/// syntax to downcast a `GenericMetadata` value to a specific metadata type.
16///
17/// Metadata marker types can be used directly, for example:
18/// ```ignore
19/// use immeta::markers::Jpeg;
20///
21/// let metadata = Jpeg::load_from_file("kitty.jpg").unwrap();
22/// ```
23///
24/// They can also be used together with `GenericMetadata`:
25/// ```ignore
26/// use immeta::markers::Jpeg;
27///
28/// let gmd = immeta::load_from_file("kitty.jpg").unwrap();
29/// let jpeg_metadata: Jpeg::Metadata = gmd.into::<Jpeg>().unwrap();
30/// ```
31///
32/// Alternatively, you can use `as_ref()`:
33/// ```ignore
34/// let jpeg_metadata: &Jpeg::Metadata = gmd.as_ref::<Jpeg>().unwrap();
35/// ```
36///
37/// `MetadataMarker::Metadata` associated type always points to concrete metadata type
38/// from one of `immeta::formats` submodules.
39pub mod markers {
40 use std::io::{BufRead, Seek};
41 use std::path::Path;
42 use std::result;
43
44 use generic::GenericMetadata;
45 use types::Result;
46 use formats::{jpeg, png, gif, webp};
47
48 /// A marker trait for a specific metadata type.
49 pub trait MetadataMarker {
50 type Metadata;
51
52 /// Tries to convert the given `GenericMetadata` instance into a concrete metadata type.
53 ///
54 /// If the generic value really contains the associated metadata type, then `Ok` variant
55 /// is returned; otherwise `Err` variant containing the original value is returned.
56 ///
57 /// # Examples
58 ///
59 /// ```no_run
60 /// use immeta::markers::Jpeg;
61 /// use immeta::formats::jpeg;
62 /// use immeta::GenericMetadata;
63 ///
64 /// let generic = immeta::load_from_file("kitty.jpg").unwrap();
65 /// let concrete: Result<jpeg::Metadata, GenericMetadata> = generic.into::<Jpeg>();
66 /// assert!(concrete.is_ok());
67 /// ```
68 ///
69 /// ```no_run
70 /// use immeta::markers::Jpeg;
71 /// use immeta::formats::jpeg;
72 /// use immeta::GenericMetadata;
73 ///
74 /// let generic = immeta::load_from_file("kitty.png").unwrap();
75 /// let concrete: Result<jpeg::Metadata, GenericMetadata> = generic.into::<Jpeg>();
76 /// assert!(concrete.is_err());
77 /// ```
78 fn from_generic(gmd: GenericMetadata) -> result::Result<Self::Metadata, GenericMetadata>;
79
80 /// Tries to extract a reference to a concrete metadata type from the given
81 /// `GenericMetadata` reference.
82 ///
83 /// Behaves similarly to `from_generic()`, except using references instead of immediate
84 /// values.
85 ///
86 /// # Examples
87 ///
88 /// ```no_run
89 /// use immeta::markers::Jpeg;
90 /// use immeta::formats::jpeg;
91 ///
92 /// let generic = immeta::load_from_file("kitty.jpg").unwrap();
93 /// let concrete: Option<&jpeg::Metadata> = generic.as_ref::<Jpeg>();
94 /// assert!(concrete.is_some());
95 /// ```
96 ///
97 /// ```no_run
98 /// use immeta::markers::Jpeg;
99 /// use immeta::formats::jpeg;
100 ///
101 /// let generic = immeta::load_from_file("kitty.png").unwrap();
102 /// let concrete: Option<&jpeg::Metadata> = generic.as_ref::<Jpeg>();
103 /// assert!(concrete.is_none());
104 /// ```
105 fn from_generic_ref(gmd: &GenericMetadata) -> Option<&Self::Metadata>;
106
107 /// Attempts to load metadata for an image of a concrete type from the provided reader.
108 ///
109 /// Invokes `LoadableMetadata::load()` for the associated metadata type. Use this
110 /// method instead of calling `load()` on the metadata type directly.
111 ///
112 /// # Examples
113 ///
114 /// ```no_run
115 /// use std::io::{self, BufReader};
116 /// use immeta::markers::{MetadataMarker, Jpeg};
117 ///
118 /// let data = io::stdin();
119 /// let metadata = Jpeg::load(&mut data.lock());
120 /// ```
121 fn load<R: ?Sized + BufRead>(r: &mut R) -> Result<Self::Metadata>;
122
123 /// Attempts to load metadata for an image of a concrete type from the provided
124 /// seekable reader.
125 ///
126 /// Invokes `LoadableMetadata::load_from_seek()` for the associated metadata type. Use
127 /// this method instead of calling `load_from_seek()` on the metadata type directly.
128 ///
129 /// # Examples
130 ///
131 /// ```no_run
132 /// use std::io::{Read, BufReader, Cursor};
133 /// use immeta::markers::{MetadataMarker, Jpeg};
134 ///
135 /// # fn obtain_image() -> Vec<u8> { unimplemented!() }
136 ///
137 /// let data: Vec<u8> = obtain_image();
138 /// let metadata = Jpeg::load(&mut BufReader::new(Cursor::new(data)));
139 /// ```
140 fn load_from_seek<R: ?Sized + BufRead + Seek>(r: &mut R) -> Result<Self::Metadata>;
141
142 /// Attempts to load metadata for an image of a concrete type from a file identified
143 /// by the provided path.
144 ///
145 /// Invokes `LoadableMetadata::load_from_file()` for the associated metadata type. Use this
146 /// method instead of calling `load_from_file()` on the metadata type directly.
147 ///
148 /// # Examples
149 ///
150 /// ```no_run
151 /// use immeta::markers::{MetadataMarker, Jpeg};
152 ///
153 /// let metadata = Jpeg::load_from_file("kitty.jpg");
154 /// ```
155 fn load_from_file<P: AsRef<Path>>(p: P) -> Result<Self::Metadata>;
156
157 /// Attempts to load metadata for an image of a concrete type from the provided byte
158 /// buffer.
159 ///
160 /// Invokes `LoadableMetadata::load_from_buf()` for the associated metadata type. Use this
161 /// method instead of calling `load_from_buf()` on the metadata type directly.
162 ///
163 /// # Examples
164 ///
165 /// ```no_run
166 /// use immeta::markers::{MetadataMarker, Jpeg};
167 ///
168 /// let buf: &[u8] = &[1, 2, 3, 4]; // pretend that this is an actual image
169 /// let metadata = Jpeg::load_from_buf(buf);
170 /// ```
171 fn load_from_buf(b: &[u8]) -> Result<Self::Metadata>;
172 }
173
174 macro_rules! impl_metadata_marker {
175 ($name:ident, $gvar:ident, $mtpe:ty) => {
176 pub enum $name {}
177
178 impl MetadataMarker for $name {
179 type Metadata = $mtpe;
180
181 #[inline]
182 fn from_generic(gmd: GenericMetadata) -> result::Result<$mtpe, GenericMetadata> {
183 match gmd {
184 $crate::generic::GenericMetadata::$gvar(md) => Ok(md),
185 gmd => Err(gmd)
186 }
187 }
188
189 #[inline]
190 fn from_generic_ref(gmd: &GenericMetadata) -> Option<&$mtpe> {
191 match *gmd {
192 $crate::generic::GenericMetadata::$gvar(ref md) => Some(md),
193 _ => None
194 }
195 }
196
197 #[inline]
198 fn load<R: ?Sized + BufRead>(r: &mut R) -> Result<$mtpe> {
199 $crate::traits::LoadableMetadata::load(r)
200 }
201
202 #[inline]
203 fn load_from_seek<R: ?Sized + BufRead + Seek>(r: &mut R) -> Result<$mtpe> {
204 $crate::traits::LoadableMetadata::load_from_seek(r)
205 }
206
207 #[inline]
208 fn load_from_file<P: AsRef<Path>>(p: P) -> Result<$mtpe> {
209 $crate::traits::LoadableMetadata::load_from_file(p)
210 }
211
212 #[inline]
213 fn load_from_buf(b: &[u8]) -> Result<$mtpe> {
214 $crate::traits::LoadableMetadata::load_from_buf(b)
215 }
216 }
217 }
218 }
219
220 impl_metadata_marker! { Jpeg, Jpeg, jpeg::Metadata }
221 impl_metadata_marker! { Png, Png, png::Metadata }
222 impl_metadata_marker! { Gif, Gif, gif::Metadata }
223 impl_metadata_marker! { Webp, Webp, webp::Metadata }
224}
225
226/// Represents metadata loaded from a file whose format was determined automatically.
227///
228/// Values of this type are obtained via `immeta::load()` function and its derivatives.
229#[derive(Debug, Clone, Eq, PartialEq)]
230pub enum GenericMetadata {
231 Png(png::Metadata),
232 Gif(gif::Metadata),
233 Jpeg(jpeg::Metadata),
234 Webp(webp::Metadata)
235}
236
237impl GenericMetadata {
238 /// Returns image dimensions from the contained metadata.
239 pub fn dimensions(&self) -> Dimensions {
240 match *self {
241 GenericMetadata::Png(ref md) => md.dimensions,
242 GenericMetadata::Gif(ref md) => md.dimensions,
243 GenericMetadata::Jpeg(ref md) => md.dimensions,
244 GenericMetadata::Webp(ref md) => md.dimensions()
245 }
246 }
247
248 /// Returns a MIME type string for the image type of the contained metadata.
249 pub fn mime_type(&self) -> &'static str {
250 match *self {
251 GenericMetadata::Png(_) => "image/png",
252 GenericMetadata::Gif(_) => "image/gif",
253 GenericMetadata::Jpeg(_) => "image/jpeg",
254 GenericMetadata::Webp(_) => "image/webp"
255 }
256 }
257
258 /// Attemts to convert this value to the specific metadata type by value.
259 ///
260 /// This method is needed only to provide a convenient syntax and it is not necessary
261 /// because one may just `match` on the `GenericMetadata` value.
262 #[inline]
263 pub fn into<T: MetadataMarker>(self) -> result::Result<T::Metadata, GenericMetadata> {
264 <T as MetadataMarker>::from_generic(self)
265 }
266
267 /// Attempts to convert this value to the sepcific metadata type by reference.
268 ///
269 /// This method is needed only to provide a convenient syntax and it is not necessary
270 /// because one may just `match` on the `GenericMetadata` value.
271 #[inline]
272 pub fn as_ref<T: MetadataMarker>(&self) -> Option<&T::Metadata> {
273 <T as MetadataMarker>::from_generic_ref(self)
274 }
275}
276
277/// Attempts to load metadata for an image contained in the provided input stream.
278///
279/// This method automatically determines the format of the contained image. Because it may
280/// need to read the stream from the beginning several times, a `Seek` bound is necessary
281/// on the input stream. This may cause problems only with network streams as they are
282/// naturally not seekable, so one would need to buffer the data from them first.
283pub fn load<R: ?Sized + BufRead + Seek>(r: &mut R) -> Result<GenericMetadata> {
284 // try png
285 try!(r.seek(SeekFrom::Start(0)));
286 if let Ok(md) = png::Metadata::load_from_seek(r) {
287 return Ok(GenericMetadata::Png(md));
288 }
289
290 // try gif
291 try!(r.seek(SeekFrom::Start(0)));
292 if let Ok(md) = gif::Metadata::load_from_seek(r) {
293 return Ok(GenericMetadata::Gif(md));
294 }
295
296 // try webp
297 try!(r.seek(SeekFrom::Start(0)));
298 if let Ok(md) = webp::Metadata::load_from_seek(r) {
299 return Ok(GenericMetadata::Webp(md));
300 }
301
302 // try jpeg
303 try!(r.seek(SeekFrom::Start(0)));
304 if let Ok(md) = jpeg::Metadata::load_from_seek(r) {
305 return Ok(GenericMetadata::Jpeg(md));
306 }
307
308 Err(invalid_format!("unknown or unsupported image type"))
309}
310
311/// Attempts to load metadata for an image contained in a file identified by the provided path.
312///
313/// This method delegates to `load()` method and, consequently, also determines the image format
314/// automatically.
315pub fn load_from_file<P: AsRef<Path>>(p: P) -> Result<GenericMetadata> {
316 let mut f = BufReader::new(try!(File::open(p)));
317 load(&mut f)
318}
319
320/// Attempts to load metadata for an image contained in an in-memory buffer.
321///
322/// This method delegates to `load()` method and, consequently, also determines the image format
323/// automatically.
324pub fn load_from_buf(b: &[u8]) -> Result<GenericMetadata> {
325 load(&mut Cursor::new(b))
326}