~aleteoryx/muditaos

ref: 5f03b9148ed78d558e139b8a3d563c6f08f33447 muditaos/module-sys/Service/ServiceProxy.hpp -rw-r--r-- 1.3 KiB
5f03b914 — Marcin Smoczyński [EGD-7641] Disable service desktop tests 4 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
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#pragma once

#include <memory>
#include <stdexcept>
#include <utility>

namespace sys
{
    class Service;
}

namespace service
{
    /// Proxy class for classes using Service raw pointer
    /// - initialized in InitHandler
    /// - provides weak bounding with Service (to avoid infinite shared ptr loop)
    /// - used to provide Class <-> System interface
    /// - invalid ServiceProxy will throw runtime error instead of crash on invalid Service* ptr
    class ServiceProxy
    {
      private:
        std::weak_ptr<sys::Service> service;

      protected:
        [[nodiscard]] std::shared_ptr<sys::Service> getService()
        {
            if (auto val = service.lock(); val != nullptr) {
                return val;
            }
            throw std::runtime_error("no service");
        }

      public:
        explicit ServiceProxy(std::weak_ptr<sys::Service> service) : service(std::move(service))
        {}
        ServiceProxy()          = default;
        virtual ~ServiceProxy() = default;
        [[nodiscard]] bool isValid() const noexcept
        {
            return !service.expired();
        }
    };
} // namespace service