aboutsummaryrefslogtreecommitdiffstats
path: root/src/3rdparty/yoga/event/event.cpp
blob: dad7a9a082e5c848aec406ec1b110a8756216bcd (plain)
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
80
81
82
83
84
// Copyright (C) 2016 The Qt Company Ltd.
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// SPDX-License-Identifier: MIT

#include "event.h"
#include <atomic>
#include <memory>

namespace facebook {
namespace yoga {

const char* LayoutPassReasonToString(const LayoutPassReason value) {
  switch (value) {
    case LayoutPassReason::kInitial:
      return "initial";
    case LayoutPassReason::kAbsLayout:
      return "abs_layout";
    case LayoutPassReason::kStretch:
      return "stretch";
    case LayoutPassReason::kMultilineStretch:
      return "multiline_stretch";
    case LayoutPassReason::kFlexLayout:
      return "flex_layout";
    case LayoutPassReason::kMeasureChild:
      return "measure";
    case LayoutPassReason::kAbsMeasureChild:
      return "abs_measure";
    case LayoutPassReason::kFlexMeasure:
      return "flex_measure";
    default:
      return "unknown";
  }
}

namespace {

struct Node {
  std::function<Event::Subscriber> subscriber = nullptr;
  Node* next = nullptr;

  Node(std::function<Event::Subscriber>&& subscriber)
      : subscriber{std::move(subscriber)} {}
};

std::atomic<Node*> subscribers{nullptr};

Node* push(Node* newHead) {
  Node* oldHead;
  do {
    oldHead = subscribers.load(std::memory_order_relaxed);
    if (newHead != nullptr) {
      newHead->next = oldHead;
    }
  } while (!subscribers.compare_exchange_weak(
      oldHead, newHead, std::memory_order_release, std::memory_order_relaxed));
  return oldHead;
}

} // namespace

void Event::reset() {
  auto head = push(nullptr);
  while (head != nullptr) {
    auto current = head;
    head = head->next;
    delete current;
  }
}

void Event::subscribe(std::function<Subscriber>&& subscriber) {
  push(new Node{std::move(subscriber)});
}

void Event::publish(const YGNode& node, Type eventType, const Data& eventData) {
  for (auto subscriber = subscribers.load(std::memory_order_relaxed);
       subscriber != nullptr;
       subscriber = subscriber->next) {
    subscriber->subscriber(node, eventType, eventData);
  }
}

} // namespace yoga
} // namespace facebook