1/*
2 * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#ifndef ECMASCRIPT_DFX_HPROF_FILE_STREAM_H
17#define ECMASCRIPT_DFX_HPROF_FILE_STREAM_H
18
19#include <cstdint>
20#include <fstream>
21#include <iosfwd>
22#include <utility>
23
24#include "ecmascript/dfx/hprof/stream.h"
25#include "ecmascript/mem/mem_common.h"
26
27namespace panda::ecmascript {
28class FileStream : public Stream {
29public:
30    explicit FileStream(const std::string &fileName);
31    ~FileStream() override;
32
33    void EndOfStream() override;
34
35    // Get chunk's size
36    int GetSize() override
37    {
38        const static int fileChunkSize = static_cast<int>(1_MB);
39        return fileChunkSize;
40    }
41
42    // Writes the chunk of data into the stream
43    bool WriteChunk(char* data, int32_t size) override;
44    bool WriteBinBlock(char *data, int32_t size) override
45    {
46        return WriteChunk(data, size);
47    }
48    bool Good() override;
49    void UpdateHeapStats([[maybe_unused]] HeapStat* data, [[maybe_unused]] int32_t count) override
50    {
51    }
52    void UpdateLastSeenObjectId([[maybe_unused]]int32_t lastSeenObjectId, [[maybe_unused]]int64_t timeStampUs) override
53    {
54    }
55
56private:
57    void Initialize(const std::string &fileName);
58    std::pair<bool, std::string> FilePathValid(const std::string &fileName);
59
60    std::fstream fileStream_;
61};
62
63class FileDescriptorStream : public Stream {
64public:
65    explicit FileDescriptorStream(int32_t fd): fd_(fd) {}
66    ~FileDescriptorStream() override = default;
67
68    void EndOfStream() override;
69
70    // Get chunk's size
71    int GetSize() override
72    {
73        const static int fileChunkSize = static_cast<int>(1_MB);
74        return fileChunkSize;
75    }
76
77    // Writes the chunk of data into the stream
78    bool WriteChunk(char *data, int32_t size) override;
79    bool WriteBinBlock(char *data, int32_t size) override;
80    bool Good() override;
81    void UpdateHeapStats([[maybe_unused]] HeapStat* data, [[maybe_unused]] int32_t count) override
82    {
83    }
84    void UpdateLastSeenObjectId([[maybe_unused]]int32_t lastSeenObjectId, [[maybe_unused]]int64_t timeStampUs) override
85    {
86    }
87
88private:
89    int32_t fd_;
90};
91}  // namespace panda::ecmascript::tooling
92
93#endif  // ECMASCRIPT_DFX_HPROF_FILE_STREAM_H
94