1"use strict"; 2/* 3 * Copyright (c) 2022-2025 Huawei Device Co., Ltd. 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16Object.defineProperty(exports, "__esModule", { value: true }); 17exports.markableQueue = void 0; 18const compat_1 = require("#koalaui/compat"); 19/** 20 * Creates a new markable queue to safely process callbacks across several threads or tasks. 21 * @param reversed - `true` changes the order of calling callbacks 22 */ 23function markableQueue(reversed = false) { 24 return reversed ? new ReversedQueue() : new DefaultQueue(); 25} 26exports.markableQueue = markableQueue; 27class DefaultQueue { 28 constructor() { 29 this.last = new compat_1.AtomicRef(new Block()); 30 this.first = new compat_1.AtomicRef(this.last.value); 31 this.marker = new compat_1.AtomicRef(undefined); 32 } 33 setMarker() { 34 const marker = new Block(); 35 this.last.getAndSet(marker).next.value = marker; 36 this.marker.value = marker; 37 } 38 addCallback(callback) { 39 const block = new Block(callback); 40 this.last.getAndSet(block).next.value = block; 41 } 42 callCallbacks() { 43 var _a; 44 const marker = this.marker.getAndSet(undefined); 45 if (marker) { 46 let block = this.first.getAndSet(marker); 47 while (block !== marker) { 48 (_a = block.callback) === null || _a === void 0 ? void 0 : _a.call(block); 49 block = block.next.value; 50 } 51 } 52 } 53 clear() { 54 this.last.value = this.first.value; 55 this.marker.value = undefined; 56 } 57} 58class ReversedQueue { 59 constructor() { 60 this.last = new compat_1.AtomicRef(undefined); 61 this.marker = new compat_1.AtomicRef(undefined); 62 } 63 setMarker() { 64 const marker = new Block(); 65 marker.next.value = this.last.getAndSet(marker); 66 this.marker.value = marker; 67 } 68 addCallback(callback) { 69 const block = new Block(callback); 70 block.next.value = this.last.getAndSet(block); 71 } 72 callCallbacks() { 73 var _a, _b; 74 const marker = this.marker.getAndSet(undefined); 75 if (marker) { 76 let block = marker.next.getAndSet(undefined); 77 while (block) { 78 (_b = (_a = block).callback) === null || _b === void 0 ? void 0 : _b.call(_a); 79 block = block.next.value; 80 } 81 } 82 } 83 clear() { 84 this.last.value = undefined; 85 this.marker.value = undefined; 86 } 87} 88class Block { 89 constructor(callback) { 90 this.next = new compat_1.AtomicRef(undefined); 91 this.callback = callback; 92 } 93} 94//# sourceMappingURL=MarkableQueue.js.map