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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
// (c) Copyright 2019-2020 OLX
use crate::bindings;
use crate::error::Error;
use crate::ops::*;
use crate::utils;
use crate::Result;

use num_traits::{FromPrimitive, ToPrimitive};
use std::borrow::Cow;
use std::convert::TryInto;
use std::ffi::*;
use std::ptr::null_mut;

const NULL: *const c_void = null_mut();

#[derive(Debug, Clone)]
pub struct VipsImage {
    pub(crate) ctx: *mut bindings::VipsImage,
}

#[derive(Debug, Clone)]
pub struct VipsInterpolate {
    pub(crate) ctx: *mut bindings::VipsInterpolate,
}

#[derive(Debug, Clone)]
pub struct VipsBlob {
    pub(crate) ctx: *mut bindings::VipsBlob,
}

#[derive(Debug, Clone)]
pub struct VipsConnection {
    pub(crate) ctx: *mut bindings::VipsConnection,
}

#[derive(Debug, Clone)]
pub struct VipsSource {
    pub(crate) ctx: *mut bindings::VipsSource,
}

#[derive(Debug, Clone)]
pub struct VipsTarget {
    pub(crate) ctx: *mut bindings::VipsTarget,
}

/// This is the main type of vips. It represents an image and most operations will take one as input and output a new one.
/// In the moment this type is not thread safe. Be careful working within thread environments.
impl VipsImage {
    pub fn new() -> VipsImage {
        VipsImage {
            ctx: unsafe { bindings::vips_image_new() },
        }
    }

    pub fn new_memory() -> Result<VipsImage> {
        unsafe {
            let res = bindings::vips_image_new_memory();
            vips_image_result(res, Error::InitializationError("Could not generate object"))
        }
    }

    pub fn new_from_file(filename: &str) -> Result<VipsImage> {
        unsafe {
            let f = utils::new_c_string(filename)?;
            let res = bindings::vips_image_new_from_file(f.as_ptr(), NULL);
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from file"),
            )
        }
    }

    pub fn new_from_file_rw(filename: &str) -> Result<VipsImage> {
        unsafe {
            let f = utils::new_c_string(filename)?;
            let res = bindings::vips_image_new_from_file_RW(f.as_ptr());
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from file"),
            )
        }
    }

    pub fn new_from_file_raw(
        filename: &str,
        x_size: i32,
        y_size: i32,
        bands: i32,
        offset: u64,
    ) -> Result<VipsImage> {
        unsafe {
            let f = utils::new_c_string(filename)?;
            let res =
                bindings::vips_image_new_from_file_raw(f.as_ptr(), x_size, y_size, bands, offset);
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from file"),
            )
        }
    }

    pub fn new_from_file_access(filename: &str, access: Access, memory: bool) -> Result<VipsImage> {
        unsafe {
            let access_str = utils::new_c_string("access")?;
            let memory_str = utils::new_c_string("memory")?;
            let f = utils::new_c_string(filename)?;
            let res = bindings::vips_image_new_from_file(
                f.as_ptr(),
                access_str.as_ptr(),
                access as i32,
                memory_str.as_ptr(),
                if memory { 1 } else { 0 },
                NULL,
            );
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from file"),
            )
        }
    }

    pub fn new_from_buffer(buffer: &[u8], option_str: &str) -> Result<VipsImage> {
        unsafe {
            let options = utils::new_c_string(option_str)?;
            let res = bindings::vips_image_new_from_buffer(
                buffer.as_ptr() as *const c_void,
                buffer.len() as u64,
                options.as_ptr(),
                NULL,
            );
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from file"),
            )
        }
    }

    pub fn new_from_memory(
        buffer: &[u8],
        width: i32,
        height: i32,
        bands: i32,
        format: BandFormat,
    ) -> Result<VipsImage> {
        unsafe {
            if let Some(format) = format.to_i32() {
                let res = bindings::vips_image_new_from_memory(
                    buffer.as_ptr() as *const c_void,
                    buffer.len() as u64,
                    width,
                    height,
                    bands,
                    format,
                );
                vips_image_result(
                    res,
                    Error::InitializationError("Could not initialise VipsImage from memory"),
                )
            } else {
                Err(Error::InitializationError(
                    "Invalid BandFormat. Please file a bug report, as this should never happen.",
                ))
            }
        }
    }

    pub fn image_new_matrix(width: i32, height: i32) -> Result<VipsImage> {
        unsafe {
            let res = bindings::vips_image_new_matrix(width, height);
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from file"),
            )
        }
    }

    pub fn image_new_matrix_from_array(
        width: i32,
        height: i32,
        array: &[f64],
    ) -> Result<VipsImage> {
        unsafe {
            let res = bindings::vips_image_new_matrix_from_array(
                width,
                height,
                array.as_ptr(),
                array.len() as i32,
            );
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from file"),
            )
        }
    }

    pub fn new_from_image(image: &VipsImage, array: &[f64]) -> Result<VipsImage> {
        unsafe {
            let res =
                bindings::vips_image_new_from_image(image.ctx, array.as_ptr(), array.len() as i32);
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from Object"),
            )
        }
    }

    pub fn new_from_image1(image: &VipsImage, c: f64) -> Result<VipsImage> {
        unsafe {
            let res = bindings::vips_image_new_from_image1(image.ctx, c);
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from Object"),
            )
        }
    }

    pub fn image_new_temp_file(format: &str) -> Result<VipsImage> {
        unsafe {
            let format_c_str = utils::new_c_string(format)?;
            let res = bindings::vips_image_new_temp_file(format_c_str.as_ptr());
            vips_image_result(
                res,
                Error::InitializationError("Could not initialise VipsImage from format"),
            )
        }
    }

    pub fn image_copy_memory(image: VipsImage) -> Result<VipsImage> {
        unsafe {
            let result = bindings::vips_image_copy_memory(image.ctx);
            vips_image_result(result, Error::OperationError("Could not copy memory"))
        }
    }

    pub fn image_wio_input(&mut self) -> Result<()> {
        unsafe {
            let result = bindings::vips_image_wio_input(self.ctx);
            utils::result(
                result,
                (),
                Error::OperationError("Error on vips image_wio_input"),
            )
        }
    }

    pub fn get_filename(&self) -> std::result::Result<&str, std::str::Utf8Error> {
        unsafe {
            let filename = bindings::vips_image_get_filename(self.ctx);
            let res = CStr::from_ptr(filename);
            res.to_str()
        }
    }

    pub fn get_width(&self) -> i32 {
        unsafe { bindings::vips_image_get_width(self.ctx) }
    }

    pub fn get_height(&self) -> i32 {
        unsafe { bindings::vips_image_get_height(self.ctx) }
    }

    pub fn get_xoffset(&self) -> i32 {
        unsafe { bindings::vips_image_get_xoffset(self.ctx) }
    }

    pub fn get_yoffset(&self) -> i32 {
        unsafe { bindings::vips_image_get_yoffset(self.ctx) }
    }

    pub fn get_scale(&self) -> f64 {
        unsafe { bindings::vips_image_get_scale(self.ctx) }
    }

    pub fn get_offset(&self) -> f64 {
        unsafe { bindings::vips_image_get_offset(self.ctx) }
    }

    pub fn get_xres(&self) -> f64 {
        unsafe { bindings::vips_image_get_xres(self.ctx) }
    }

    pub fn get_yres(&self) -> f64 {
        unsafe { bindings::vips_image_get_yres(self.ctx) }
    }

    pub fn get_bands(&self) -> i32 {
        unsafe { bindings::vips_image_get_bands(self.ctx) }
    }

    pub fn get_page_height(&self) -> i32 {
        unsafe { bindings::vips_image_get_page_height(self.ctx) }
    }

    pub fn get_n_pages(&self) -> i32 {
        unsafe { bindings::vips_image_get_n_pages(self.ctx) }
    }

    pub fn get_coding(&self) -> Result<Coding> {
        unsafe {
            let res = bindings::vips_image_get_format(self.ctx);
            let format_enum = FromPrimitive::from_i32(res);
            format_enum.ok_or_else(|| Error::IOError("Could get format from image"))
        }
    }

    pub fn get_format(&self) -> Result<BandFormat> {
        unsafe {
            let res = bindings::vips_image_get_format(self.ctx);
            let format_enum = FromPrimitive::from_i32(res);
            format_enum.ok_or_else(|| Error::IOError("Could get format from image"))
        }
    }

    pub fn guess_format(&self) -> Result<BandFormat> {
        unsafe {
            let res = bindings::vips_image_guess_format(self.ctx);
            let format_enum = FromPrimitive::from_i32(res);
            format_enum.ok_or_else(|| Error::IOError("Could get format from image"))
        }
    }

    pub fn get_interpretation(&self) -> Result<Interpretation> {
        unsafe {
            let res = bindings::vips_image_get_interpretation(self.ctx);
            let format_enum = FromPrimitive::from_i32(res);
            format_enum.ok_or_else(|| Error::IOError("Could get format from image"))
        }
    }

    pub fn guess_interpretation(&self) -> Result<Interpretation> {
        unsafe {
            let res = bindings::vips_image_guess_interpretation(self.ctx);
            let format_enum = FromPrimitive::from_i32(res);
            format_enum.ok_or_else(|| Error::IOError("Could get format from image"))
        }
    }

    pub fn image_set_delete_on_close(&mut self, flag: bool) {
        unsafe {
            bindings::vips_image_set_delete_on_close(self.ctx, if flag { 1 } else { 0 });
        }
    }

    pub fn image_invalidate_all(&self) {
        unsafe {
            bindings::vips_image_invalidate_all(self.ctx);
        }
    }

    pub fn image_minimise_all(&self) {
        unsafe {
            bindings::vips_image_minimise_all(self.ctx);
        }
    }

    pub fn image_iskilled(&self) -> bool {
        unsafe { bindings::vips_image_iskilled(self.ctx) == 1 }
    }

    pub fn image_isMSBfirst(&self) -> bool {
        unsafe { bindings::vips_image_isMSBfirst(self.ctx) == 1 }
    }

    pub fn image_isfile(&self) -> bool {
        unsafe { bindings::vips_image_isfile(self.ctx) == 1 }
    }

    pub fn image_ispartial(&self) -> bool {
        unsafe { bindings::vips_image_ispartial(self.ctx) == 1 }
    }

    pub fn image_hasalpha(&self) -> bool {
        unsafe { bindings::vips_image_hasalpha(self.ctx) == 1 }
    }

    pub fn image_set_kill(&self, flag: bool) {
        unsafe {
            bindings::vips_image_set_kill(self.ctx, if flag { 1 } else { 0 });
        }
    }

    pub fn image_set_progress(&self, flag: bool) {
        unsafe {
            bindings::vips_image_set_progress(self.ctx, if flag { 1 } else { 0 });
        }
    }

    pub fn image_write(&self) -> Result<VipsImage> {
        unsafe {
            let out: *mut bindings::VipsImage = null_mut();
            let res = bindings::vips_image_write(self.ctx, out);
            utils::result(
                res,
                VipsImage { ctx: out },
                Error::IOError("Cannot write input to output"),
            )
        }
    }

    pub fn image_pio_input(&mut self) -> Result<()> {
        unsafe {
            let res = bindings::vips_image_pio_input(self.ctx);
            utils::result(res, (), Error::IOError("Cannot read image"))
        }
    }

    pub fn image_pio_output(&mut self) -> Result<()> {
        unsafe {
            let res = bindings::vips_image_pio_output(self.ctx);
            utils::result(res, (), Error::IOError("Cannot write image"))
        }
    }

    pub fn image_inplace(&self) -> Result<()> {
        unsafe {
            let res = bindings::vips_image_inplace(self.ctx);
            utils::result(res, (), Error::IOError("Cannot cannot be modified inplace"))
        }
    }

    pub fn image_write_to_file(&self, filename: &str) -> Result<()> {
        unsafe {
            let file_c_str = utils::new_c_string(filename)?;
            let res = bindings::vips_image_write_to_file(self.ctx, file_c_str.as_ptr(), NULL);
            utils::result(res, (), Error::IOError("Cannot write to file"))
        }
    }

    pub fn image_write_prepare(&self) -> Result<()> {
        unsafe {
            let res = bindings::vips_image_write_prepare(self.ctx);
            utils::result(res, (), Error::IOError("Cannot prepare file to write"))
        }
    }

    pub fn image_write_to_buffer(&self, suffix: &str) -> Result<Vec<u8>> {
        unsafe {
            let mut buffer_buf_size: u64 = 0;
            let mut buffer_out: *mut c_void = null_mut();
            let suffix_c_str = utils::new_c_string(suffix)?;
            let res = bindings::vips_image_write_to_buffer(
                self.ctx,
                suffix_c_str.as_ptr(),
                &mut buffer_out,
                &mut buffer_buf_size,
                NULL,
            );
            utils::result(
                res,
                utils::new_byte_array(buffer_out, buffer_buf_size),
                Error::IOError("Cannot write content to buffer"),
            )
        }
    }

    pub fn image_write_to_memory(&self) -> Vec<u8> {
        unsafe {
            let mut buffer_buf_size: u64 = 0;
            let buffer_out = bindings::vips_image_write_to_memory(self.ctx, &mut buffer_buf_size);
            let buf = std::slice::from_raw_parts(buffer_out as *mut u8, buffer_buf_size as usize).to_vec();
            bindings::g_free(buffer_out);
            buf
        }
    }

    pub fn image_decode_predict(&self) -> Result<(i32, BandFormat)> {
        unsafe {
            let mut out_bands = 0;
            let mut out_format = 0;
            let res =
                bindings::vips_image_decode_predict(self.ctx, &mut out_bands, &mut out_format);
            let format_enum = FromPrimitive::from_i32(out_format);
            if format_enum.is_some() {
                utils::result(
                    res,
                    (out_bands, format_enum.unwrap()),
                    Error::IOError("Could not predict image format"),
                )
            } else {
                Err(Error::IOError("Could not predict image format"))
            }
        }
    }

    pub fn image_decode(&self) -> Result<VipsImage> {
        unsafe {
            let mut out: *mut bindings::VipsImage = null_mut();
            let res = bindings::vips_image_decode(self.ctx, &mut out);
            utils::result(
                res,
                VipsImage { ctx: out },
                Error::IOError("Cannot decode image"),
            )
        }
    }

    pub fn image_encode(&self, coding: Coding) -> Result<VipsImage> {
        unsafe {
            let mut out: *mut bindings::VipsImage = null_mut();
            let res = bindings::vips_image_encode(self.ctx, &mut out, coding as i32);
            utils::result(
                res,
                VipsImage { ctx: out },
                Error::IOError("Cannot encode image"),
            )
        }
    }
}

impl VipsConnection {
    pub fn connection_filename(&self) -> Option<String> {
        unsafe {
            let result = bindings::vips_connection_filename(self.ctx);
            if result.is_null() {
                None
            } else {
                let cstr = CStr::from_ptr(result);
                match cstr.to_string_lossy() {
                    Cow::Borrowed(slice) => Some(slice.to_string()),
                    Cow::Owned(string) => Some(string),
                }
            }
        }
    }

    pub fn connection_nick(&self) -> Option<String> {
        unsafe {
            let result = bindings::vips_connection_nick(self.ctx);
            if result.is_null() {
                None
            } else {
                let cstr = CStr::from_ptr(result);
                match cstr.to_string_lossy() {
                    Cow::Borrowed(slice) => Some(slice.to_string()),
                    Cow::Owned(string) => Some(string),
                }
            }
        }
    }
}

impl VipsSource {
    pub fn new_from_descriptor(descriptor: i32) -> Result<Self> {
        unsafe {
            let res = bindings::vips_source_new_from_descriptor(descriptor);
            vips_source_result(
                res,
                Error::InitializationError("Could not initialise VipsSource from descriptor"),
            )
        }
    }

    pub fn new_from_file(filename: &str) -> Result<Self> {
        unsafe {
            let f = utils::new_c_string(filename)?;
            let res = bindings::vips_source_new_from_file(f.as_ptr());
            vips_source_result(
                res,
                Error::InitializationError("Could not initialise VipsSource from file"),
            )
        }
    }

    // not sure if it this is safe
    // should test before making it public
    fn new_from_blob(blob: VipsBlob) -> Result<Self> {
        unsafe {
            let res = bindings::vips_source_new_from_blob(blob.ctx);
            vips_source_result(
                res,
                Error::InitializationError("Could not initialise VipsSource from blob"),
            )
        }
    }

    pub fn new_from_memory(buffer: &[u8]) -> Result<Self> {
        unsafe {
            let res = bindings::vips_source_new_from_memory(
                buffer.as_ptr() as *const c_void,
                buffer.len() as u64,
            );
            vips_source_result(
                res,
                Error::InitializationError("Could not initialise VipsSource from memory"),
            )
        }
    }

    pub fn new_from_options(option_str: &str) -> Result<Self> {
        unsafe {
            let options = utils::new_c_string(option_str)?;
            let res = bindings::vips_source_new_from_options(options.as_ptr());
            vips_source_result(
                res,
                Error::InitializationError("Could not initialise VipsSource from options"),
            )
        }
    }

    pub fn minimise(&mut self) {
        unsafe {
            bindings::vips_source_minimise(self.ctx);
        }
    }

    pub fn unminimise(&mut self) -> Result<()> {
        unsafe {
            let result = bindings::vips_source_unminimise(self.ctx);
            utils::result(
                result,
                (),
                Error::OperationError("Error on vips unminimise"),
            )
        }
    }

    pub fn decode(&mut self) -> Result<()> {
        unsafe {
            let result = bindings::vips_source_decode(self.ctx);
            utils::result(
                result,
                (),
                Error::OperationError("Error on vips decode"),
            )
        }
    }

    pub fn read(&mut self, length: u64) -> Result<Vec<u8>> {
        unsafe {
            let bytes: *mut c_void = null_mut();
            let result = bindings::vips_source_read(self.ctx, bytes, length);
            if result != -1 {
                let buffer =
                    Vec::from_raw_parts(bytes as *mut u8, result as usize, result as usize);
                Ok(buffer)
            } else {
                Err(Error::OperationError("Error on vips read"))
            }
        }
    }

    pub fn is_mappable(&self) -> bool {
        unsafe { bindings::vips_source_is_mappable(self.ctx) == 1 }
    }

    pub fn seek(&mut self, offset: i64, whence: i32) -> Result<i64> {
        unsafe {
            let result = bindings::vips_source_seek(self.ctx, offset, whence);
            if result == -1 {
                Err(Error::OperationError("Error on vips seek"))
            } else {
                Ok(result)
            }
        }
    }

    pub fn rewind(&mut self) -> Result<()> {
        unsafe {
            let result = bindings::vips_source_rewind(self.ctx);
            if result == -1 {
                Err(Error::OperationError("Error on vips rewind"))
            } else {
                Ok(())
            }
        }
    }

    pub fn length(&self) -> Result<i64> {
        unsafe {
            let result = bindings::vips_source_length(self.ctx);
            if result == -1 {
                Err(Error::OperationError("Error on vips length"))
            } else {
                Ok(result)
            }
        }
    }
}

impl<'a> VipsSource {
    pub fn map(&'a self) -> Result<&'a [u8]> {
        unsafe {
            let length: *mut u64 = null_mut();
            let result = bindings::vips_source_map(self.ctx, length);
            if length.is_null() {
                Err(Error::OperationError("Error on vips map"))
            } else {
                let size = (*length)
                    .try_into()
                    .map_err(|_| Error::OperationError("Can't get size of array"))?;
                Ok(std::slice::from_raw_parts(result as *mut u8, size))
            }
        }
    }

    // pub fn map_blob(&'a self) -> Result<&'a VipsBlob> {
    //     unsafe {
    //         let result = bindings::vips_source_map_blob(self.ctx);
    //         if result.is_null() {
    //             Err(Error::OperationError("Error on vips map blob"))
    //         } else {
    //             Ok(&VipsBlob { ctx: result })
    //         }
    //     }
    // }
}

impl VipsTarget {
    pub fn new_to_descriptor(descriptor: i32) -> Result<Self> {
        unsafe {
            let res = bindings::vips_target_new_to_descriptor(descriptor);
            vips_target_result(
                res,
                Error::InitializationError("Could not initialise VipsTarget from descriptor"),
            )
        }
    }

    pub fn new_to_file(filename: &str) -> Result<Self> {
        unsafe {
            let f = utils::new_c_string(filename)?;
            let res = bindings::vips_target_new_to_file(f.as_ptr());
            vips_target_result(
                res,
                Error::InitializationError("Could not initialise VipsTarget from file"),
            )
        }
    }

    pub fn new_to_memory() -> Result<Self> {
        unsafe {
            let res = bindings::vips_target_new_to_memory();
            vips_target_result(
                res,
                Error::InitializationError("Could not initialise VipsTarget from memory"),
            )
        }
    }

    pub fn write(&mut self, buffer: &[u8]) -> Result<()> {
        unsafe {
            let res = bindings::vips_target_write(
                self.ctx,
                buffer.as_ptr() as *const c_void,
                buffer.len() as u64,
            );
            if res == -1 {
                Err(Error::OperationError("Could not write to buffer"))
            } else {
                Ok(())
            }
        }
    }

    pub fn finish(self) {
        unsafe {
            bindings::vips_target_finish(self.ctx);
        }
    }

    pub fn putc(&mut self, ch: char) -> Result<()> {
        unsafe {
            let res = bindings::vips_target_putc(self.ctx, ch as i32);
            if res == -1 {
                Err(Error::OperationError("Could not write to buffer"))
            } else {
                Ok(())
            }
        }
    }

    pub fn writes(&mut self, text: &str) -> Result<()> {
        unsafe {
            let cstr = CString::new(text).map_err(|_| Error::OperationError("Cannot initialize C string"))?;
            let res = bindings::vips_target_writes(self.ctx, cstr.as_ptr());
            if res == -1 {
                Err(Error::OperationError("Could not write to buffer"))
            } else {
                Ok(())
            }
        }
    }

    pub fn write_amp(&mut self, text: &str) -> Result<()> {
        unsafe {
            let cstr = CString::new(text).map_err(|_| Error::OperationError("Cannot initialize C string"))?;
            let res = bindings::vips_target_write_amp(self.ctx, cstr.as_ptr());
            if res == -1 {
                Err(Error::OperationError("Could not write to buffer"))
            } else {
                Ok(())
            }
        }
    }
}

unsafe fn vips_image_result(res: *mut bindings::VipsImage, err: Error) -> Result<VipsImage> {
    if res.is_null() {
        Err(err)
    } else {
        Ok(VipsImage { ctx: res })
    }
}

unsafe fn vips_source_result(res: *mut bindings::VipsSource, err: Error) -> Result<VipsSource> {
    if res.is_null() {
        Err(err)
    } else {
        Ok(VipsSource { ctx: res })
    }
}

unsafe fn vips_target_result(res: *mut bindings::VipsTarget, err: Error) -> Result<VipsTarget> {
    if res.is_null() {
        Err(err)
    } else {
        Ok(VipsTarget { ctx: res })
    }
}

impl VipsInterpolate {
    /// defaults to vips_interpolate_nearest_static
    pub fn new() -> VipsInterpolate {
        unsafe {
            VipsInterpolate {
                ctx: bindings::vips_interpolate_nearest_static(),
            }
        }
    }

    pub fn new_from_neasest_static() -> VipsInterpolate {
        unsafe {
            VipsInterpolate {
                ctx: bindings::vips_interpolate_nearest_static(),
            }
        }
    }

    pub fn new_from_bilinear_static() -> VipsInterpolate {
        unsafe {
            VipsInterpolate {
                ctx: bindings::vips_interpolate_bilinear_static(),
            }
        }
    }

    pub fn new_from_name(name: &str) -> Result<VipsInterpolate> {
        unsafe {
            let nickname = utils::new_c_string(name)?;
            let res = bindings::vips_interpolate_new(nickname.as_ptr());
            if res.is_null() {
                Err(Error::InitializationError(
                    "Cannot initialize interpolator with provided nickname",
                ))
            } else {
                Ok(VipsInterpolate { ctx: res })
            }
        }
    }

    pub fn get_window_size(&self) -> i32 {
        unsafe { bindings::vips_interpolate_get_window_size(self.ctx) }
    }

    pub fn get_windows_offset(&self) -> i32 {
        unsafe { bindings::vips_interpolate_get_window_offset(self.ctx) }
    }
}

impl Drop for VipsImage {
    fn drop(&mut self) {
        unsafe {
            if !self.ctx.is_null() {
                bindings::g_object_unref(self.ctx as *mut c_void);
            }
        }
    }
}

impl Drop for VipsInterpolate {
    fn drop(&mut self) {
        unsafe {
            if !self.ctx.is_null() {
                bindings::g_object_unref(self.ctx as *mut c_void);
            }
        }
    }
}

impl Drop for VipsBlob {
    fn drop(&mut self) {
        unsafe {
            if !self.ctx.is_null() {
                bindings::g_object_unref(self.ctx as *mut c_void);
            }
        }
    }
}

impl Drop for VipsConnection {
    fn drop(&mut self) {
        unsafe {
            if !self.ctx.is_null() {
                bindings::g_object_unref(self.ctx as *mut c_void);
            }
        }
    }
}

impl Drop for VipsSource {
    fn drop(&mut self) {
        unsafe {
            if !self.ctx.is_null() {
                bindings::g_object_unref(self.ctx as *mut c_void);
            }
        }
    }
}

impl Drop for VipsTarget {
    fn drop(&mut self) {
        unsafe {
            if !self.ctx.is_null() {
                bindings::g_object_unref(self.ctx as *mut c_void);
            }
        }
    }
}

impl Into<Vec<u8>> for VipsBlob {
    fn into(self) -> Vec<u8> {
        unsafe {
            let mut size: u64 = 0;
            let bytes = bindings::vips_blob_get(self.ctx, &mut size);
            Vec::from_raw_parts(bytes as *mut u8, size as usize, size as usize)
        }
    }
}