cacache/
get.rs

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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! Functions for reading from cache.
use std::path::Path;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::pin::Pin;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::task::{Context as TaskContext, Poll};

use ssri::{Algorithm, Integrity};

#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::AsyncRead;
use crate::content::read;
use crate::errors::{Error, Result};
use crate::index::{self, Metadata};

// ---------
// Async API
// ---------

/// File handle for reading data asynchronously.
///
/// Make sure to call `.check()` when done reading to verify that the
/// extracted data passes integrity verification.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub struct Reader {
    reader: read::AsyncReader,
}

#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncRead for Reader {
    #[cfg(feature = "async-std")]
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut TaskContext<'_>,
        buf: &mut [u8],
    ) -> Poll<std::io::Result<usize>> {
        Pin::new(&mut self.reader).poll_read(cx, buf)
    }

    #[cfg(feature = "tokio")]
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut TaskContext<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<tokio::io::Result<()>> {
        Pin::new(&mut self.reader).poll_read(cx, buf)
    }
}

#[cfg(any(feature = "async-std", feature = "tokio"))]
impl Reader {
    /// Checks that data read from disk passes integrity checks. Returns the
    /// algorithm that was used verified the data. Should be called only after
    /// all data has been read from disk.
    ///
    /// This check is very cheap, since most of the verification is done on
    /// the fly. This simply finalizes verification, and is always
    /// synchronous.
    ///
    /// ## Example
    /// ```no_run
    /// use async_std::prelude::*;
    /// use async_attributes;
    ///
    /// #[async_attributes::main]
    /// async fn main() -> cacache::Result<()> {
    ///     let mut fd = cacache::Reader::open("./my-cache", "my-key").await?;
    ///     let mut str = String::new();
    ///     fd.read_to_string(&mut str).await.expect("Failed to read to string");
    ///     // Remember to check that the data you got was correct!
    ///     fd.check()?;
    ///     Ok(())
    /// }
    /// ```
    pub fn check(self) -> Result<Algorithm> {
        self.reader.check()
    }

    /// Opens a new file handle into the cache, looking it up in the index using
    /// `key`.
    ///
    /// ## Example
    /// ```no_run
    /// use async_std::prelude::*;
    /// use async_attributes;
    ///
    /// #[async_attributes::main]
    /// async fn main() -> cacache::Result<()> {
    ///     let mut fd = cacache::Reader::open("./my-cache", "my-key").await?;
    ///     let mut str = String::new();
    ///     fd.read_to_string(&mut str).await.expect("Failed to read to string");
    ///     // Remember to check that the data you got was correct!
    ///     fd.check()?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn open<P, K>(cache: P, key: K) -> Result<Reader>
    where
        P: AsRef<Path>,
        K: AsRef<str>,
    {
        async fn inner(cache: &Path, key: &str) -> Result<Reader> {
            if let Some(entry) = index::find_async(cache, key).await? {
                Reader::open_hash(cache, entry.integrity).await
            } else {
                Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
            }
        }
        inner(cache.as_ref(), key.as_ref()).await
    }

    /// Opens a new file handle into the cache, based on its integrity address.
    ///
    /// ## Example
    /// ```no_run
    /// use async_std::prelude::*;
    /// use async_attributes;
    ///
    /// #[async_attributes::main]
    /// async fn main() -> cacache::Result<()> {
    ///     let sri = cacache::write("./my-cache", "key", b"hello world").await?;
    ///     let mut fd = cacache::Reader::open_hash("./my-cache", sri).await?;
    ///     let mut str = String::new();
    ///     fd.read_to_string(&mut str).await.expect("Failed to read to string");
    ///     // Remember to check that the data you got was correct!
    ///     fd.check()?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn open_hash<P>(cache: P, sri: Integrity) -> Result<Reader>
    where
        P: AsRef<Path>,
    {
        Ok(Reader {
            reader: read::open_async(cache.as_ref(), sri).await?,
        })
    }
}

/// Reads the entire contents of a cache file into a bytes vector, looking the
/// data up by key.
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     let data: Vec<u8> = cacache::read("./my-cache", "my-key").await?;
///     Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn read<P, K>(cache: P, key: K) -> Result<Vec<u8>>
where
    P: AsRef<Path>,
    K: AsRef<str>,
{
    async fn inner(cache: &Path, key: &str) -> Result<Vec<u8>> {
        if let Some(entry) = index::find_async(cache, key).await? {
            read_hash(cache, &entry.integrity).await
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref()).await
}

/// Reads the entire contents of a cache file into a bytes vector, looking the
/// data up by its content address.
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     let sri = cacache::write("./my-cache", "my-key", b"hello").await?;
///     let data: Vec<u8> = cacache::read_hash("./my-cache", &sri).await?;
///     Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn read_hash<P>(cache: P, sri: &Integrity) -> Result<Vec<u8>>
where
    P: AsRef<Path>,
{
    read::read_async(cache.as_ref(), sri).await
}

/// Copies cache data to a specified location. Returns the number of bytes
/// copied.
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     cacache::copy("./my-cache", "my-key", "./data.txt").await?;
///     Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy<P, K, Q>(cache: P, key: K, to: Q) -> Result<u64>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    async fn inner(cache: &Path, key: &str, to: &Path) -> Result<u64> {
        if let Some(entry) = index::find_async(cache, key).await? {
            copy_hash(cache, &entry.integrity, to).await
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref()).await
}

/// Copies cache data to a specified location. Cache data will not be checked
/// during copy.
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     cacache::copy_unchecked("./my-cache", "my-key", "./data.txt").await?;
///     Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy_unchecked<P, K, Q>(cache: P, key: K, to: Q) -> Result<u64>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    async fn inner(cache: &Path, key: &str, to: &Path) -> Result<u64> {
        if let Some(entry) = index::find_async(cache, key).await? {
            copy_hash_unchecked(cache, &entry.integrity, to).await
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref()).await
}

/// Copies a cache data by hash to a specified location. Returns the number of
/// bytes copied.
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     let sri = cacache::write("./my-cache", "my-key", b"hello world").await?;
///     cacache::copy_hash("./my-cache", &sri, "./data.txt").await?;
///     Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy_hash<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<u64>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::copy_async(cache.as_ref(), sri, to.as_ref()).await
}

/// Copies a cache data by hash to a specified location. Copied data will not
/// be checked against the given hash.
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     let sri = cacache::write("./my-cache", "my-key", b"hello world").await?;
///     cacache::copy_hash_unchecked("./my-cache", &sri, "./data.txt").await?;
///     Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy_hash_unchecked<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<u64>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::copy_unchecked_async(cache.as_ref(), sri, to.as_ref()).await
}

/// Creates a reflink/clonefile from a cache entry to a destination path.
///
/// Fails if the destination is on a different filesystem or if the filesystem
/// does not support reflinks.
///
/// Currently, reflinks are known to work on APFS (macOS), XFS, btrfs, and
/// ReFS (Windows DevDrive)
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     cacache::reflink("./my-cache", "my-key", "./data.txt").await?;
///     Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn reflink<P, K, Q>(cache: P, key: K, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    async fn inner(cache: &Path, key: &str, to: &Path) -> Result<()> {
        if let Some(entry) = index::find_async(cache, key).await? {
            reflink_hash(cache, &entry.integrity, to).await
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref()).await
}

/// Reflinks/clonefiles cache data to a specified location. Cache data will
/// not be checked during linking.
///
/// Fails if the destination is on a different filesystem or if the filesystem
/// does not support reflinks.
///
/// Currently, reflinks are known to work on APFS (macOS), XFS, btrfs, and
/// ReFS (Windows DevDrive)
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     cacache::reflink_unchecked("./my-cache", "my-key", "./data.txt").await?;
///     Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn reflink_unchecked<P, K, Q>(cache: P, key: K, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    async fn inner(cache: &Path, key: &str, to: &Path) -> Result<()> {
        if let Some(entry) = index::find_async(cache, key).await? {
            reflink_hash_unchecked_sync(cache, &entry.integrity, to)
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref()).await
}

/// Reflinks/clonefiles cache data by hash to a specified location.
///
/// Fails if the destination is on a different filesystem or if the filesystem
/// does not support reflinks.
///
/// Currently, reflinks are known to work on APFS (macOS), XFS, btrfs, and
/// ReFS (Windows DevDrive)
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     let sri = cacache::write("./my-cache", "my-key", b"hello world").await?;
///     cacache::reflink_hash("./my-cache", &sri, "./data.txt").await?;
///     Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn reflink_hash<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::reflink_async(cache.as_ref(), sri, to.as_ref()).await
}

/// Hard links a cache entry by hash to a specified location.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn hard_link_hash<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::hard_link_async(cache.as_ref(), sri, to.as_ref()).await
}

/// Hard links a cache entry by key to a specified location.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn hard_link<P, K, Q>(cache: P, key: K, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    async fn inner(cache: &Path, key: &str, to: &Path) -> Result<()> {
        if let Some(entry) = index::find(cache, key)? {
            hard_link_hash(cache, &entry.integrity, to).await
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref()).await
}

/// Gets the metadata entry for a certain key.
///
/// Note that the existence of a metadata entry is not a guarantee that the
/// underlying data exists, since they are stored and managed independently.
/// To verify that the underlying associated data exists, use `exists()`.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn metadata<P, K>(cache: P, key: K) -> Result<Option<Metadata>>
where
    P: AsRef<Path>,
    K: AsRef<str>,
{
    index::find_async(cache.as_ref(), key.as_ref()).await
}

/// Returns true if the given hash exists in the cache.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn exists<P: AsRef<Path>>(cache: P, sri: &Integrity) -> bool {
    read::has_content_async(cache.as_ref(), sri).await.is_some()
}

// ---------------
// Synchronous API
// ---------------

/// File handle for reading data synchronously.
///
/// Make sure to call `get.check()` when done reading
/// to verify that the extracted data passes integrity
/// verification.
pub struct SyncReader {
    reader: read::Reader,
}

impl std::io::Read for SyncReader {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.reader.read(buf)
    }
}

impl SyncReader {
    /// Checks that data read from disk passes integrity checks. Returns the
    /// algorithm that was used verified the data. Should be called only after
    /// all data has been read from disk.
    ///
    /// ## Example
    /// ```no_run
    /// use std::io::Read;
    ///
    /// fn main() -> cacache::Result<()> {
    ///     let mut fd = cacache::SyncReader::open("./my-cache", "my-key")?;
    ///     let mut str = String::new();
    ///     fd.read_to_string(&mut str).expect("Failed to read to string");
    ///     // Remember to check that the data you got was correct!
    ///     fd.check()?;
    ///     Ok(())
    /// }
    /// ```
    pub fn check(self) -> Result<Algorithm> {
        self.reader.check()
    }

    /// Opens a new synchronous file handle into the cache, looking it up in the
    /// index using `key`.
    ///
    /// ## Example
    /// ```no_run
    /// use std::io::Read;
    ///
    /// fn main() -> cacache::Result<()> {
    ///     let mut fd = cacache::SyncReader::open("./my-cache", "my-key")?;
    ///     let mut str = String::new();
    ///     fd.read_to_string(&mut str).expect("Failed to parse string");
    ///     // Remember to check that the data you got was correct!
    ///     fd.check()?;
    ///     Ok(())
    /// }
    /// ```
    pub fn open<P, K>(cache: P, key: K) -> Result<SyncReader>
    where
        P: AsRef<Path>,
        K: AsRef<str>,
    {
        fn inner(cache: &Path, key: &str) -> Result<SyncReader> {
            if let Some(entry) = index::find(cache, key)? {
                SyncReader::open_hash(cache, entry.integrity)
            } else {
                Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
            }
        }
        inner(cache.as_ref(), key.as_ref())
    }

    /// Opens a new synchronous file handle into the cache, based on its integrity address.
    ///
    /// ## Example
    /// ```no_run
    /// use std::io::Read;
    ///
    /// fn main() -> cacache::Result<()> {
    ///     let sri = cacache::write_sync("./my-cache", "key", b"hello world")?;
    ///     let mut fd = cacache::SyncReader::open_hash("./my-cache", sri)?;
    ///     let mut str = String::new();
    ///     fd.read_to_string(&mut str).expect("Failed to read to string");
    ///     // Remember to check that the data you got was correct!
    ///     fd.check()?;
    ///     Ok(())
    /// }
    /// ```
    pub fn open_hash<P>(cache: P, sri: Integrity) -> Result<SyncReader>
    where
        P: AsRef<Path>,
    {
        Ok(SyncReader {
            reader: read::open(cache.as_ref(), sri)?,
        })
    }
}

/// Reads the entire contents of a cache file synchronously into a bytes
/// vector, looking the data up by key.
///
/// ## Example
/// ```no_run
/// use std::io::Read;
///
/// fn main() -> cacache::Result<()> {
///     let data = cacache::read_sync("./my-cache", "my-key")?;
///     Ok(())
/// }
/// ```
pub fn read_sync<P, K>(cache: P, key: K) -> Result<Vec<u8>>
where
    P: AsRef<Path>,
    K: AsRef<str>,
{
    fn inner(cache: &Path, key: &str) -> Result<Vec<u8>> {
        if let Some(entry) = index::find(cache, key)? {
            read_hash_sync(cache, &entry.integrity)
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref())
}

/// Reads the entire contents of a cache file synchronously into a bytes
/// vector, looking the data up by its content address.
///
/// ## Example
/// ```no_run
/// use std::io::Read;
///
/// fn main() -> cacache::Result<()> {
///     let sri = cacache::write_sync("./my-cache", "my-key", b"hello")?;
///     let data = cacache::read_hash_sync("./my-cache", &sri)?;
///     Ok(())
/// }
/// ```
pub fn read_hash_sync<P>(cache: P, sri: &Integrity) -> Result<Vec<u8>>
where
    P: AsRef<Path>,
{
    read::read(cache.as_ref(), sri)
}

/// Copies a cache entry by key to a specified location. Returns the number of
/// bytes copied.
///
/// On platforms that support it, this will create a copy-on-write "reflink"
/// with a full-copy fallback.
///
/// ## Example
/// ```no_run
/// use std::io::Read;
///
/// fn main() -> cacache::Result<()> {
///     cacache::copy_sync("./my-cache", "my-key", "./my-hello.txt")?;
///     Ok(())
/// }
/// ```
pub fn copy_sync<P, K, Q>(cache: P, key: K, to: Q) -> Result<u64>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    fn inner(cache: &Path, key: &str, to: &Path) -> Result<u64> {
        if let Some(entry) = index::find(cache, key)? {
            copy_hash_sync(cache, &entry.integrity, to)
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref())
}

/// Copies a cache entry by key to a specified location. Does not verify cache
/// contents while copying.
///
/// On platforms that support it, this will create a copy-on-write "reflink"
/// with a full-copy fallback.
///
/// ## Example
/// ```no_run
/// use std::io::Read;
///
/// fn main() -> cacache::Result<()> {
///     cacache::copy_unchecked_sync("./my-cache", "my-key", "./my-hello.txt")?;
///     Ok(())
/// }
/// ```
pub fn copy_unchecked_sync<P, K, Q>(cache: P, key: K, to: Q) -> Result<u64>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    fn inner(cache: &Path, key: &str, to: &Path) -> Result<u64> {
        if let Some(entry) = index::find(cache, key)? {
            copy_hash_unchecked_sync(cache, &entry.integrity, to)
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref())
}

/// Copies a cache entry by integrity address to a specified location. Returns
/// the number of bytes copied.
///
/// On platforms that support it, this will create a copy-on-write "reflink"
/// with a full-copy fallback.
///
/// ## Example
/// ```no_run
/// use std::io::Read;
///
/// fn main() -> cacache::Result<()> {
///     let sri = cacache::write_sync("./my-cache", "my-key", b"hello")?;
///     cacache::copy_hash_sync("./my-cache", &sri, "./my-hello.txt")?;
///     Ok(())
/// }
/// ```
pub fn copy_hash_sync<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<u64>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::copy(cache.as_ref(), sri, to.as_ref())
}

/// Copies a cache entry by integrity address to a specified location. Does
/// not verify cache contents while copying.
///
/// On platforms that support it, this will create a copy-on-write "reflink"
/// with a full-copy fallback.
///
/// ## Example
/// ```no_run
/// use std::io::Read;
///
/// fn main() -> cacache::Result<()> {
///     let sri = cacache::write_sync("./my-cache", "my-key", b"hello")?;
///     cacache::copy_hash_unchecked_sync("./my-cache", &sri, "./my-hello.txt")?;
///     Ok(())
/// }
/// ```
pub fn copy_hash_unchecked_sync<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<u64>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::copy_unchecked(cache.as_ref(), sri, to.as_ref())
}

/// Creates a reflink/clonefile from a cache entry to a destination path.
///
/// Fails if the destination is on a different filesystem or if the filesystem
/// does not support reflinks.
///
/// Currently, reflinks are known to work on APFS (macOS), XFS, btrfs, and
/// ReFS (Windows DevDrive)
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     cacache::reflink_sync("./my-cache", "my-key", "./data.txt")?;
///     Ok(())
/// }
/// ```
pub fn reflink_sync<P, K, Q>(cache: P, key: K, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    fn inner(cache: &Path, key: &str, to: &Path) -> Result<()> {
        if let Some(entry) = index::find(cache, key)? {
            reflink_hash_sync(cache, &entry.integrity, to)
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref())
}

/// Reflinks/clonefiles cache data by hash to a specified location.
///
/// Fails if the destination is on a different filesystem or if the filesystem
/// does not support reflinks.
///
/// Currently, reflinks are known to work on APFS (macOS), XFS, btrfs, and
/// ReFS (Windows DevDrive)
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     let sri = cacache::write_sync("./my-cache", "my-key", b"hello world")?;
///     cacache::reflink_hash_sync("./my-cache", &sri, "./data.txt")?;
///     Ok(())
/// }
/// ```
pub fn reflink_hash_sync<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::reflink(cache.as_ref(), sri, to.as_ref())
}

/// Reflinks/clonefiles cache data by hash to a specified location. Cache data
/// will not be checked during linking.
///
/// Fails if the destination is on a different filesystem or if the filesystem
/// does not support reflinks.
///
/// Currently, reflinks are known to work on APFS (macOS), XFS, btrfs, and
/// ReFS (Windows DevDrive)
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     let sri = cacache::write_sync("./my-cache", "my-key", b"hello world")?;
///     cacache::reflink_hash_unchecked_sync("./my-cache", &sri, "./data.txt")?;
///     Ok(())
/// }
/// ```
pub fn reflink_hash_unchecked_sync<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::reflink_unchecked(cache.as_ref(), sri, to.as_ref())
}

/// Reflinks/clonefiles cache data to a specified location. Cache data will
/// not be checked during linking.
///
/// Fails if the destination is on a different filesystem or if the filesystem
/// does not support reflinks.
///
/// Currently, reflinks are known to work on APFS (macOS), XFS, btrfs, and
/// ReFS (Windows DevDrive)
///
/// ## Example
/// ```no_run
/// use async_std::prelude::*;
/// use async_attributes;
///
/// #[async_attributes::main]
/// async fn main() -> cacache::Result<()> {
///     cacache::reflink_unchecked_sync("./my-cache", "my-key", "./data.txt")?;
///     Ok(())
/// }
/// ```
pub fn reflink_unchecked_sync<P, K, Q>(cache: P, key: K, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    fn inner(cache: &Path, key: &str, to: &Path) -> Result<()> {
        if let Some(entry) = index::find(cache, key)? {
            reflink_hash_unchecked_sync(cache, &entry.integrity, to)
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref())
}

/// Hard links a cache entry by key to a specified location. The cache entry
/// contents will not be checked, and all the usual caveats of hard links
/// apply: The potentially-shared cache might be corrupted if the hard link is
/// modified.
pub fn hard_link_unchecked_sync<P, K, Q>(cache: P, key: K, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    fn inner(cache: &Path, key: &str, to: &Path) -> Result<()> {
        if let Some(entry) = index::find(cache, key)? {
            hard_link_hash_unchecked_sync(cache, &entry.integrity, to)
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref())
}

/// Hard links a cache entry by key to a specified location.
pub fn hard_link_sync<P, K, Q>(cache: P, key: K, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    K: AsRef<str>,
    Q: AsRef<Path>,
{
    fn inner(cache: &Path, key: &str, to: &Path) -> Result<()> {
        if let Some(entry) = index::find(cache, key)? {
            read::hard_link(cache, &entry.integrity, to)
        } else {
            Err(Error::EntryNotFound(cache.to_path_buf(), key.into()))
        }
    }
    inner(cache.as_ref(), key.as_ref(), to.as_ref())
}

/// Hard links a cache entry by integrity address to a specified location,
/// verifying contents as hard links are created.
pub fn hard_link_hash_sync<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::hard_link(cache.as_ref(), sri, to.as_ref())
}

/// Hard links a cache entry by integrity address to a specified location. The
/// cache entry contents will not be checked, and all the usual caveats of
/// hard links apply: The potentially-shared cache might be corrupted if the
/// hard link is modified.
pub fn hard_link_hash_unchecked_sync<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<()>
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    read::hard_link_unchecked(cache.as_ref(), sri, to.as_ref())
}

/// Gets metadata for a certain key.
///
/// Note that the existence of a metadata entry is not a guarantee that the
/// underlying data exists, since they are stored and managed independently.
/// To verify that the underlying associated data exists, use `exists_sync()`.
pub fn metadata_sync<P, K>(cache: P, key: K) -> Result<Option<Metadata>>
where
    P: AsRef<Path>,
    K: AsRef<str>,
{
    index::find(cache.as_ref(), key.as_ref())
}

/// Returns true if the given hash exists in the cache.
pub fn exists_sync<P: AsRef<Path>>(cache: P, sri: &Integrity) -> bool {
    read::has_content(cache.as_ref(), sri).is_some()
}

#[cfg(test)]
mod tests {
    #[cfg(any(feature = "async-std", feature = "tokio"))]
    use crate::async_lib::AsyncReadExt;
    use std::fs;

    #[cfg(feature = "async-std")]
    use async_attributes::test as async_test;
    #[cfg(feature = "tokio")]
    use tokio::test as async_test;

    #[cfg(any(feature = "async-std", feature = "tokio"))]
    #[async_test]
    async fn test_open() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_owned();
        crate::write(&dir, "my-key", b"hello world").await.unwrap();

        let mut handle = crate::Reader::open(&dir, "my-key").await.unwrap();
        let mut str = String::new();
        handle.read_to_string(&mut str).await.unwrap();
        handle.check().unwrap();
        assert_eq!(str, String::from("hello world"));
    }

    #[cfg(any(feature = "async-std", feature = "tokio"))]
    #[async_test]
    async fn test_open_hash() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_owned();
        let sri = crate::write(&dir, "my-key", b"hello world").await.unwrap();

        let mut handle = crate::Reader::open_hash(&dir, sri).await.unwrap();
        let mut str = String::new();
        handle.read_to_string(&mut str).await.unwrap();
        handle.check().unwrap();
        assert_eq!(str, String::from("hello world"));
    }

    #[test]
    fn test_open_sync() {
        use std::io::prelude::*;
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_owned();
        crate::write_sync(&dir, "my-key", b"hello world").unwrap();

        let mut handle = crate::SyncReader::open(&dir, "my-key").unwrap();
        let mut str = String::new();
        handle.read_to_string(&mut str).unwrap();
        handle.check().unwrap();
        assert_eq!(str, String::from("hello world"));
    }

    #[test]
    fn test_open_hash_sync() {
        use std::io::prelude::*;
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_owned();
        let sri = crate::write_sync(&dir, "my-key", b"hello world").unwrap();

        let mut handle = crate::SyncReader::open_hash(&dir, sri).unwrap();
        let mut str = String::new();
        handle.read_to_string(&mut str).unwrap();
        handle.check().unwrap();
        assert_eq!(str, String::from("hello world"));
    }

    #[cfg(any(feature = "async-std", feature = "tokio"))]
    #[async_test]
    async fn test_read() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_owned();
        crate::write(&dir, "my-key", b"hello world").await.unwrap();

        let data = crate::read(&dir, "my-key").await.unwrap();
        assert_eq!(data, b"hello world");
    }

    #[cfg(any(feature = "async-std", feature = "tokio"))]
    #[async_test]
    async fn test_read_hash() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_owned();
        let sri = crate::write(&dir, "my-key", b"hello world").await.unwrap();

        let data = crate::read_hash(&dir, &sri).await.unwrap();
        assert_eq!(data, b"hello world");
    }

    #[test]
    fn test_read_sync() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_owned();
        crate::write_sync(&dir, "my-key", b"hello world").unwrap();

        let data = crate::read_sync(&dir, "my-key").unwrap();
        assert_eq!(data, b"hello world");
    }

    #[test]
    fn test_read_hash_sync() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_owned();
        let sri = crate::write_sync(&dir, "my-key", b"hello world").unwrap();

        let data = crate::read_hash_sync(&dir, &sri).unwrap();
        assert_eq!(data, b"hello world");
    }

    #[cfg(any(feature = "async-std", feature = "tokio"))]
    #[async_test]
    async fn test_copy() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let dest = dir.join("data");
        crate::write(&dir, "my-key", b"hello world").await.unwrap();

        crate::copy(&dir, "my-key", &dest).await.unwrap();
        let data = crate::async_lib::read(&dest).await.unwrap();
        assert_eq!(data, b"hello world");
    }

    #[cfg(any(feature = "async-std", feature = "tokio"))]
    #[async_test]
    async fn test_copy_hash() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let dest = dir.join("data");
        let sri = crate::write(&dir, "my-key", b"hello world").await.unwrap();

        crate::copy_hash(&dir, &sri, &dest).await.unwrap();
        let data = crate::async_lib::read(&dest).await.unwrap();
        assert_eq!(data, b"hello world");
    }

    #[test]
    fn test_copy_sync() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let dest = dir.join("data");
        crate::write_sync(dir, "my-key", b"hello world").unwrap();

        crate::copy_sync(dir, "my-key", &dest).unwrap();
        let data = fs::read(&dest).unwrap();
        assert_eq!(data, b"hello world");
    }

    #[test]
    fn test_copy_hash_sync() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let dest = dir.join("data");
        let sri = crate::write_sync(dir, "my-key", b"hello world").unwrap();

        crate::copy_hash_sync(dir, &sri, &dest).unwrap();
        let data = fs::read(&dest).unwrap();
        assert_eq!(data, b"hello world");
    }
}