style: Clean up RecycleBin
This commit is contained in:
1 parent
2489a2ce0c
commit
6bf2c297d7
1 file changed
+65
-16
@@ -1,31 +1,80 @@
|
||||
using System;
|
||||
using mbts;
|
||||
|
||||
using System;
|
||||
|
||||
namespace bts.utils {
|
||||
class RecycleBin<T> where T : class {
|
||||
readonly Action<T> _init, _destroy;
|
||||
static class RecycleBin {
|
||||
public static RecycleBin<T> create<T>(Action<T> init, Action<T> destroy) where T : class =>
|
||||
new(init, destroy);
|
||||
|
||||
public static RecycleBin<T> create<T>(Func<T, IDisposable> init) where T : class {
|
||||
IDisposable dispose_value = null;
|
||||
return new(init_impl, destroy_impl);
|
||||
|
||||
void init_impl(T value) =>
|
||||
dispose_value = init(value);
|
||||
|
||||
void destroy_impl(T _) =>
|
||||
dispose_value?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class RecycleBin<T> : IDisposable {
|
||||
readonly Action<T> _init;
|
||||
Action _destroy;
|
||||
T _value;
|
||||
|
||||
public RecycleBin(Action<T> init, Action<T> destroy) {
|
||||
_init = init;
|
||||
_destroy = destroy;
|
||||
}
|
||||
public RecycleBin(Func<T, IDisposable> init) {
|
||||
IDisposable d = null;
|
||||
_init = v => d = init(v);
|
||||
_destroy = _ => d.Dispose();
|
||||
IDisposable dispose_value = null;
|
||||
_init = init_impl;
|
||||
_destroy = destroy_impl;
|
||||
|
||||
void init_impl(T value) {
|
||||
if (dispose_value is not null) {
|
||||
throw new InvalidOperationException(
|
||||
"dispose_value should be null (this may indicate the previous value wasn't disposed)");
|
||||
}
|
||||
dispose_value = init(value);
|
||||
}
|
||||
|
||||
void destroy_impl() =>
|
||||
Disposable.dispose(ref dispose_value);
|
||||
}
|
||||
|
||||
public RecycleBin(Action<T> init, Action<T> destroy) {
|
||||
if (init is null) {
|
||||
throw new ArgumentNullException(nameof(init));
|
||||
}
|
||||
|
||||
if (destroy is null) {
|
||||
_init = init;
|
||||
} else {
|
||||
_init = init_impl;
|
||||
void init_impl(T value) {
|
||||
init(value);
|
||||
_destroy = destroy_impl;
|
||||
|
||||
void destroy_impl() {
|
||||
destroy(value);
|
||||
_destroy = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public T value {
|
||||
get => _value;
|
||||
set {
|
||||
if (!ReferenceEquals(value, _value)) {
|
||||
if (_value != null)
|
||||
_destroy?.Invoke(_value);
|
||||
_value = value;
|
||||
if (_value != null)
|
||||
_init?.Invoke(_value);
|
||||
if (ReferenceEquals(value, _value)) {
|
||||
return;
|
||||
}
|
||||
_destroy?.Invoke();
|
||||
_value = value;
|
||||
_init(_value);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() =>
|
||||
_destroy?.Invoke();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user