-
Notifications
You must be signed in to change notification settings - Fork 2
/
native-instance.ts
67 lines (56 loc) · 1.56 KB
/
native-instance.ts
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
// Copyright Dirk Lemstra https://github.com/dlemstra/magick-wasm.
// Licensed under the Apache License, Version 2.0.
import { MagickError } from "../magick-error.ts";
import { Exception } from "./exception/exception.ts";
export interface INativeInstance {
dispose(): void;
}
export abstract class NativeInstance implements NativeInstance {
private readonly disposeMethod: (instance: number) => void;
private instance: number;
/** @internal */
protected constructor(
instance: number,
disposeMethod: (instance: number) => void,
) {
this.instance = instance;
this.disposeMethod = disposeMethod;
}
/** @internal */
get _instance(): number {
if (this.instance > 0) {
return this.instance;
}
if (this.instance === -1) {
this._instanceNotInitialized();
}
throw new MagickError("instance is disposed");
}
/** @internal */
set _instance(instance: number) {
this.disposeInstance(this.instance);
this.instance = instance;
}
dispose(): void {
this.instance = this.disposeInstance(this.instance);
}
/** @internal */
protected _setInstance(instance: number, exception: Exception): void {
exception.check(() => {
this.dispose();
this.instance = instance;
}, () => {
this.disposeInstance(instance);
});
}
/** @internal */
protected _instanceNotInitialized(): void {
throw new MagickError("instance is not initialized");
}
private disposeInstance(instance: number): number {
if (instance > 0) {
this.disposeMethod(instance);
}
return 0;
}
}