File: SkAnySubclass.h

package info (click to toggle)
webkit2gtk 2.51.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 455,340 kB
  • sloc: cpp: 3,865,253; javascript: 197,710; ansic: 165,177; python: 49,241; asm: 21,868; ruby: 18,095; perl: 16,926; xml: 4,623; sh: 2,409; yacc: 2,356; java: 2,019; lex: 1,330; pascal: 372; makefile: 210
file content (79 lines) | stat: -rw-r--r-- 2,298 bytes parent folder | download | duplicates (24)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
 * Copyright 2023 Google LLC
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SkAnySubclass_DEFINED
#define SkAnySubclass_DEFINED

#include "include/private/base/SkAssert.h"

#include <cstddef>
#include <new>
#include <type_traits>  // IWYU pragma: keep
#include <utility>

/**
 *  Stores any subclass `T` of `Base`, where sizeof(T) <= `Size`, without using the heap.
 *  Doesn't need advance knowledge of T, so it's particularly suited to platform or backend
 *  implementations of a generic interface, where the set of possible subclasses is finite and
 *  known, but can't be made available at compile-time.
 */
template <typename Base, size_t Size>
class SkAnySubclass {
public:
    SkAnySubclass() = default;
    ~SkAnySubclass() {
        this->reset();
    }

    SkAnySubclass(const SkAnySubclass&) = delete;
    SkAnySubclass& operator=(const SkAnySubclass&) = delete;
    SkAnySubclass(SkAnySubclass&&) = delete;
    SkAnySubclass& operator=(SkAnySubclass&&) = delete;

    template <typename T, typename... Args>
    void emplace(Args&&... args) {
        static_assert(std::is_base_of_v<Base, T>);
        static_assert(sizeof(T) <= Size);
        // We're going to clean up our stored object by calling ~Base:
        static_assert(std::has_virtual_destructor_v<Base> || std::is_trivially_destructible_v<T>);
        SkASSERT(!fValid);
        new (fData) T(std::forward<Args>(args)...);
        fValid = true;
    }

    void reset() {
        if (fValid) {
            this->get()->~Base();
        }
        fValid = false;
    }

    bool has_value() const { return fValid; }
    explicit operator bool() const { return this->has_value(); }

    const Base* get() const {
        SkASSERT(fValid);
        return std::launder(reinterpret_cast<const Base*>(fData));
    }

    Base* get() {
        SkASSERT(fValid);
        return std::launder(reinterpret_cast<Base*>(fData));
    }

    Base* operator->() { return this->get(); }
    const Base* operator->() const { return this->get(); }

    Base& operator*() { return *this->get(); }
    const Base& operator*() const { return *this->get(); }

private:
    alignas(8) std::byte fData[Size];
    bool fValid = false;
};

#endif  // SkAnySubclass_DEFINED