admerge 0.1.3

Merge multiply sources into one, with advanced options
Documentation
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
//! Definition of various mergers.
#![allow(unreachable_patterns)]

use crate::error::{ErrorKind, Result};
use crate::util;

use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Seek, Write};
use std::path::Path;

use byteseeker::ByteSeeker;

/// A Merger that can merge multiple sources that implement [`Read`] and [`Seek`] into one.
///
/// Generally speaking, when using `RsMerger`, you'll first call [`new`] to create a
/// merger builder, then call configuration methods to set each option. And eventually, call
/// [`merge_sources_into`] to actually merge multiple sources into a given writer.
///
/// # Behaviours
///
/// The current algorithm to merge sources is described as following:
///
/// 1. If any leading padding is given by [`pad_with`], writes it into the writer.
/// 2. For each source, if skip range is given by [`skip_head`] and
///    [`skip_tail`], writes the contents remaining into the writer.
/// 3. For each source, if forcing ending newline option is set by
///    [`force_ending_newline`], writes a ending newline into the writer if this source
///    is not ends with a newline.
/// 4. For each source, if any inner padding is given by [`pad_with`], writes it into the
///    writer.
/// 5. If any ending padding is given by [`pad_with`], writes it into the writer.
///
/// # Examples
///
/// ```
/// use admerge::{RsMerger, Skip, Pad, Newline, Result};
/// use std::io::Cursor;
///
/// fn main() -> Result<()> {
///     // Cursor implements `Read` and `Seek`.
///     let mut c1 = Cursor::new(" record 1\n date created: 2000/01/01\n");
///     let mut c2 = Cursor::new(" record 2\n date created: 2000/01/01\n");
///     let mut c3 = Cursor::new(" record 3\n date created: 2000/01/01\n");
///     let mut buf = Vec::new();
///
///     // Configures merger.
///     let mut merger = RsMerger::new();
///     merger.skip_tail(Skip::LinesOnce(1));
///     merger.pad_with(Pad::Before(b"header\n"));
///     merger.force_ending_newline(Newline::Lf);
///
///     // Merges sources into one.
///     merger.merge_sources_into(vec![&mut c1, &mut c2, &mut c3], &mut buf)?;
///     assert_eq!(
///         std::str::from_utf8(&buf).unwrap(),
///         "header\n record 1\n record 2\n record 3\n date created: 2000/01/01\n"
///     );
///
///     Ok(())
/// }
/// ```
///
/// [`Read`]: std::io::Read
/// [`Seek`]: std::io::Seek
/// [`new`]: RsMerger::new
/// [`pad_with`]: RsMerger::pad_with
/// [`skip_head`]: RsMerger::skip_head
/// [`skip_tail`]: RsMerger::skip_tail
/// [`force_ending_newline`]: RsMerger::force_ending_newline
/// [`merge_sources_into`]: RsMerger::merge_sources_into
#[derive(Debug, Clone)]
pub struct RsMerger<'a> {
    opts: RsMergerOptions<'a>,
}

#[derive(Clone, Debug, Default)]
struct RsMergerOptions<'a> {
    skip_head: Option<Skip<'a>>,
    skip_tail: Option<Skip<'a>>,
    padding: Option<Pad<'a>>,
    newline: Option<Newline>,
}

/// Controls the skip behaviour when merging sources.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum Skip<'a> {
    /// Skip a number of bytes from each part.
    Bytes(usize),
    /// Keep the contents of the first part untouched (or the last part if passed by `skip_tail`),
    /// but skip a given number of bytes from the rest parts.
    BytesOnce(usize),
    /// Skip a number of lines from each part.
    Lines(usize),
    /// Keep the contents of the first part untouched (or the last part if passed by `skip_tail`),
    /// but skip a given number of lines from the rest parts.
    LinesOnce(usize),
    /// Skip every byte sequence that matches a given byte pattern from each part.
    /// The given byte pattern must match the first few bytes.
    Repeats(&'a [u8]),
    /// Skip a sequence of bytes until reaching a given byte pattern from each part.
    /// The given byte pattern will be skipped.
    Until(&'a [u8]),
    /// Skip a sequence of bytes until reaching a given byte pattern from each part.
    /// The given byte pattern will not be skipped.
    Before(&'a [u8]),
}

/// Configures where padding will be filled when merging sources.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum Pad<'a> {
    /// Fills the given padding before the first source.
    Before(&'a [u8]),
    /// Fills the given padding between two sources.
    Between(&'a [u8]),
    /// Fills the given padding after the last source.
    After(&'a [u8]),
    /// Fills the given paddings before the first source,
    /// between sources and after the last source.
    ///
    /// The argument order is (Before, Between, After).
    Custom(Option<&'a [u8]>, Option<&'a [u8]>, Option<&'a [u8]>),
}

/// The style of a newline, either unix-style `LF` or dos-style `CRLF`.
#[derive(Debug, Clone, Copy)]
pub enum Newline {
    Lf,
    Crlf,
}

impl Default for Newline {
    fn default() -> Self {
        Newline::Lf
    }
}

impl<'a> Default for RsMerger<'a> {
    fn default() -> Self {
        let opts = RsMergerOptions {
            skip_head: None,
            skip_tail: None,
            padding: None,
            newline: None,
        };
        RsMerger { opts }
    }
}

// Public APIs
impl<'a> RsMerger<'a> {
    /// Creates a new `RsMerger` builder.
    ///
    /// # Examples
    ///
    /// ```
    /// use admerge::{RsMerger, Result};
    /// use std::io::Cursor;
    ///
    /// fn main() -> Result<()> {
    ///     let c1 = Cursor::new("foo ");
    ///     let c2 = Cursor::new("bar ");
    ///     let c3 = Cursor::new("baz ");
    ///     let mut buf = Vec::new();
    ///
    ///     let merger = RsMerger::new();
    ///     merger.merge_sources_into(vec![c1, c2, c3], &mut buf)?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn new() -> Self {
        Default::default()
    }

    /// Configures this merger to skip partial of contents from the head of each source.
    ///
    /// # Examples
    ///
    /// Keeps the first given source untouched, but skips first line from the rest sources.
    ///
    /// ```
    /// use admerge::{RsMerger, Skip, Result};
    /// use std::io::Cursor;
    ///
    /// fn main() -> Result<()> {
    ///     // Cursor implements `Read` and `Seek`.
    ///     let mut c1 = Cursor::new("header\n record 1\n");
    ///     let mut c2 = Cursor::new("header\n record 2\n");
    ///     let mut c3 = Cursor::new("header\n record 3\n");
    ///     let mut buf = Vec::new();
    ///
    ///     // Configures merger.
    ///     let mut merger = RsMerger::new();
    ///     merger.skip_head(Skip::LinesOnce(1));
    ///
    ///     // Merges sources into one.
    ///     merger.merge_sources_into(vec![&mut c1, &mut c2, &mut c3], &mut buf)?;
    ///     assert_eq!(
    ///         std::str::from_utf8(&buf).unwrap(),
    ///         "header\n record 1\n record 2\n record 3\n"
    ///     );
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn skip_head(&mut self, skip: Skip<'a>) -> &mut Self {
        self.opts.skip_head = Some(skip);
        self
    }

    /// Configures this merger to skip partial of contents from the tail of each source.
    ///
    /// # Examples
    ///
    /// Keeps the last given source untouched, but skips last line from the rest sources.
    ///
    /// ```
    /// use admerge::{RsMerger, Skip, Result};
    /// use std::io::Cursor;
    ///
    /// fn main() -> Result<()> {
    ///     // Cursor implements `Read` and `Seek`.
    ///     let mut c1 = Cursor::new(" record 1\n date created: 2000/01/01\n");
    ///     let mut c2 = Cursor::new(" record 2\n date created: 2000/01/01\n");
    ///     let mut c3 = Cursor::new(" record 3\n date created: 2000/01/01\n");
    ///     let mut buf = Vec::new();
    ///
    ///     // Configures merger.
    ///     let mut merger = RsMerger::new();
    ///     merger.skip_tail(Skip::LinesOnce(1));
    ///
    ///     // Merges sources into one.
    ///     merger.merge_sources_into(vec![&mut c1, &mut c2, &mut c3], &mut buf)?;
    ///     assert_eq!(
    ///         std::str::from_utf8(&buf).unwrap(),
    ///         " record 1\n record 2\n record 3\n date created: 2000/01/01\n"
    ///     );
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn skip_tail(&mut self, skip: Skip<'a>) -> &mut Self {
        self.opts.skip_tail = Some(skip);
        self
    }

    /// Configures this merger to fill some padding before, between or after the given sources.
    ///
    /// # Examples
    ///
    /// ```
    /// use admerge::{RsMerger, Pad, Result};
    /// use std::io::Cursor;
    ///
    /// fn main() -> Result<()> {
    ///     // Cursor implements `Read` and `Seek`.
    ///     let mut c1 = Cursor::new(" record 1 ");
    ///     let mut c2 = Cursor::new(" record 2 ");
    ///     let mut c3 = Cursor::new(" record 3 ");
    ///     let mut buf = Vec::new();
    ///
    ///     // Configures merger.
    ///     let mut merger = RsMerger::new();
    ///     merger.pad_with(Pad::Custom(
    ///         Some(b"header"),
    ///         Some(b"padding"),
    ///         Some(b"date created: 2000/01/01")
    ///     ));
    ///
    ///     // Merges sources into one.
    ///     merger.merge_sources_into(vec![&mut c1, &mut c2, &mut c3], &mut buf)?;
    ///     assert_eq!(
    ///         std::str::from_utf8(&buf).unwrap(),
    ///         "header record 1 padding record 2 padding record 3 date created: 2000/01/01"
    ///     );
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn pad_with(&mut self, padding: Pad<'a>) -> &mut Self {
        self.opts.padding = Some(padding);
        self
    }

    /// Configures this merger to force the presence of ending newline after each source.
    ///
    /// Noting that ending newlines are given after sources, not after paddings.
    ///
    /// # Examples
    ///
    /// ```
    /// use admerge::{RsMerger, Newline, Result};
    /// use std::io::Cursor;
    ///
    /// fn main() -> Result<()> {
    ///     // Cursor implements `Read` and `Seek`.
    ///     let mut c1 = Cursor::new(" line 1 ");
    ///     let mut c2 = Cursor::new(" line 2 ");
    ///     let mut c3 = Cursor::new(" line 3 ");
    ///     let mut buf = Vec::new();
    ///
    ///     // Configures merger.
    ///     let mut merger = RsMerger::new();
    ///     merger.force_ending_newline(Newline::Crlf);
    ///
    ///     // Merges sources into one.
    ///     merger.merge_sources_into(vec![&mut c1, &mut c2, &mut c3], &mut buf)?;
    ///     assert_eq!(
    ///         std::str::from_utf8(&buf).unwrap(),
    ///         " line 1 \r\n line 2 \r\n line 3 \r\n"
    ///     );
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn force_ending_newline(&mut self, newline: Newline) -> &mut Self {
        self.opts.newline = Some(newline);
        self
    }

    /// Merges the given sources into the given writer according to the given configurations.
    ///
    /// # Errors
    ///
    /// Returns an error variant of [`ErrorKind::NothingPassed`] if the given source vector is
    /// empty;
    ///
    /// Returns an error variant of [`ErrorKind::InvalidSkip`] if the given [`Skip`]s cannot
    /// applied to the given sources;
    ///
    /// Returns an error variant of [`ErrorKind::Io`] if any I/O errors were encountered.
    ///
    /// # Examples
    ///
    /// ```
    /// use admerge::{RsMerger, Skip, Pad, Newline, Result};
    /// use std::io::Cursor;
    ///
    /// fn main() -> Result<()> {
    ///     // Cursor implements `Read` and `Seek`.
    ///     let mut c1 = Cursor::new(" record 1\n date created: 2000/01/01\n");
    ///     let mut c2 = Cursor::new(" record 2\n date created: 2000/01/01\n");
    ///     let mut c3 = Cursor::new(" record 3\n date created: 2000/01/01\n");
    ///     let mut buf = Vec::new();
    ///
    ///     // Configures merger.
    ///     let mut merger = RsMerger::new();
    ///     merger.skip_tail(Skip::LinesOnce(1));
    ///     merger.pad_with(Pad::Before(b"header\n"));
    ///     merger.force_ending_newline(Newline::Lf);
    ///
    ///     // Merges sources into one.
    ///     merger.merge_sources_into(vec![&mut c1, &mut c2, &mut c3], &mut buf)?;
    ///     assert_eq!(
    ///         std::str::from_utf8(&buf).unwrap(),
    ///         "header\n record 1\n record 2\n record 3\n date created: 2000/01/01\n"
    ///     );
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn merge_sources_into<RS, W>(&self, mut sources: Vec<RS>, writer: &mut W) -> Result<()>
    where
        RS: Read + Seek,
        W: Write,
    {
        let len = sources.len();
        if len == 0 {
            return Err(ErrorKind::NothingPassed);
        }

        // Merge first part.
        self.write_contents(&mut sources[0], writer, PartPos::Start)?;
        // Merge inner parts.
        for i in 1..(len - 1) {
            self.write_contents(&mut sources[i], writer, PartPos::Inside)?;
        }
        // Merge last part.
        if len > 1 {
            self.write_contents(&mut sources[len - 1], writer, PartPos::End)?;
        }

        return Ok(());
    }
}

// Indicates the relative position.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum PartPos {
    Start,
    Inside,
    End,
}

// Private methods
impl<'a> RsMerger<'a> {
    // Writes the contents (entire or partial) of one part into the writer.
    fn write_contents<RS, W>(&self, reader: &mut RS, writer: &mut W, pos: PartPos) -> Result<()>
    where
        RS: Read + Seek,
        W: Write,
    {
        // Writes padding before this source.
        self.write_padding_before(writer, pos)?;

        // Needs to know if the reader stream ends with a newline or not.
        let endn = util::endswith_newline(reader)?;

        // Gets the stream length of the given reader;
        let stream_len = util::seek_to_end(reader)? as usize;

        // Resets the cursor first.
        util::seek_to_start(reader)?;

        if !self.should_view_contents() {
            // Just copy the entire contents if viewing into the reader is not required.
            io::copy(reader, writer)?;
        } else {
            // Skips contents if either `skip_head` or `skip_tail` is set.
            if self.opts.skip_head.is_some() || self.opts.skip_tail.is_some() {
                let mut seeker = ByteSeeker::new(reader);

                // Position to start reading.
                seeker.reset();
                let start = match &self.opts.skip_head {
                    None => 0,
                    Some(skip) => match *skip {
                        Skip::Bytes(n) => n,
                        Skip::BytesOnce(n) => match pos {
                            PartPos::Start => 0,
                            _ => n,
                        },
                        Skip::Lines(n) => match n {
                            0 => 0,
                            _ => {
                                let pos;

                                if !endn && n == 1 {
                                    match seeker.seek_nth(b"\n", 1) {
                                        Ok(idx) => {
                                            pos = idx + 1;
                                        }
                                        Err(e) => match e.kind() {
                                            byteseeker::ErrorKind::ByteNotFound => pos = stream_len,
                                            _ => return Err(e.into()),
                                        },
                                    }
                                } else {
                                    let nth = if endn { n } else { n - 1 };
                                    match seeker.seek_nth(b"\n", nth) {
                                        Ok(idx) => {
                                            if endn {
                                                pos = idx + 1;
                                            } else {
                                                match seeker.seek(b"\n") {
                                                    Ok(idx) => {
                                                        pos = idx + 1;
                                                    }
                                                    Err(e) => match e.kind() {
                                                        byteseeker::ErrorKind::ByteNotFound => {
                                                            pos = stream_len
                                                        }
                                                        _ => return Err(e.into()),
                                                    },
                                                }
                                            }
                                        }
                                        Err(e) => match e.kind() {
                                            byteseeker::ErrorKind::ByteNotFound => {
                                                return Err(ErrorKind::InvalidSkip);
                                            }
                                            _ => return Err(e.into()),
                                        },
                                    }
                                }

                                pos
                            }
                        },
                        Skip::LinesOnce(n) => match pos {
                            PartPos::Start => 0,
                            _ => match n {
                                0 => 0,
                                _ => {
                                    let pos;

                                    if !endn && n == 1 {
                                        match seeker.seek_nth(b"\n", 1) {
                                            Ok(idx) => {
                                                pos = idx + 1;
                                            }
                                            Err(e) => match e.kind() {
                                                byteseeker::ErrorKind::ByteNotFound => {
                                                    pos = stream_len
                                                }
                                                _ => return Err(e.into()),
                                            },
                                        }
                                    } else {
                                        let nth = if endn { n } else { n - 1 };
                                        match seeker.seek_nth(b"\n", nth) {
                                            Ok(idx) => {
                                                if endn {
                                                    pos = idx + 1;
                                                } else {
                                                    match seeker.seek(b"\n") {
                                                        Ok(idx) => {
                                                            pos = idx + 1;
                                                        }
                                                        Err(e) => match e.kind() {
                                                            byteseeker::ErrorKind::ByteNotFound => {
                                                                pos = stream_len
                                                            }
                                                            _ => return Err(e.into()),
                                                        },
                                                    }
                                                }
                                            }
                                            Err(e) => match e.kind() {
                                                byteseeker::ErrorKind::ByteNotFound => {
                                                    return Err(ErrorKind::InvalidSkip);
                                                }
                                                _ => return Err(e.into()),
                                            },
                                        }
                                    }

                                    pos
                                }
                            },
                        },
                        Skip::Until(bytes) => match seeker.seek(bytes) {
                            Ok(pos) => pos + bytes.len(),
                            Err(e) => match e.kind() {
                                byteseeker::ErrorKind::ByteNotFound => stream_len,
                                _ => return Err(e.into()),
                            },
                        },
                        Skip::Before(bytes) => match seeker.seek(bytes) {
                            Ok(pos) => pos,
                            Err(e) => match e.kind() {
                                byteseeker::ErrorKind::ByteNotFound => stream_len,
                                _ => return Err(e.into()),
                            },
                        },
                        Skip::Repeats(bytes) => {
                            let width = bytes.len();
                            match width {
                                0 => 0,
                                _ => {
                                    let mut buf = Vec::with_capacity(width);
                                    buf.resize(width, 0);

                                    let mut reader = seeker.get_mut();
                                    util::seek_to_start(&mut reader)?;
                                    let mut bytes_match = 0;
                                    loop {
                                        reader.read_exact(&mut buf)?;
                                        if &buf == bytes {
                                            bytes_match += width;
                                            if bytes_match == stream_len {
                                                break;
                                            }
                                        } else {
                                            break;
                                        }
                                    }

                                    bytes_match
                                }
                            }
                        }
                        _ => unimplemented!(),
                    },
                };

                // Position to end reading.
                //
                // Only bytes before this position will be read.
                seeker.reset();
                let end = match &self.opts.skip_tail {
                    None => util::seek_to_end(reader)? as usize,
                    Some(skip) => match *skip {
                        Skip::Bytes(n) => match n > stream_len {
                            true => return Err(ErrorKind::InvalidSkip),
                            false => stream_len - n,
                        },
                        Skip::BytesOnce(n) => match pos {
                            PartPos::End => stream_len,
                            _ => match n > stream_len {
                                true => return Err(ErrorKind::InvalidSkip),
                                false => stream_len - n,
                            },
                        },
                        Skip::Lines(n) => match n {
                            0 => stream_len,
                            _ => {
                                let pos;

                                // Ignore any ending newline.
                                if endn {
                                    seeker.seek_back(b"\n")?;
                                }

                                match n {
                                    1 => match seeker.seek_back(b"\n") {
                                        Ok(idx) => {
                                            pos = idx + 1;
                                        }
                                        Err(e) => match e.kind() {
                                            byteseeker::ErrorKind::ByteNotFound => pos = 0,
                                            _ => return Err(e.into()),
                                        },
                                    },
                                    _ => match seeker.seek_nth_back(b"\n", n - 1) {
                                        Ok(_) => match seeker.seek_back(b"\n") {
                                            Ok(idx) => pos = idx + 1,
                                            Err(e) => match e.kind() {
                                                byteseeker::ErrorKind::ByteNotFound => pos = 0,
                                                _ => return Err(e.into()),
                                            },
                                        },
                                        Err(e) => match e.kind() {
                                            byteseeker::ErrorKind::ByteNotFound => {
                                                return Err(ErrorKind::InvalidSkip)
                                            }
                                            _ => return Err(e.into()),
                                        },
                                    },
                                }

                                pos
                            }
                        },
                        Skip::LinesOnce(n) => match pos {
                            PartPos::End => stream_len,
                            _ => match n {
                                0 => stream_len,
                                _ => {
                                    let pos;

                                    // Ignore any ending newline.
                                    if endn {
                                        seeker.seek_back(b"\n")?;
                                    }

                                    match n {
                                        1 => match seeker.seek_back(b"\n") {
                                            Ok(idx) => {
                                                pos = idx + 1;
                                            }
                                            Err(e) => match e.kind() {
                                                byteseeker::ErrorKind::ByteNotFound => pos = 0,
                                                _ => return Err(e.into()),
                                            },
                                        },
                                        _ => match seeker.seek_nth_back(b"\n", n - 1) {
                                            Ok(_) => match seeker.seek_back(b"\n") {
                                                Ok(idx) => pos = idx + 1,
                                                Err(e) => match e.kind() {
                                                    byteseeker::ErrorKind::ByteNotFound => pos = 0,
                                                    _ => return Err(e.into()),
                                                },
                                            },
                                            Err(e) => match e.kind() {
                                                byteseeker::ErrorKind::ByteNotFound => {
                                                    return Err(ErrorKind::InvalidSkip)
                                                }
                                                _ => return Err(e.into()),
                                            },
                                        },
                                    }

                                    pos
                                }
                            },
                        },
                        Skip::Until(bytes) => match seeker.seek_back(bytes) {
                            Ok(pos) => pos,
                            Err(e) => match e.kind() {
                                byteseeker::ErrorKind::ByteNotFound => 0,
                                _ => return Err(e.into()),
                            },
                        },
                        Skip::Before(bytes) => match seeker.seek(bytes) {
                            Ok(pos) => pos + bytes.len(),
                            Err(e) => match e.kind() {
                                byteseeker::ErrorKind::ByteNotFound => 0,
                                _ => return Err(e.into()),
                            },
                        },
                        Skip::Repeats(bytes) => {
                            let width = bytes.len();
                            match width {
                                0 => stream_len,
                                _ => {
                                    let mut buf = Vec::with_capacity(width);
                                    buf.resize(width, 0);

                                    let mut reader = seeker.get_mut();
                                    util::seek_to_end(&mut reader)?;
                                    let mut bytes_match = 0;
                                    loop {
                                        // Avoid seek negative.
                                        if bytes_match + width > stream_len {
                                            break;
                                        }
                                        util::seek_end(-((bytes_match + width) as i64), reader)?;
                                        reader.read_exact(&mut buf)?;
                                        if &buf == bytes {
                                            bytes_match += width;
                                            if bytes_match == stream_len {
                                                break;
                                            }
                                        } else {
                                            break;
                                        }
                                    }

                                    stream_len - bytes_match
                                }
                            }
                        }
                    },
                };

                match (start, end) {
                    _ if end < start => return Err(ErrorKind::InvalidSkip),
                    _ if start == end => (),
                    _ => {
                        // Reads the desired contents.
                        let bytes_count = end - start;
                        match bytes_count {
                            0 => (),
                            _ => {
                                let mut buf_reader = BufReader::new(reader);
                                let mut read = 0;
                                util::seek_start(start as u64, &mut buf_reader)?;

                                loop {
                                    let buf = buf_reader.fill_buf()?;
                                    let length = buf.len();
                                    if length == 0 {
                                        break;
                                    }
                                    if read + length > bytes_count {
                                        let mut buffer = buf.to_owned();
                                        buffer.truncate(bytes_count - read);
                                        writer.write_all(&buffer)?;
                                        buf_reader.consume(length);
                                    } else {
                                        read += length;
                                        writer.write_all(buf)?;
                                        buf_reader.consume(length);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                // Just copy the entire contents of the given reader into the given writer.
                io::copy(reader, writer)?;
            }
        }

        // Should we writer ending newline?
        if self.opts.newline.is_some() && !endn {
            match self.opts.newline.unwrap() {
                Newline::Lf => {
                    writer.write_all(b"\n")?;
                }
                Newline::Crlf => {
                    writer.write_all(b"\r\n")?;
                }
            }
        }

        // Writes padding after this source.
        self.write_padding_after(writer, pos)?;

        Ok(())
    }

    fn write_padding_before<W: Write>(&self, writer: &mut W, pos: PartPos) -> Result<()> {
        if let Some(pad) = &self.opts.padding {
            // Check if padding should be filled before this source.
            match (pad, pos) {
                (Pad::Before(padding), PartPos::Start) => {
                    writer.write_all(padding)?;
                }
                (Pad::Custom(Some(padding), _, _), PartPos::Start) => {
                    writer.write_all(padding)?;
                }
                _ => (),
            }
        }

        Ok(())
    }

    fn write_padding_after<W: Write>(&self, writer: &mut W, pos: PartPos) -> Result<()> {
        if let Some(pad) = &self.opts.padding {
            // Check if padding should be filled before this source.
            match (pad, pos) {
                (Pad::After(padding), PartPos::End) => {
                    writer.write_all(padding)?;
                }
                (Pad::Between(padding), PartPos::Start) => {
                    writer.write_all(padding)?;
                }
                (Pad::Between(padding), PartPos::Inside) => {
                    writer.write_all(padding)?;
                }
                (Pad::Custom(_, Some(padding), _), PartPos::Start) => {
                    writer.write_all(padding)?;
                }
                (Pad::Custom(_, Some(padding), _), PartPos::Inside) => {
                    writer.write_all(padding)?;
                }
                (Pad::Custom(_, _, Some(padding)), PartPos::End) => {
                    writer.write_all(padding)?;
                }
                _ => (),
            }
        }

        Ok(())
    }

    // Returns `true` if viewing into the contents of each part is required.
    fn should_view_contents(&self) -> bool {
        self.opts.newline.is_some()
            || self.opts.skip_head.is_some()
            || self.opts.skip_tail.is_some()
    }
}

/// Simliar to [`RsMerger`] but provides dedicated methods to work with [`Path`]s and [`File`]s.
#[derive(Clone, Debug)]
pub struct FileMerger<'a>(RsMerger<'a>);

impl<'a> Default for FileMerger<'a> {
    fn default() -> Self {
        let opts = RsMergerOptions {
            skip_head: None,
            skip_tail: None,
            padding: None,
            newline: None,
        };
        FileMerger(RsMerger { opts })
    }
}

impl<'a> FileMerger<'a> {
    /// Creates a new `FileMerger` builder.
    pub fn new() -> Self {
        Default::default()
    }

    /// Configures this merger to skip partial of contents from the head of each file.
    pub fn skip_head(&mut self, skip: Skip<'a>) -> &mut Self {
        self.0.opts.skip_head = Some(skip);
        self
    }

    /// Configures this merger to skip partial of contents from the tail of each file.
    pub fn skip_tail(&mut self, skip: Skip<'a>) -> &mut Self {
        self.0.opts.skip_tail = Some(skip);
        self
    }

    /// Configures this merger to fill some padding before, between or after the file contents.
    pub fn pad_with(&mut self, padding: Pad<'a>) -> &mut Self {
        self.0.opts.padding = Some(padding);
        self
    }

    /// Configures this merger to force the presence of ending newline after each file.
    pub fn force_ending_newline(&mut self, newline: Newline) -> &mut Self {
        self.0.opts.newline = Some(newline);
        self
    }

    /// Opens file paths given and merges file contents into the given writer according to the
    /// given configrations.
    ///
    /// Nothing that this method will return an error if any path given is not point to a regular
    /// file. For an variant that ignores invalid paths, see [`with_paths_lossy`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use admerge::{FileMerger, Skip, Pad, Newline, Result};
    /// use std::fs::OpenOptions;
    ///
    /// fn main() -> Result<()> {
    ///     let mut file = OpenOptions::new().append(true).create(true).open("merged.txt")?;
    ///
    ///     // Configures merger.
    ///     let mut merger = FileMerger::new();
    ///     merger.skip_tail(Skip::LinesOnce(1));
    ///     merger.pad_with(Pad::Before(b"leading contents\n"));
    ///     merger.force_ending_newline(Newline::Lf);
    ///
    ///     // Merges sources into one.
    ///     merger.with_paths(vec!["foo.txt", "bar.txt", "baz.txt"], &mut file)?;
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error variant of [`ErrorKind::NothingPassed`] if the given path vector is
    /// empty;
    ///
    /// Returns an error variant of [`ErrorKind::InvalidPath`] if the given paths contain invalid
    /// path.
    ///
    /// Returns an error variant of [`ErrorKind::InvalidSkip`] if the given [`Skip`]s cannot
    /// applied to the given sources;
    ///
    /// Returns an error variant of [`ErrorKind::Io`] if any I/O errors were encountered.
    ///
    /// [`with_paths_lossy`]: FileMerger::with_paths_lossy
    pub fn with_paths<P, W>(&self, paths: Vec<P>, writer: &mut W) -> Result<()>
    where
        P: AsRef<Path>,
        W: Write,
    {
        let sources: Result<Vec<_>> = paths
            .into_iter().enumerate()
            .map(|(i, p)| File::open(p).map_err(|_| ErrorKind::InvalidPath(i)))
            .collect();

        self.with_files(sources?, writer)
    }

    /// Opens every file path given if path points to a regular file, and then merges file contents
    /// into the given writer according to the given configrations.
    ///
    /// See also [`with_paths`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use admerge::{FileMerger, Skip, Pad, Newline, Result};
    /// use std::fs::OpenOptions;
    ///
    /// fn main() -> Result<()> {
    ///     let mut file = OpenOptions::new().append(true).create(true).open("merged.txt")?;
    ///
    ///     // Configures merger.
    ///     let mut merger = FileMerger::new();
    ///     merger.skip_tail(Skip::LinesOnce(1));
    ///     merger.pad_with(Pad::Before(b"leading contents\n"));
    ///     merger.force_ending_newline(Newline::Lf);
    ///
    ///     // Merges sources into one.
    ///     merger.with_paths_lossy(vec!["foo.txt", "bar.txt", "not a file path"], &mut file)?;
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error variant of [`ErrorKind::NothingPassed`] if the given path vector is
    /// empty;
    ///
    /// Returns an error variant of [`ErrorKind::InvalidSkip`] if the given [`Skip`]s cannot
    /// applied to the given sources;
    ///
    /// Returns an error variant of [`ErrorKind::Io`] if any I/O errors were encountered.
    ///
    /// [`with_paths`]: FileMerger::with_paths
    pub fn with_paths_lossy<P, W>(&self, paths: Vec<P>, writer: &mut W) -> Result<()>
    where
        P: AsRef<Path>,
        W: Write,
    {
        // Dumps any path that does not point to a regular file..
        let sources: Vec<_> = paths.into_iter().filter(|p| p.as_ref().is_file()).collect();

        self.with_paths(sources, writer)
    }

    /// Reads sequentially from the given files and merges their contents into the given writer
    /// according to the given configrations.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use admerge::{FileMerger, Skip, Pad, Newline, Result};
    /// use std::fs::{File, OpenOptions};
    ///
    /// fn main() -> Result<()> {
    ///     let f1 = File::open("foo.txt")?;
    ///     let f2 = File::open("bar.txt")?;
    ///     let f3 = File::open("baz.txt")?;
    ///     let mut file = OpenOptions::new().append(true).create(true).open("merged.txt")?;
    ///
    ///     // Configures merger.
    ///     let mut merger = FileMerger::new();
    ///     merger.skip_tail(Skip::LinesOnce(1));
    ///     merger.pad_with(Pad::Before(b"leading contents\n"));
    ///     merger.force_ending_newline(Newline::Lf);
    ///
    ///     // Merges sources into one.
    ///     merger.with_files(vec![f1, f2, f3], &mut file)?;
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error variant of [`ErrorKind::NothingPassed`] if the given path vector is
    /// empty;
    ///
    /// Returns an error variant of [`ErrorKind::InvalidSkip`] if the given [`Skip`]s cannot
    /// applied to the given sources;
    ///
    /// Returns an error variant of [`ErrorKind::Io`] if any I/O errors were encountered.
    pub fn with_files<W>(&self, files: Vec<File>, writer: &mut W) -> Result<()>
    where
        W: Write,
    {
        self.0.merge_sources_into(files, writer)
    }
}