~aleteoryx/muditaos

ref: 6ce0dc4df3820d0cb3cf2e5b22fb2f2feb3d0d79 muditaos/module-utils/Utils.cpp -rw-r--r-- 1.5 KiB
6ce0dc4d — jimmorrisson [EGD-4751] Change: new filesystem handling implementation in module services. (#1151) 5 years ago
                                                                                
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
// Copyright (c) 2017-2020, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "Utils.hpp"

namespace utils::filesystem
{
    long int filelength(std::FILE *file) noexcept
    {
        if (file == nullptr) {
            return 0;
        }
        std::fseek(file, 0, SEEK_END);
        return std::ftell(file);
    }

    void computeCRC32(std::FILE *file, unsigned long *outCrc32) noexcept
    {
        if (outCrc32 == nullptr)
            return;

        auto buf = std::make_unique<unsigned char[]>(purefs::buffer::crc_buf);
        size_t bufLen;

        *outCrc32 = 0;

        while (!std::feof(file)) {
            bufLen = std::fread(buf.get(), 1, purefs::buffer::crc_buf, file);
            if (bufLen <= 0)
                break;

            *outCrc32 = Crc32_ComputeBuf(*outCrc32, buf.get(), bufLen);
        }
    }

    std::string generateRandomId(std::size_t length) noexcept
    {
        const std::string CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

        std::random_device random_device;
        std::mt19937 generator(random_device());
        generator.seed(utils::time::Timestamp().getTime());
        std::uniform_int_distribution<> distribution(0, CHARACTERS.size() - 1);

        std::string random_string;

        for (std::size_t i = 0; i < length; ++i) {
            random_string += CHARACTERS[distribution(generator)];
        }

        return random_string;
    }
} // namespace utils::filesystem