Q2NS dev
ns-3 module
Loading...
Searching...
No Matches
q2nsviz-trace-writer.h
Go to the documentation of this file.
1/*-----------------------------------------------------------------------------
2 * Q2NS - Quantum Network Simulator
3 * Copyright (c) 2026 quantuminternet.it
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
8 *---------------------------------------------------------------------------*/
9#pragma once
10
11#include "ns3/simulator.h"
12#include <cstdio>
13#include <fstream>
14#include <mutex>
15#include <string>
16
18public:
20 static TraceWriter inst;
21 return inst;
22 }
23 void Open(const std::string& path) {
24 std::lock_guard<std::mutex> g(mu_);
25 if (ofs_.is_open())
26 ofs_.close();
27 ofs_.open(path, std::ios::out | std::ios::trunc);
28 }
29 void Write(const std::string& line) {
30 std::lock_guard<std::mutex> g(mu_);
31 if (ofs_.is_open()) {
32 ofs_ << line << "\n";
33 ofs_.flush();
34 }
35 }
36 void Close() {
37 std::lock_guard<std::mutex> g(mu_);
38 if (ofs_.is_open())
39 ofs_.close();
40 }
41
42private:
43 std::mutex mu_;
44 std::ofstream ofs_;
45 TraceWriter() = default;
46};
47
48inline std::string J(const std::string& s) {
49 std::string out;
50 out.reserve(s.size() + 8);
51 out.push_back('"');
52 for (unsigned char uc : s) {
53 switch (uc) {
54 case '\"':
55 out += "\\\"";
56 break;
57 case '\\':
58 out += "\\\\";
59 break;
60 case '\b':
61 out += "\\b";
62 break;
63 case '\f':
64 out += "\\f";
65 break;
66 case '\n':
67 out += "\\n";
68 break;
69 case '\r':
70 out += "\\r";
71 break;
72 case '\t':
73 out += "\\t";
74 break;
75 default:
76 if (uc < 0x20) {
77 char buf[7];
78 std::snprintf(buf, sizeof(buf), "\\u%04X", (unsigned) uc);
79 out += buf;
80 } else {
81 out.push_back(static_cast<char>(uc)); // keep UTF-8 bytes as-is
82 }
83 }
84 }
85 out.push_back('"');
86 return out;
87}
88
89
90inline uint64_t JTns() {
91 return ns3::Simulator::Now().GetNanoSeconds();
92}
static TraceWriter & Instance()
TraceWriter()=default
void Open(const std::string &path)
std::ofstream ofs_
void Write(const std::string &line)
std::string J(const std::string &s)
uint64_t JTns()