if(!cap||cap<=0)throw`Semaphore capacity cannot be '${cap}', must be a number greater than 0`;
this.capacity=cap;
this.length=0;
letself=this;
// Waiters for the seamphore
varnext={
waiters:[],
// wait for a slot to be available, then take it. If there are slots, the promise resolves immediately, if not, it is added to the release queue and will resolve when there is one available for it.
// release a raw lock on the semaphore. if there are pending `acquire()` promises, the length is not decremented, but the next queued up acquire is resolved insetad.
release:()=>{
if(next.waiters.length>0)// There are pending waiters
next.waiters.shift()();// No need to decrement, there is a pending waiter and that slot goes directly to them. (asyn)
elseself.length-=1;// Deremenet the length (imm)
}
//TODO: ,dispose: (error = new SemaphoreDisposed()) => { } // reject all `waiters`, and cause all new `acquire()`s to immediately reject.
/// Acquire a semaphore lock (if one is not available, wait until one is) and then run `func()` with the lock held, afterwards, release the lock and return the result of `func()`.
/// If `func` is an async function, it is awaited and the lock is released after it has resolved (or rejected), and the result of this function is the result of that promise.
/// Attempt to acquire a semaphore lock and execute `func()` with that lock held. If there is no available lock, immediately return and do not attempt to run `func()`.
///
/// # Async `func()`
/// If `func` is an async function, the return value of this function will be an awaitable promise that will release the lock upon awaiting (resolved or rejected), and yield the value of the awaited promise.
///
/// # Returns
/// You can use the second parameter to the function, the object `opt`, to choose how success/failure is represented in the returned value from the function call/returned promise (in the case of `func()` returning a promise (see above))
///
/// ## On successfully acquireing the lock:
/// * If `opt.wrap === true`: An object in the form of `{success: true, value: <returned value>}`. If `opt.keep_func === "always"`, the object will include the field `"func": func` as well. (See below)
/// * Otherwise, just the returned value itself. (*default*)
///
/// ## On failing to acquire the lock:
/// * If `opt.wrap === true`: An object in the form of `{success: false, value: opt.or, func: <see below>}`
/// * Otherwise, just `opt.or`. (*default*)
///
/// ### Notes
/// * If `opt` has no field called `or`, `undefined` is used instead.
/// * If `opt` has a field called `keep_func` and that field is `=== true` or `=== "always"`, *and* `opt.wrap === true`: On a failure to acquire the lock, the wrapped object will be in the form `{ value: (opt.or || undefined), success: false, "func": func }`.