xiaoyifang / goldendict-ng

The Next Generation GoldenDict
https://xiaoyifang.github.io/goldendict-ng/
Other
1.71k stars 95 forks source link

clean: unify a common idx file read pattern uint32_t size + data #1969

Closed shenlebantongying closed 2 days ago

shenlebantongying commented 2 days ago

redo https://github.com/xiaoyifang/goldendict-ng/pull/1435

(I don't like the ceremony of reading dictionaryName.)

sonarcloud[bot] commented 2 days ago

Quality Gate Passed Quality Gate passed

Issues
1 New issue
0 Accepted issues

Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarQube Cloud

xiaoyifang commented 2 days ago
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdint>

// 模板方法,读取一个整数表示的长度,然后读取相应字节
template <typename T>
T read_data(std::ifstream& file) {
    uint32_t length;
    file.read(reinterpret_cast<char*>(&length), sizeof(length));

    if (!file) {
        throw std::runtime_error("Failed to read length");
    }

    T data;
    if constexpr (std::is_same_v<T, std::string>) {
        data.resize(length);
        file.read(&data[0], length);
    } else if constexpr (std::is_same_v<T, std::vector<uint8_t>>) {
        data.resize(length);
        file.read(reinterpret_cast<char*>(data.data()), length);
    } else {
        static_assert(std::is_same_v<T, T>, "Unsupported return type");
    }

    if (!file) {
        throw std::runtime_error("Failed to read data");
    }

    return data;
}

int main() {
    std::ifstream file("data.bin", std::ios::binary);
    if (!file) {
        std::cerr << "Failed to open file" << std::endl;
        return 1;
    }

    try {
        std::string str_data = read_data<std::string>(file);
        std::vector<uint8_t> vec_data = read_data<std::vector<uint8_t>>(file);

        std::cout << "String data: " << str_data << std::endl;
        std::cout << "Vector data: ";
        for (uint8_t byte : vec_data) {
            std::cout << std::hex << static_cast<int>(byte) << " ";
        }
        std::cout << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    file.close();
    return 0;
}

return type can be specified.