openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
57 lines (56 loc) • 1.4 kB
JavaScript
//#region src/shared/bounded-buffer.ts
var BoundedBuffer = class {
constructor(e, t, n = () => 1) {
this.capacity = e;
this.overflow = t;
this.measure = n;
this.values = [];
this.head = 0;
this.size = 0;
this.closed = false;
}
push(e) {
if (this.closed) return false;
const t = this.measure(e);
if (this.size + t <= this.capacity) {
this.values.push(e);
this.size += t;
return true;
}
if (this.overflow.mode !== "drop-oldest") {
this.closed = true;
if (this.overflow.mode === "fail-closed") {
this.drain();
this.overflow.onOverflow();
}
return false;
}
this.values.push(e);
this.size += t;
while (this.size > this.capacity && this.head < this.values.length - 1) {
const e = this.values[this.head];
this.size -= this.measure(e);
this.values[this.head] = void 0;
this.head += 1;
}
if (this.size > this.capacity) {
const t = this.overflow.fit?.(e, this.capacity);
this.values = t === void 0 ? [] : [t];
this.head = 0;
this.size = t === void 0 ? 0 : this.measure(t);
} else if (this.head * 2 >= this.values.length) {
this.values = this.values.slice(this.head);
this.head = 0;
}
return true;
}
drain() {
const e = this.head === 0 ? this.values : this.values.slice(this.head);
this.values = [];
this.head = 0;
this.size = 0;
return e;
}
};
//#endregion
export { BoundedBuffer as t };