File: SkAnySubclass.h

package info (click to toggle)
wpewebkit 2.48.3-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 421,720 kB
  • sloc: cpp: 3,670,389; javascript: 194,411; ansic: 165,592; python: 46,476; asm: 19,276; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; java: 1,993; sh: 1,948; lex: 1,327; pascal: 366; makefile: 85
file content (73 lines) | stat: -rw-r--r-- 2,079 bytes parent folder | download | duplicates (8)
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
/*
 * 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;
    }

    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(); }

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

#endif  // SkAnySubclass_DEFINED