File: SomeFileReader.hpp

package info (click to toggle)
r-bioc-alabaster.base 1.6.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,652 kB
  • sloc: cpp: 11,377; sh: 29; makefile: 2
file content (70 lines) | stat: -rw-r--r-- 1,765 bytes parent folder | download | duplicates (2)
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
#ifndef BYTEME_SOME_FILE_READER_HPP
#define BYTEME_SOME_FILE_READER_HPP

#include "Reader.hpp"
#include "RawFileReader.hpp"
#include "GzipFileReader.hpp"
#include "magic_numbers.hpp"
#include <memory>
#include <cstdio>

/**
 * @file SomeFileReader.hpp
 *
 * @brief Read a possibly-Gzipped file.
 */

namespace byteme {

/**
 * @brief Read a file that may or may not be Gzipped.
 *
 * This class will automatically detect whether `path` refers to a text file or a Gzip-compressed file, based on its initial magic numbers.
 * After that, it will dispatch appropriately to `RawFileReader` or `GzipFileReader` respectively.
 */
class SomeFileReader : public Reader {
public:
    /**
     * @param path Path to the file.
     * @param buffer_size Size of the buffer to use for reading.
     */
    SomeFileReader(const char* path, size_t buffer_size = 65536) { 
        unsigned char header[3];
        size_t read;
        {
            SelfClosingFILE file(path, "rb");
            read = std::fread(header, sizeof(unsigned char), 3, file.handle);
        }

        if (is_gzip(header, read)) {
            source.reset(new GzipFileReader(path, buffer_size));
        } else {
            source.reset(new RawFileReader(path, buffer_size));
        }
    }

    /**
     * @param path Path to the file.
     * @param buffer_size Size of the buffer to use for reading.
     */
    SomeFileReader(const std::string& path, size_t buffer_size = 65536) : SomeFileReader(path.c_str(), buffer_size) {}

    bool load() {
        return source->load();
    }

    const unsigned char* buffer() const {
        return source->buffer();
    }

    size_t available() const {
        return source->available();
    }

private:
    std::unique_ptr<Reader> source;
};

}

#endif