summaryrefslogtreecommitdiff
path: root/support/pkgcheck/src/recode.rs
blob: 39a85bacd2c7611ca72e3996c9a51c2fc568dda7 (plain)
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
// the code here is taken (and slightly modified) from https://github.com/XadillaX/crlf2lf

//
// convert CRLF (0D 0A) to LF ( 0A )
//

use std::fs::File;
use std::io::prelude::*;
use std::io::{self, Read};
use std::path::Path;

// The caller has to make sure that crlf2lf is only
// used for text files
pub fn crlf2lf(fname: &str) -> Result<(), io::Error> {
    let path = Path::new(fname);

    let mut hdl_in;
    match File::open(path) {
        Ok(f) => {
            hdl_in = f;
        }
        Err(e) => return Err(e),
    };
    let mut buffer: Vec<u8> = Vec::new();

    // read the whole file
    if let Err(e) = hdl_in.read_to_end(&mut buffer) {
        return Err(e);
    };

    // convert \r\n to \n
    let mut another_vec: Vec<u8> = Vec::new();
    const CR: u8 = 0x0d; // 13
    const LF: u8 = 0x0a; // 10

    for i in 0..buffer.len() {
        if buffer[i] == CR {
            if i < buffer.len() - 1 && buffer[i + 1] == LF {
                continue;
            }

            if i > 0 && buffer[i - 1] == LF {
                continue;
            }
        }
        another_vec.push(buffer[i]);
    }

    let mut hdl_out;
    match File::create(path) {
        Ok(f) => {
            hdl_out = f;
        }
        Err(e) => return Err(e),
    };

    // write back
    match hdl_out.write(&another_vec) {
        Ok(_) => Ok(()),
        Err(e) => Err(e),
    }
}