Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie dot falco at gmail dot com)
3 : //
4 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 : //
7 : // Official repository: https://github.com/cppalliance/beast2
8 : //
9 :
10 : #include <boost/beast2/logger.hpp>
11 : #include <iostream>
12 : #include <mutex>
13 : #include <unordered_map>
14 : #include <vector>
15 :
16 : namespace boost {
17 : namespace beast2 {
18 :
19 0 : section::
20 : section() noexcept = default;
21 :
22 : void
23 0 : section::
24 : write(
25 : int level,
26 : std::string s)
27 : {
28 : (void)level;
29 : // VFALCO NO! This is just for demo purposes
30 : static std::mutex m;
31 0 : std::lock_guard<std::mutex> lock(m);
32 0 : std::cerr << s << std::endl;
33 0 : }
34 :
35 0 : section::
36 0 : section(core::string_view name)
37 0 : : impl_(std::make_shared<impl>())
38 : {
39 0 : impl_->name = name;
40 0 : }
41 :
42 : //------------------------------------------------
43 :
44 : struct log_sections::impl
45 : {
46 : struct hash
47 : {
48 : std::size_t
49 0 : operator()(core::string_view const& s) const noexcept
50 : {
51 : #if SIZE_MAX == 4294967295U
52 : std::size_t hash = 2166136261; // FNV offset basis
53 : for (unsigned char c : s)
54 : hash ^= c, hash *= 16777619; // FNV prime
55 : #else
56 0 : std::size_t hash = 1469598103934665603; // FNV offset basis
57 0 : for (unsigned char c : s)
58 0 : hash ^= c, hash *= 1099511628211; // FNV prime
59 : #endif
60 0 : return hash;
61 : }
62 : };
63 :
64 : std::mutex m;
65 : std::unordered_map<core::string_view, section, hash> map;
66 : std::vector<section> vec;
67 : };
68 :
69 0 : log_sections::
70 : ~log_sections()
71 : {
72 0 : delete impl_;
73 0 : }
74 :
75 0 : log_sections::
76 0 : log_sections()
77 0 : : impl_(new impl)
78 : {
79 0 : }
80 :
81 : section
82 0 : log_sections::
83 : get(core::string_view name)
84 : {
85 : // contention for this lock should be minimal,
86 : // as most sections are created at startup.
87 0 : std::lock_guard<std::mutex> lock(impl_->m);
88 0 : auto it = impl_->map.find(name);
89 0 : if(it != impl_->map.end())
90 0 : return it->second;
91 : // the map stores a string_view; make sure
92 : // the string data it references does not
93 : // move after creation.
94 0 : auto v = section(name);
95 0 : impl_->map.emplace(
96 0 : core::string_view(v.impl_->name), v);
97 0 : impl_->vec.push_back(v);
98 0 : return v;
99 0 : }
100 :
101 : auto
102 0 : log_sections::
103 : get_sections() const noexcept ->
104 : std::vector<section>
105 : {
106 0 : std::lock_guard<std::mutex> lock(impl_->m);
107 0 : return impl_->vec;
108 0 : }
109 :
110 : } // beast2
111 : } // boost
|