summaryrefslogtreecommitdiffstats
path: root/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Map.sys.mjs
blob: 5b6e6dc172968ed0f2df2c71b4b999ace11bda2e (plain)
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
// Export the FFIConverter object to make external types work.
export class {{ ffi_converter }} extends FfiConverterArrayBuffer {
    static read(dataStream) {
        const len = dataStream.readInt32();
        const map = {};
        for (let i = 0; i < len; i++) {
            const key = {{ key_type.ffi_converter() }}.read(dataStream);
            const value = {{ value_type.ffi_converter() }}.read(dataStream);
            map[key] = value;
        }

        return map;
    }

    static write(dataStream, value) {
        dataStream.writeInt32(Object.keys(value).length);
        for (const key in value) {
            {{ key_type.ffi_converter() }}.write(dataStream, key);
            {{ value_type.ffi_converter() }}.write(dataStream, value[key]);
        }
    }

    static computeSize(value) {
        // The size of the length
        let size = 4;
        for (const key in value) {
            size += {{ key_type.ffi_converter() }}.computeSize(key);
            size += {{ value_type.ffi_converter() }}.computeSize(value[key]);
        }
        return size;
    }

    static checkType(value) {
        for (const key in value) {
            try {
                {{ key_type.ffi_converter() }}.checkType(key);
            } catch (e) {
                if (e instanceof UniFFITypeError) {
                    e.addItemDescriptionPart("(key)");
                }
                throw e;
            }

            try {
                {{ value_type.ffi_converter() }}.checkType(value[key]);
            } catch (e) {
                if (e instanceof UniFFITypeError) {
                    e.addItemDescriptionPart(`[${key}]`);
                }
                throw e;
            }
        }
    }
}