• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 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 RAWHEAP_TRANSLATE_SERIALIZER_H
17 #define RAWHEAP_TRANSLATE_SERIALIZER_H
18 
19 #define NODE_FIELD_COUNT 8
20 #include "ecmascript/dfx/hprof/rawheap_translate/rawheap_translate.h"
21 #include "ecmascript/dfx/hprof/rawheap_translate/utils.h"
22 
23 
24 namespace rawheap_translate {
25 class StreamWriter {
26 public:
StreamWriter()27     StreamWriter()
28     {
29         chunk_.resize(chunkSize_);
30     }
31 
~StreamWriter()32     ~StreamWriter()
33     {
34         EndOfStream();
35     }
36 
37     bool Initialize(const std::string &filePath);
38     void WriteString(const std::string &str);
39     void EndOfStream();
40 
WriteChar(char c)41     void WriteChar(char c)
42     {
43         if (c == '\0') {
44             return;
45         }
46         MaybeWriteChunk();
47         chunk_[current_++] = c;
48     }
49 
WriteNumber(uint64_t num)50     void WriteNumber(uint64_t num)
51     {
52         WriteString(std::to_string(num));
53     }
54 
55 private:
MaybeWriteChunk()56     void MaybeWriteChunk()
57     {
58         if (current_ == chunkSize_) {
59             std::string str(chunk_.begin(), chunk_.end());
60             fileStream_ << str;
61             current_ = 0;
62         }
63     }
64 
65     std::ofstream fileStream_;
66     std::vector<char> chunk_;
67     int current_ {0};
68     int chunkSize_ {1024 * 1024};
69 };
70 
71 class HeapSnapshotJSONSerializer {
72 public:
73     explicit HeapSnapshotJSONSerializer() = default;
74     ~HeapSnapshotJSONSerializer() = default;
75 
76     static bool Serialize(RawHeap *rawheap, StreamWriter *writer);
77 
78 private:
79     static constexpr char ASCII_US = 31;
80     static constexpr char ASCII_DEL = 127;
81     static constexpr uint8_t UTF8_MAX_BYTES = 4;
82 
83 private:
84     static void SerializeSnapshotHeader(RawHeap *rawheap, StreamWriter *writer);
85     static void SerializeNodes(RawHeap *rawheap, StreamWriter *writer);
86     static void SerializeEdges(RawHeap *rawheap, StreamWriter *writer);
87     static void SerializeStringTable(RawHeap *rawheap, StreamWriter *writer);
88     static void SerializeString(const char *str, StreamWriter *writer);
89     static void SerializerSnapshotClosure(StreamWriter *writer);
90 };
91 }  // namespace rawheap_translate
92 #endif