cala_core 0.1.1

Low-level platform glue for Cala
Documentation
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
// cala_core
//
// Copyright (c) 2020 Jeron Aldaron Lau
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// https://apache.org/licenses/LICENSE-2.0>, or the Zlib License, <LICENSE-ZLIB
// or http://opensource.org/licenses/Zlib>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! Web-Specific APIs

#![allow(unsafe_code)]

use std::{
    marker::PhantomData,
    cell::RefCell,
    collections::HashMap,
    future::Future,
    pin::Pin,
    task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};

#[cfg(feature = "wasm-bindgen")]
use wasm_bindgen::prelude::*;

#[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
use stdweb::unstable::TryInto;

thread_local! {
    // A map of the resolved promises / ready futures
    static READY: RefCell<HashMap<i32, JsVar>> = RefCell::new(HashMap::new())
}

// Run whenever a Promise resolves.
fn wake_internal(promise: i32, result: i32) {
    // Promise resolving marks the future as "ready" with a value in the map.
    READY.with(|w| w.borrow_mut().insert(promise, JsVar(result)));
    // Promise resolving wakes the thread, so run the executor.
    executor();
}

#[cfg(feature = "wasm-bindgen")]
#[doc = ""]
#[wasm_bindgen]
pub fn wake(promise: i32, result: i32) {
    wake_internal(promise, result);
}

#[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
#[js_export]
fn wake(promise: i32, result: i32) {
    wake_internal(promise, result);
}

#[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
#[no_mangle]
extern "C" fn wake(promise: i32, result: i32) {
    wake_internal(promise, result);
}

/// A JavaScript Promise
#[derive(Debug)]
pub struct JsPromise<T: From<JsVar>>(JsVar, PhantomData::<T>);

impl<T: From<JsVar>> JsPromise<T> {
    /// Poll a JavaScript Promise.
    pub fn poll(&self) -> Poll<T> {
        READY.with(|w| {
            if let Some(value) = w.borrow_mut().remove(&(self.0).0) {
                Poll::Ready(value.into())
            } else {
                Poll::Pending
            }
        })
    }
}

/// A JavaScript variable.
#[derive(Debug)]
pub struct JsVar(i32);

impl JsVar {
    /// Assume the JavaScript variable is a promise, and convert to a JsPromise.
    pub unsafe fn into_promise<T: From<JsVar>>(self) -> JsPromise<T> {
        self.set_waker_internal();
        JsPromise(self, PhantomData)
    }

    /// Assuming the JavaScript variable is a function with two parameters,
    /// convert into a `JsFn`.
    pub unsafe fn into_fn(self) -> JsFn {
        JsFn(self)
    }

    /// Create a new `JsVar` from a Rust integer
    pub fn from_i32(value: i32) -> JsVar {
        Self::from_i32_internal(value)
    }

    #[cfg(feature = "wasm-bindgen")]
    fn from_i32_internal(value: i32) -> Self {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_store_int(idx: i32) -> i32;
        }

        Self(_cala_js_store_int(value))
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    fn from_i32_internal(value: i32) -> Self {
        Self(
            js! {
                return _cala_js_store_int(@{value});
            }
            .try_into()
            .unwrap(),
        )
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    fn from_i32_internal(value: i32) -> Self {
        extern "C" {
            // Free a JavaScript object
            fn _cala_js_store_int(idx: i32) -> i32;
        }
        Self(unsafe { _cala_js_store_int(value) })
    }

    /// Get a Rust integer from a `JsVar`.
    pub unsafe fn into_i32(&self) -> i32 {
        Self::into_i32_internal(self)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn into_i32_internal(value: &JsVar) -> i32 {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_load_int(idx: i32) -> i32;
        }
        _cala_js_load_int(value.0)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn into_i32_internal(value: &JsVar) -> i32 {
        let ret = js! {
            return _cala_js_load_int(@{value.0});
        };
        ret.try_into().unwrap()
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn into_i32_internal(value: &JsVar) -> i32 {
        extern "C" {
            // Free a JavaScript object
            fn _cala_js_load_int(idx: i32) -> i32;
        }
        _cala_js_load_int(value.0)
    }

    /// Create a new `JsVar` from a Rust float
    pub fn from_f32(value: f32) -> JsVar {
        Self::from_f32_internal(value)
    }

    #[cfg(feature = "wasm-bindgen")]
    fn from_f32_internal(value: f32) -> Self {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_store_float(idx: f32) -> i32;
        }

        Self(_cala_js_store_float(value))
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    fn from_f32_internal(value: f32) -> Self {
        Self(
            js! {
                return _cala_js_store_float(@{value});
            }
            .try_into()
            .unwrap(),
        )
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    fn from_f32_internal(value: f32) -> Self {
        extern "C" {
            // Free a JavaScript object
            fn _cala_js_store_float(idx: f32) -> i32;
        }
        Self(unsafe { _cala_js_store_float(value) })
    }

    /// Get a Rust float from a `JsVar`.
    pub unsafe fn into_f32(&self) -> f32 {
        Self::into_f32_internal(self)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn into_f32_internal(value: &JsVar) -> f32 {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_load_float(idx: i32) -> f32;
        }
        _cala_js_load_float(value.0)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn into_f32_internal(value: &JsVar) -> f32 {
        let ret = js! {
            return _cala_js_load_float(@{value.0});
        };
        let ret: f64 = ret.try_into().unwrap();
        ret as _
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn into_f32_internal(value: &JsVar) -> f32 {
        extern "C" {
            // Free a JavaScript object
            fn _cala_js_load_float(idx: i32) -> f32;
        }
        _cala_js_load_float(value.0)
    }

    /// Create a new `JsVar` from a Rust float
    pub fn from_f64(value: f64) -> JsVar {
        Self::from_f64_internal(value)
    }

    #[cfg(feature = "wasm-bindgen")]
    fn from_f64_internal(value: f64) -> Self {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_store_double(idx: f64) -> i32;
        }

        Self(_cala_js_store_double(value))
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    fn from_f64_internal(value: f64) -> Self {
        Self(
            js! {
                return _cala_js_store_double(@{value});
            }
            .try_into()
            .unwrap(),
        )
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    fn from_f64_internal(value: f64) -> Self {
        extern "C" {
            // Free a JavaScript object
            fn _cala_js_store_double(idx: f64) -> i32;
        }
        Self(unsafe { _cala_js_store_double(value) })
    }

    /// Get a Rust float from a `JsVar`.
    pub unsafe fn into_f64(&self) -> f64 {
        Self::into_f64_internal(self)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn into_f64_internal(value: &JsVar) -> f64 {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_load_double(idx: i32) -> f64;
        }
        _cala_js_load_double(value.0)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn into_f64_internal(value: &JsVar) -> f64 {
        let ret = js! {
            return _cala_js_load_double(@{value.0});
        };
        ret.try_into().unwrap()
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn into_f64_internal(value: &JsVar) -> f64 {
        extern "C" {
            // Free a JavaScript object
            fn _cala_js_load_double(idx: i32) -> f64;
        }
        _cala_js_load_double(value.0)
    }

    /// Assume the variable is a string and copy into Rust `Vec`.
    pub unsafe fn read_utf16(&self, output: &mut Vec<u16>) {
        let length = self.vecstr(output, 0); // Query size
        output.reserve_exact(length as usize - output.len());
        let written = self.vecstr(output, length); // Write data
        output.set_len(written as usize);
        debug_assert_eq!(length, written);
    }

    /// Assume the variable is an array and copy into Rust `Vec`.
    pub unsafe fn read_bytes(&self, output: &mut Vec<u8>) {
        let length = self.vec8i(output, 0); // Query size
        output.reserve_exact(length as usize - output.len());
        let written = self.vec8i(output, length); // Write data
        output.set_len(written as usize);
        debug_assert_eq!(length, written);
    }

    /// Assume the variable is an array and copy into Rust `Vec`.
    pub unsafe fn read_ints(&self, output: &mut Vec<i32>) {
        let length = self.vec32i(output, 0); // Query size
        output.reserve_exact(length as usize - output.len());
        let written = self.vec32i(output, length); // Write data
        output.set_len(written as usize);
        debug_assert_eq!(length, written);
    }

    /// Assume the variable is an array and copy into Rust `Vec`.
    pub unsafe fn read_floats(&self, output: &mut Vec<f32>) {
        let length = self.vec32f(output, 0); // Query size
        output.reserve_exact(length as usize - output.len());
        let written = self.vec32f(output, length); // Write data
        output.set_len(written as usize);
        debug_assert_eq!(length, written);
    }

    /// Assume the variable is an array and copy into Rust `Vec`.
    pub unsafe fn read_doubles(&self, output: &mut Vec<f64>) {
        let length = self.vec64f(output, 0); // Query size
        output.reserve_exact(length as usize - output.len());
        let written = self.vec64f(output, length); // Write data
        output.set_len(written as usize);
        debug_assert_eq!(length, written);
    }

    /// Assume the variable is an array and copy from Rust slice.
    pub unsafe fn write_bytes(&self, input: &[u8]) {
        self.slice8i(input);
    }

    /// Assume the variable is an array and copy from Rust slice.
    pub unsafe fn write_ints(&self, input: &[i32]) {
        self.slice32i(input);
    }

    /// Assume the variable is an array and copy from Rust slice.
    pub unsafe fn write_floats(&self, input: &[f32]) {
        self.slice32f(input);
    }

    /// Assume the variable is an array and copy from Rust slice.
    pub unsafe fn write_doubles(&self, input: &[f64]) {
        self.slice64f(input);
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn vec8i(&self, output: &mut Vec<u8>, length: u32) -> u32 {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_read_bytes(j: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_bytes(self.0, output.as_mut_ptr() as u32, length)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn vec8i(&self, output: &mut Vec<u8>, length: u32) -> u32 {
        let ret = js! {
            return _cala_js_read_bytes(
                @{self.0},
                @{output.as_mut_ptr() as u32},
                @{length}
            );
        };
        ret.try_into().unwrap()
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn vec8i(&self, output: &mut Vec<u8>, length: u32) -> u32 {
        extern "C" {
            fn _cala_js_read_bytes(j: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_bytes(self.0, output.as_mut_ptr() as u32, length)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn vec32i(&self, output: &mut Vec<i32>, length: u32) -> u32 {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_read_ints(j: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_ints(self.0, output.as_mut_ptr() as u32, length)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn vec32i(&self, output: &mut Vec<i32>, length: u32) -> u32 {
        let ret = js! {
            return _cala_js_read_ints(
                @{self.0},
                @{output.as_mut_ptr() as u32},
                @{length}
            );
        };
        ret.try_into().unwrap()
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn vec32i(&self, output: &mut Vec<i32>, length: u32) -> u32 {
        extern "C" {
            fn _cala_js_read_ints(j: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_ints(self.0, output.as_mut_ptr() as u32, length)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn vec32f(&self, output: &mut Vec<f32>, length: u32) -> u32 {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_read_floats(j: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_floats(self.0, output.as_mut_ptr() as u32, length)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn vec32f(&self, output: &mut Vec<f32>, length: u32) -> u32 {
        let ret = js! {
            return _cala_js_read_floats(
                @{self.0},
                @{output.as_mut_ptr() as u32},
                @{length}
            );
        };
        ret.try_into().unwrap()
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn vec32f(&self, output: &mut Vec<f32>, length: u32) -> u32 {
        extern "C" {
            fn _cala_js_read_floats(j: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_floats(self.0, output.as_mut_ptr() as u32, length)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn vec64f(&self, output: &mut Vec<f64>, length: u32) -> u32 {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_read_doubles(j: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_doubles(self.0, output.as_mut_ptr() as u32, length)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn vec64f(&self, output: &mut Vec<f64>, length: u32) -> u32 {
        let ret = js! {
            return _cala_js_read_doubles(
                @{self.0},
                @{output.as_mut_ptr() as u32},
                @{length}
            );
        };
        ret.try_into().unwrap()
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn vec64f(&self, output: &mut Vec<f64>, length: u32) -> u32 {
        extern "C" {
            fn _cala_js_read_doubles(j: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_doubles(self.0, output.as_mut_ptr() as u32, length)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn slice8i(&self, input: &[u8]) {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_write_bytes(j: i32, p: u32, l: u32);
        }
        _cala_js_write_bytes(self.0, input.as_ptr() as u32, input.len() as u32)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn slice8i(&self, input: &[u8]) {
        js! {
            return _cala_js_write_bytes(
                @{self.0},
                @{input.as_ptr() as u32},
                @{input.len() as u32}
            );
        };
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn slice8i(&self, input: &[u8]) {
        extern "C" {
            fn _cala_js_write_bytes(j: i32, p: u32, l: u32) -> ();
        }
        _cala_js_write_bytes(self.0, input.as_ptr() as u32, input.len() as u32)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn slice32i(&self, input: &[i32]) {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_write_ints(j: i32, p: u32, l: u32);
        }
        _cala_js_write_ints(self.0, input.as_ptr() as u32, input.len() as u32)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn slice32i(&self, input: &[i32]) {
        js! {
            return _cala_js_write_ints(
                @{self.0},
                @{input.as_ptr() as u32},
                @{input.len() as u32}
            );
        };
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn slice32i(&self, input: &[i32]) {
        extern "C" {
            fn _cala_js_write_ints(j: i32, p: u32, l: u32) -> ();
        }
        _cala_js_write_ints(self.0, input.as_ptr() as u32, input.len() as u32)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn slice32f(&self, input: &[f32]) {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_write_floats(j: i32, p: u32, l: u32);
        }
        _cala_js_write_floats(self.0, input.as_ptr() as u32, input.len() as u32)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn slice32f(&self, input: &[f32]) {
        js! {
            return _cala_js_write_floats(
                @{self.0},
                @{input.as_ptr() as u32},
                @{input.len() as u32}
            );
        };
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn slice32f(&self, input: &[f32]) {
        extern "C" {
            fn _cala_js_write_floats(j: i32, p: u32, l: u32) -> ();
        }
        _cala_js_write_floats(self.0, input.as_ptr() as u32, input.len() as u32)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn slice64f(&self, input: &[f64]) {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_write_doubles(j: i32, p: u32, l: u32);
        }
        _cala_js_write_doubles(
            self.0,
            input.as_ptr() as u32,
            input.len() as u32,
        )
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn slice64f(&self, input: &[f64]) {
        js! {
            _cala_js_write_doubles(
                @{self.0},
                @{input.as_ptr() as u32},
                @{input.len() as u32}
            );
        };
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn slice64f(&self, input: &[f64]) {
        extern "C" {
            fn _cala_js_write_doubles(j: i32, p: u32, l: u32) -> ();
        }
        _cala_js_write_doubles(
            self.0,
            input.as_ptr() as u32,
            input.len() as u32,
        )
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn vecstr<T>(&self, output: &mut Vec<T>, length: u32) -> u32 {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_read_text(idx: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_text(self.0, output.as_ptr() as u32, length)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn vecstr<T>(&self, output: &mut Vec<T>, length: u32) -> u32 {
        let ret = js! {
            return _cala_js_read_text(
                @{self.0},
                @{output.as_ptr() as u32},
                @{length}
            );
        };
        ret.try_into().unwrap()
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn vecstr<T>(&self, output: &mut Vec<T>, length: u32) -> u32 {
        extern "C" {
            fn _cala_js_read_text(idx: i32, p: u32, l: u32) -> u32;
        }
        _cala_js_read_text(self.0, output.as_ptr() as u32, length)
    }

    #[cfg(feature = "wasm-bindgen")]
    unsafe fn set_waker_internal(&self) {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_waker(idx: i32);
        }
        _cala_js_waker(self.0)
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    unsafe fn set_waker_internal(&self) {
        let ret = js! { _cala_js_waker(@{self.0}); };
        ret.try_into().unwrap()
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    unsafe fn set_waker_internal(&self) {
        extern "C" {
            fn _cala_js_waker(idx: i32);
        }
        _cala_js_waker(self.0)
    }

    // Remove any state associated with ready promises on drop.
    fn drop_internal(&self) {
        READY.with(|w| w.borrow_mut().remove(&self.0));
    }
}

impl Drop for JsVar {
    #[cfg(feature = "wasm-bindgen")]
    fn drop(&mut self) {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_free(idx: i32);
        }

        self.drop_internal();
        _cala_js_free(self.0);
    }

    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    fn drop(&mut self) {
        self.drop_internal();
        js! {
            _cala_js_free(@{self.0});
        }
    }

    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    fn drop(&mut self) {
        extern "C" {
            // Free a JavaScript object
            fn _cala_js_free(idx: i32) -> ();
        }

        self.drop_internal();
        unsafe {
            _cala_js_free(self.0);
        }
    }
}

/// A JavaScript String
#[derive(Debug)]
pub struct JsString(JsVar);

impl JsString {
    /// Allocate a new javascript string from a Rust string slice.
    #[cfg(feature = "wasm-bindgen")]
    pub fn new(string: &str) -> JsString {
        #[wasm_bindgen]
        extern "C" {
            fn _cala_js_text(p: u32, l: u32) -> i32;
        }

        // around the right amount of memory
        let mut text = Vec::with_capacity(string.len());
        for c in string.encode_utf16() {
            text.push(c);
        }
        JsString(JsVar(_cala_js_text(
            text.as_ptr() as u32,
            text.len() as u32,
        )))
    }

    /// Allocate a new javascript string from a Rust string slice.
    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    pub fn new(string: &str) -> JsString {
        // around the right amount of memory
        let mut text = Vec::with_capacity(string.len());
        for c in string.encode_utf16() {
            text.push(c);
        }
        let string = js! {
            return _cala_js_text(@{text.as_ptr() as u32}, @{text.len() as u32});
        };
        JsString(JsVar(string.try_into().unwrap()))
    }

    /// Allocate a new javascript string from a Rust string slice.
    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    pub fn new(string: &str) -> JsString {
        extern "C" {
            // Turn Rust UTF-16 String Into JavaScript String.
            fn _cala_js_text(p: u32, l: u32) -> i32;
        }

        // around the right amount of memory
        let mut text = Vec::with_capacity(string.len());
        for c in string.encode_utf16() {
            text.push(c);
        }
        JsString(JsVar(unsafe {
            _cala_js_text(text.as_ptr() as u32, text.len() as u32)
        }))
    }

    /// Get a reference to this JsString as a JsVar
    pub fn as_var(&self) -> &JsVar {
        &self.0
    }
    
    /// Turn a `JsVar` into a `JsString`.  This does no type-checking, therefore
    /// is unsafe.
    pub unsafe fn from_var(var: JsVar) -> JsString {
        JsString(var)
    }
}

/// A JavaScript Function.
#[derive(Debug)]
pub struct JsFn(JsVar);

impl JsFn {
    /// Define a function (two parameters param_a: u32, and param_b: u32,
    /// returns a u32)
    #[cfg(feature = "wasm-bindgen")]
    pub unsafe fn new(string: &str) -> JsFn {
        #[wasm_bindgen]
        extern "C" {
            // Execute some JavaScript string.
            fn _cala_js_function(idx: i32) -> i32;
        }

        let javascript = format!(
            "\
            \"use strict\";\
            return function(param_a, param_b) {{ {} }};\
            ",
            string
        );

        let string = JsString::new(&javascript);
        let func = _cala_js_function(string.as_var().0);

        JsFn(JsVar(func))
    }

    /// Define a function (two parameters param_a: u32, and param_b: u32,
    /// returns a u32)
    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    pub unsafe fn new(string: &str) -> JsFn {
        let javascript = format!(
            "\
            \"use strict\";\
            return function(param_a, param_b) {{ {} }};\
        ",
            string
        );

        let string = JsString::new(&javascript);
        let func = js! {
            return _cala_js_function(@{string.as_var().0});
        };

        JsFn(JsVar(func.try_into().unwrap()))
    }

    /// Define a function (two parameters param_a: u32, and param_b: u32,
    /// returns a u32)
    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    pub unsafe fn new(string: &str) -> JsFn {
        extern "C" {
            // Execute some JavaScript string.
            fn _cala_js_function(idx: i32) -> i32;
        }

        let javascript = format!(
            "\
            \"use strict\";\
            return function(param_a, param_b) {{ {} }};\
        ",
            string
        );

        let string = JsString::new(&javascript);
        let func = _cala_js_function(string.as_var().0);

        JsFn(JsVar(func))
    }

    /// Call a JavaScript function.
    #[cfg(feature = "wasm-bindgen")]
    pub unsafe fn call(
        &self,
        a: Option<&JsVar>,
        b: Option<&JsVar>,
    ) -> Option<JsVar> {
        #[wasm_bindgen]
        extern "C" {
            // A generic javascript shim
            fn _cala_js_call(function: i32, param_a: i32, param_b: i32) -> i32;
        }
        let ret = _cala_js_call(
            (self.0).0,
            a.map(|x| x.0).unwrap_or(-1),
            b.map(|x| x.0).unwrap_or(-1),
        );
        if ret == -1 {
            None
        } else {
            Some(JsVar(ret))
        }
    }

    /// Call a JavaScript function.
    #[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
    pub unsafe fn call(
        &self,
        a: Option<&JsVar>,
        b: Option<&JsVar>,
    ) -> Option<JsVar> {
        let ret = js! {
            return _cala_js_call(@{(self.0).0},
                @{a.map(|x| x.0).unwrap_or(-1)},
                @{b.map(|x| x.0).unwrap_or(-1)});
        };
        if ret == -1 {
            None
        } else {
            Some(JsVar(ret.try_into().unwrap()))
        }
    }

    /// Call a JavaScript function.
    #[cfg(not(any(feature = "stdweb", feature = "wasm-bindgen")))]
    pub unsafe fn call(
        &self,
        a: Option<&JsVar>,
        b: Option<&JsVar>,
    ) -> Option<JsVar> {
        extern "C" {
            // A generic javascript shim
            fn _cala_js_call(function: i32, param_a: i32, param_b: i32) -> i32;
        }
        let ret = _cala_js_call(
            (self.0).0,
            a.map(|x| x.0).unwrap_or(-1),
            b.map(|x| x.0).unwrap_or(-1),
        );
        if ret == -1 {
            None
        } else {
            Some(JsVar(ret))
        }
    }
}

thread_local!(
    static FUTURE: RefCell<Option<Pin<Box<dyn Future<Output = ()>>>>> =
        RefCell::new(None);
);

/// WASM is non-blocking, but after the function returns, the Future will be
/// running on the main (and only) thread inside the JavaScript executor.
pub fn block_on<F: Future<Output = ()> + 'static>(main: F) {
    FUTURE.with(move |future| {
        *future.borrow_mut() = Some(Box::pin(async {
            panic_hook();
            main.await;
        }));
    });
    executor();
}

fn executor() {
    FUTURE.with(|future| {
        if let Some(future) = future.borrow_mut().as_mut() {
            // Create a dummy context, nothing important
            let waker = waker();
            let mut cx = Context::from_waker(&waker);
            // Whether app exits or continues, we don't care.
            let _ = future.as_mut().poll(&mut cx);
        }
    });
}

/// Create a waker for the JavaScript executor - doesn't need any associated
/// state.
#[inline]
fn waker() -> Waker {
    #[inline]
    unsafe fn clone(data: *const ()) -> RawWaker {
        RawWaker::new(data, &RawWakerVTable::new(clone, wake, wake, drop))
    }

    #[inline]
    unsafe fn wake(_data: *const ()) {
        executor();
    }

    #[inline]
    unsafe fn drop(_data: *const ()) {}

    unsafe {
        Waker::from_raw(RawWaker::new(
            std::ptr::null(),
            &RawWakerVTable::new(clone, wake, wake, drop),
        ))
    }
}

fn panic_hook_internal(panic_info: &std::panic::PanicInfo<'_>) {
    let msg = panic_info.to_string();

    let message = JsString::new(&format!("Cala App panicked!: {:?}", msg));
    let eprint = unsafe { JsFn::new("throw new Error(param_a);") };
    unsafe {
        assert!(eprint.call(Some(message.as_var()), None).is_none());
    }
}

/// Set the panic hook for nicely printed `panic!`s.
pub fn panic_hook() {
    let hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |p| {
        hook(p);
        panic_hook_internal(p);
    }));
}