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
#![feature(allow_internal_unstable,core_intrinsics,linkage,rt,macro_reexport,optin_builtin_traits,raw,specialization,unboxed_closures)]
#![allow(unused_variables)]
#![deny(missing_docs)]
#![doc(html_logo_url = "https://rust.hadean.org/logo.png", html_favicon_url = "https://rust.hadean.org/favicon.ico", html_root_url = "https://rust.hadean.org/", html_playground_url = "https://rust.hadean.org/play/", issue_tracker_base_url = "https://github.com/hadeaninc/bindings-rust/issues/")]
extern crate bincode;
#[macro_use]
extern crate lazy_static;
extern crate libc;
#[macro_use]
#[macro_reexport(parse_generics_shim,parse_constr,parse_generics_shim_util)]
extern crate aidanhs_tmp_parse_generics_shim as parse_generics_shim;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use serde::ser::SerializeTuple;
use serde::de::{self, DeserializeOwned, SeqAccess, Visitor};
use std::any::{Any, TypeId};
use std::cell::UnsafeCell;
use std::cmp;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::PhantomData;
use std::mem;
use std::net;
use std::slice;
use std::raw;
use hoff::StartFns;
#[doc(hidden)]
pub mod hoff;
pub const DEFAULT_BUF_LEN: usize = 16384;
fn dv_round_up_to_nearest(lhs: u64, rhs: u64) -> u64 {
((lhs + rhs - 1) / rhs) * rhs
}
fn get_u32(b: &[u8], offset: u64) -> u32 {
let b = &b[offset as usize..];
unsafe { mem::transmute([b[0], b[1], b[2], b[3]]) }
}
fn get_u64(b: &[u8], offset: u64) -> u64 {
let b = &b[offset as usize..];
unsafe { mem::transmute([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) }
}
fn set_u64(b: &mut [u8], offset: u64, v: u64) {
let b = &mut b[offset as usize..];
b[..8].clone_from_slice(&unsafe { mem::transmute::<_, [u8; 8]>(v) })
}
fn copy_slice(dst: &mut [u8], src: &[u8], len: u64) {
dst[..len as usize].clone_from_slice(&src[..len as usize])
}
pub trait ProcessTransfer: ProcessSend + ProcessReceive + 'static {}
pub trait ProcessSend: Serialize + 'static {
fn processsendable_write<W: Write>(&self, writer: &mut W);
}
pub trait ProcessReceive: DeserializeOwned + 'static {
fn processsendable_read<R: Read>(reader: &mut R) -> Self;
}
impl<T: Serialize + 'static> ProcessSend for T {
fn processsendable_write<W: Write>(&self, writer: &mut W) {
bincode::serialize_into(writer, self, bincode::Infinite).expect("ProcessSend serialize failed");
writer.flush().expect("ProcessSend serialize flush failed")
}
}
impl<T: DeserializeOwned + 'static> ProcessReceive for T {
fn processsendable_read<R: Read>(reader: &mut R) -> Self {
bincode::deserialize_from(reader, bincode::Infinite).expect("ProcessReceive deserialize failed")
}
}
impl<I, O> Serialize for Box<FnSerialize<I, Output=O>> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
let deets = self.detail();
let data: &[u8] = unsafe { slice::from_raw_parts(deets.data_ptr, deets.size as usize) };
let mut ts = serializer.serialize_tuple(3)?;
ts.serialize_element::<u64>(&deets.size)?;
ts.serialize_element::<u64>(&deets.vtable_ptr)?;
ts.serialize_element::<[u8]>(data)?;
ts.end()
}
}
impl<'de, I, O> Deserialize<'de> for Box<FnSerialize<I, Output=O>> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
struct FnSerializeVisitor;
use std::fmt;
impl<'de> Visitor<'de> for FnSerializeVisitor {
type Value = (u64, u64, Vec<u8>);
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a FnSerializeTuple")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de> {
macro_rules! tupget {
($t:ty, $n:expr) => {
match seq.next_element::<$t>()? {
Some(value) => value,
None => return Err(de::Error::invalid_length($n, &self)),
};
};
}
let size = tupget!(u64, 1);
let vtable_ptr = tupget!(u64, 2);
let data = tupget!(Vec<u8>, 3);
Ok((size, vtable_ptr, data))
}
}
let (size, vtable_ptr, data) = deserializer.deserialize_tuple(3, FnSerializeVisitor)?;
let data = data.into_boxed_slice();
let data_ptr = data.as_ptr();
mem::forget(data);
let tobj = raw::TraitObject { data: data_ptr as *mut (), vtable: vtable_ptr as *mut () };
let tobj = unsafe { mem::transmute::<raw::TraitObject, Box<FnSerialize<I, Output=O>>>(tobj) };
Ok(tobj)
}
}
impl<I, O> Clone for Box<FnSerialize<I, Output=O>> {
fn clone(&self) -> Self {
let serialized = bincode::serialize(self, bincode::Infinite).expect("Failed to serialize during clone.");
bincode::deserialize(serialized.as_slice()).expect("Failed to deserialize during clone.")
}
}
impl<T: ProcessSend + ProcessReceive> ProcessTransfer for T {}
pub trait FnSerialize<T>: Fn<T> {
#[doc(hidden)]
fn detail(&self) -> FnSerializeDetail;
}
#[doc(hidden)]
pub struct FnSerializeDetail {
pub size: u64,
pub vtable_ptr: u64,
pub data_ptr: *const u8
}
#[macro_export]
#[allow_internal_unstable]
macro_rules! closure {
(__closureargstotuple, $( $closure:tt )*) => { closure!(__closureargstotuple_in, (), $( $closure )*) };
(__closureargstotuple_in, ($( $any:tt )*), || $( $closure:tt )*) => { ($( $any )*) };
(__closureargstotuple_in, ($( $any:tt )*), |$x1:ident: $t1:ty| $( $closure:tt )*) => { closure!(__closureargstotuple_in, ($( $any )* $t1,), || $( $closure )*) };
(__closureargstotuple_in, ($( $any:tt )*), |$x1:ident: $t1:ty, $( $xn:ident: $tn:ty ),*| $( $closure:tt )*) => { closure!(__closureargstotuple_in, ($( $any )* $t1,), |$( $xn:$tn ),*| $( $closure )*) };
(__genericboundstotypes_in, ([$( $gtb:tt )*], [$( $x:ident: $t:ty, )*], $( $closure:tt )*), { constr: [$( $dc1:tt )*], params: [$( $dc2:tt )*], ltimes: [$( $dc3:tt )*], tnames: [$( $gt:ident, )*], },) => {
closure!(_xx, [$( $gt, )*], [$( $gtb )*], [$( $x: $t, )*], $( $closure )*)
};
([$( $gtb:tt )*], [$( $x:ident: $t:ty ),*], $( $closure:tt )*) => {{
parse_generics_shim!{ { constr, params, ltimes, tnames }, then closure!(__genericboundstotypes_in, ([$( $gtb )*], [$( $x: $t, )*], $( $closure )*), ), <$( $gtb )*> }
}};
([$( $x:ident: $t:ty ),*], $( $closure:tt )*) => {{
closure!(_xx, [], [], [$( $x: $t, )*], $( $closure )*)
}};
(_xx, [$( $gt:ident, )*], [$( $gtb:tt )*], [$( $x:ident: $t:ty, )*], $( $closure:tt )*) => {{
#[allow(unused)]
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use std::mem;
#[allow(unused)]
use std::ptr;
use std::raw;
use $crate::{FnSerialize, FnSerializeDetail};
struct __TmpStruct<I, O, $( $gtb )*> {
$( $x: UnsafeCell<$t>, )*
_please_dont_use_this_name: PhantomData<(I, O, $( $gt, )*)>,
}
impl<I, O, $( $gtb )*> FnSerialize<I> for __TmpStruct<I, O, $( $gt, )*> {
fn detail(&self) -> FnSerializeDetail {
let tobj = self as &FnSerialize<I, Output=O>;
let tobj = unsafe { mem::transmute::<_, raw::TraitObject>(tobj) };
FnSerializeDetail {
size: mem::size_of_val(self) as u64,
vtable_ptr: tobj.vtable as u64,
data_ptr: tobj.data as *const u8,
}
}
}
impl<I, O, $( $gtb )*> FnOnce<I> for __TmpStruct<I, O, $( $gt, )*> {
type Output = O;
extern "rust-call" fn call_once(self, args: I) -> Self::Output {
{self}.call_mut(args)
}
}
impl<I, O, $( $gtb )*> FnMut<I> for __TmpStruct<I, O, $( $gt, )*> {
extern "rust-call" fn call_mut(&mut self, args: I) -> Self::Output {
self.call(args)
}
}
impl<I, O, $( $gtb )*> Fn<I> for __TmpStruct<I, O, $( $gt, )*> {
extern "rust-call" fn call(&self, args: I) -> Self::Output {
$(
let $x: $t = unsafe { ptr::read(self.$x.get()) };
)*
let ret = {
let c = $( $closure )*;
unsafe { mem::transmute::<_, &Fn<I, Output=O>>(&c as &Fn<_, Output=_>) }.call(args)
};
$(
unsafe { ptr::write(self.$x.get(), $x) }
)*
ret
}
}
{
fn typeck_transfer<T: $crate::ProcessTransfer>() {}
$(
typeck_transfer::<$t>();
)*
$(
typeck_transfer::<$gt>();
)*
}
let pd = {
$(
let $x: $t = unsafe { mem::uninitialized() };
)*
let c = $( $closure )*;
let f = &c as &Fn<closure!(__closureargstotuple, $( $closure )*), Output=_>;
fn choose_pd_t<I, O>(_: &Fn<I, Output=O>) -> PhantomData<(I, O)> { PhantomData }
choose_pd_t(f)
};
fn choose_t<I: 'static, O: 'static, $( $gtb )*>(_: PhantomData<(I, O)>, $( $x:$t, )*) -> Box<FnSerialize<I, Output=O>> {
let ts: __TmpStruct<I, O, $( $gt, )*> = __TmpStruct { $( $x: UnsafeCell::new($x), )* _please_dont_use_this_name: PhantomData };
Box::new(ts) as Box<FnSerialize<I, Output=O>>
}
choose_t::<_, _, $( $gt, )*>(pd, $( $x ),*)
}};
}
fn _typeck_closure() {
let x: usize = 5;
let y = 3;
#[derive(Serialize, Deserialize)]
struct NonCopy { val: u8 }
let nc = NonCopy { val: 5 };
let s = closure!([], || ()); s(); s();
let s = closure!([x: usize, y: u8], || { x + y as usize }); s(); s();
let s = closure!([x: usize, y: u8], || -> usize { x + y as usize }); s(); s();
let s = closure!([x: usize, y: u8], || {}); s(); s();
let s = closure!([x: usize, y: u8], || ()); s(); s();
let s = closure!([x: usize], |y: u8| (x + y as usize)); s(y); s(y);
let s = closure!([x: usize, y: u8], |x: u8| (x + 1)); s(3); s(3);
let s = closure!([x: usize, y: u8], |_x: u8| ()); s(3); s(3);
let s = closure!([x: usize, y: u8], |x: usize, y: u8| x + y as usize); s(3, 1); s(3, 1);
let s = closure!([x: usize, y: u8], |_x: u8, _y: u8| ()); s(3, 1); s(3, 1);
let s = closure!([nc: NonCopy], |x: u8| x + nc.val); s(1); s(1);
fn foo<T: ProcessTransfer>(x: T, y: T) {
let s = closure!([T: 'static], [], |t: T| t); s(x); s(y);
}
fn foo2<T: ProcessTransfer + Clone>(x: T, y: T) {
let s = closure!([T: Clone + 'static], [x: T], |y: T| (x.clone(), y)); s(y.clone()); s(y.clone());
}
fn foo3<T1: ProcessTransfer + Clone, T2: ProcessTransfer + Clone>(x: T1, y: T2) {
let s = closure!([T1: Clone + 'static, T2: Clone + 'static], [x: T1, y: T2], |z: usize| (x.clone(), y.clone(), z)); s(5); s(5);
}
}
fn raw_parts(len: usize) -> (*mut u8, usize, usize) {
let mut retvec: Vec<u8> = Vec::with_capacity(len); unsafe{retvec.set_len(len)};
let ret = (retvec.as_mut_ptr(), retvec.len(), retvec.capacity());
mem::forget(retvec);
ret
}
const RECEIVER_BUF_SIZE: usize = 1024;
struct ReceiverInner(*mut libc::c_void, Box<[u8; RECEIVER_BUF_SIZE]>, usize);
impl fmt::Debug for ReceiverInner {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ReceiverInner({:?}, ...buffer..., {:?})", self.0, self.2)
}
}
impl ReceiverInner {
pub fn available(&self) -> usize { unsafe { link::HReceiveAvailable(self.0) + self.2 } }
}
impl Read for ReceiverInner {
fn read(&mut self, outbuf: &mut [u8]) -> io::Result<usize> {
if self.2 == 0 {
let tobuffer = cmp::min(self.available(), RECEIVER_BUF_SIZE);
let tobuffer = cmp::max(tobuffer, 1);
let bufptr = unsafe { self.1.as_mut_ptr().offset((RECEIVER_BUF_SIZE-tobuffer) as isize) };
unsafe { link::HReceive(self.0, bufptr as *mut libc::c_void, tobuffer) };
self.2 = tobuffer;
}
let tocopy = cmp::min(self.2, outbuf.len());
outbuf[..tocopy].copy_from_slice(&self.1[RECEIVER_BUF_SIZE-self.2..RECEIVER_BUF_SIZE-self.2+tocopy]);
self.2 -= tocopy;
Ok(tocopy)
}
}
const SENDER_BUF_SIZE: usize = 1024;
struct SenderInner(*mut libc::c_void, Box<[u8; SENDER_BUF_SIZE]>, usize);
impl SenderInner {
pub fn available(&self) -> usize { unsafe { link::HSendAvailable(self.0) } }
}
impl fmt::Debug for SenderInner {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SenderInner({:?}, ...buffer..., {:?})", self.0, self.2)
}
}
impl Write for SenderInner {
fn write(&mut self, inbuf: &[u8]) -> io::Result<usize> {
let mut ofs = 0;
loop {
let tocopy = cmp::min(SENDER_BUF_SIZE-self.2, inbuf.len()-ofs);
self.1[self.2..self.2+tocopy].copy_from_slice(&inbuf[ofs..ofs+tocopy]);
self.2 += tocopy;
ofs += tocopy;
if ofs == inbuf.len() { break }
unsafe { link::HSend(self.0, self.1.as_ptr() as *const libc::c_void, self.2) };
self.2 = 0
}
Ok(inbuf.len())
}
fn flush(&mut self) -> io::Result<()> {
unsafe { link::HSend(self.0, self.1.as_ptr() as *const libc::c_void, self.2) };
self.2 = 0;
Ok(())
}
}
#[derive(Debug)]
pub struct Receiver<T: ProcessReceive>(UnsafeCell<ReceiverInner>, *mut u8, usize, usize, PhantomData<T>);
impl<T: ProcessReceive> Receiver<T> {
pub fn recv(&self) -> T { T::processsendable_read(unsafe { &mut *self.0.get() }) }
}
impl<T: ProcessReceive> Drop for Receiver<T> {
fn drop(&mut self) {
}
}
#[derive(Debug)]
pub struct Sender<T: ProcessSend>(UnsafeCell<SenderInner>, *mut u8, usize, usize, PhantomData<T>);
impl<T: ProcessSend> Sender<T> {
pub fn send(&self, src: &T) { src.processsendable_write(unsafe { &mut *self.0.get() }) }
}
impl<T: ProcessSend> Drop for Sender<T> {
fn drop(&mut self) {
}
}
pub struct Connection(*mut u8, usize, usize);
#[derive(Debug)]
pub struct RawReceiver(Option<TypeId>, Receiver<()>);
impl RawReceiver {
pub fn open() -> Self { Self::with_len(DEFAULT_BUF_LEN) }
pub fn with_len(len: usize) -> Self { Self::with_len_and_ty(len, None) }
fn open_with_ty(ty: TypeId) -> Self { Self::with_len_and_ty(DEFAULT_BUF_LEN, Some(ty)) }
fn with_len_and_ty(len: usize, maybety: Option<TypeId>) -> Self {
assert!(len > 0);
let (bufptr, buflen, bufcap) = raw_parts(len); assert!(buflen == len);
let receiver = ReceiverInner(unsafe { link::HOpenReceiver(bufptr as *mut _, buflen) }, unsafe { Box::new(mem::uninitialized()) }, 0);
RawReceiver(maybety, Receiver(UnsafeCell::new(receiver), bufptr, buflen, bufcap, PhantomData))
}
pub fn downcast<T: ProcessTransfer>(self) -> Receiver<T> {
if TypeId::of::<T>() == self.0.expect("Type of Receiver not known") {
self.unchecked_downcast()
} else {
panic!("Receiver could not be converted to type")
}
}
pub fn unchecked_downcast<T: ProcessReceive>(self) -> Receiver<T> {
unsafe { mem::transmute::<Receiver<_>, Receiver<_>>(self.1) }
}
pub fn recv<T: ProcessReceive>(&self) -> T {
unsafe { mem::transmute::<&Receiver<_>, &Receiver<T>>(&self.1) }.recv()
}
pub fn recv_bytes(&self, bs: &mut [u8]) {
let mut ofs = 0;
while ofs != bs.len() {
let result = unsafe { (*(self.1).0.get()).read(&mut bs[ofs..]) }.unwrap();
ofs += result;
}
}
pub fn available(&self) -> usize {
unsafe { (*(self.1).0.get()).available() }
}
}
#[derive(Debug)]
pub struct RawSender(Option<TypeId>, Sender<()>);
impl RawSender {
pub fn open() -> Self { Self::with_len(DEFAULT_BUF_LEN) }
pub fn with_len(len: usize) -> Self { Self::with_len_and_ty(len, None) }
fn open_with_ty(ty: TypeId) -> Self { Self::with_len_and_ty(DEFAULT_BUF_LEN, Some(ty)) }
fn with_len_and_ty(len: usize, maybety: Option<TypeId>) -> Self {
assert!(len > 0);
let (bufptr, buflen, bufcap) = raw_parts(len); assert!(buflen == len);
let sender = SenderInner(unsafe { link::HOpenSender(bufptr as *mut _, buflen) }, unsafe { Box::new(mem::uninitialized()) }, 0);
RawSender(maybety, Sender(UnsafeCell::new(sender), bufptr, buflen, bufcap, PhantomData))
}
pub fn downcast<T: ProcessTransfer>(self) -> Sender<T> {
if TypeId::of::<T>() == self.0.expect("Type of Sender not known") {
self.unchecked_downcast()
} else {
panic!("Sender could not be converted to type")
}
}
pub fn unchecked_downcast<T: ProcessSend>(self) -> Sender<T> {
unsafe { mem::transmute::<Sender<_>, Sender<_>>(self.1) }
}
pub fn send<T: ProcessSend>(&self, src: &T) {
unsafe { mem::transmute::<&Sender<_>, &Sender<T>>(&self.1) }.send(src)
}
pub fn send_bytes(&self, bs: &[u8]) {
unsafe { (*(self.1).0.get()).write(bs) }.unwrap();
unsafe { (*(self.1).0.get()).flush() }.unwrap()
}
pub fn available(&self) -> usize {
unsafe { (*(self.1).0.get()).available() }
}
}
#[derive(Clone, Copy)]
struct MyTypeId(TypeId);
impl Serialize for MyTypeId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
serializer.serialize_u64(unsafe { mem::transmute::<TypeId, u64>(self.0) })
}
}
impl<'de> Deserialize<'de> for MyTypeId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
struct TypeIdVisitor;
impl<'de> Visitor<'de> for TypeIdVisitor {
type Value = MyTypeId;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a TypeId")
}
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> where E: de::Error {
Ok(MyTypeId(unsafe { mem::transmute::<u64, TypeId>(value) }))
}
}
deserializer.deserialize_u64(TypeIdVisitor)
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
#[derive(Serialize, Deserialize)]
#[repr(u8)]
enum OpenChannel {
None,
Send(MyTypeId),
Receive(MyTypeId),
Connection,
}
fn open_channels(channel_opens: &[OpenChannel]) -> (Vec<RawSender>, Vec<RawReceiver>, Vec<Connection>) {
let mut senders = vec![];
let mut receivers = vec![];
let connections = vec![];
for chan in channel_opens {
match *chan {
OpenChannel::None => panic!(),
OpenChannel::Send(ty) => senders.push(RawSender::open_with_ty(ty.0)),
OpenChannel::Receive(ty) => receivers.push(RawReceiver::open_with_ty(ty.0)),
OpenChannel::Connection => unimplemented!(),
}
}
(senders, receivers, connections)
}
pub struct Process {
start_fns: StartFns,
process_data: Box<ProcessData>,
}
trait ProcessData {
fn get_data(&self) -> Vec<u8>;
fn add_channel_open(&mut self, c: OpenChannel);
}
#[derive(Serialize, Deserialize)]
struct ProcessStartData<T> {
start_arg: T,
channel_opens_end: usize,
channel_opens: [OpenChannel; 32],
}
impl<T: ProcessTransfer> ProcessData for ProcessStartData<T> {
fn get_data(&self) -> Vec<u8> {
let mut ret = vec![0; 8];
bincode::serialize_into(&mut ret, &self, bincode::Infinite).unwrap();
let datalen = ret.len() as u64 - 8;
set_u64(&mut ret, 0, datalen);
ret
}
fn add_channel_open(&mut self, c: OpenChannel) {
self.channel_opens[self.channel_opens_end] = c;
self.channel_opens_end += 1
}
}
#[macro_export]
macro_rules! mkprocess {
($main:expr, $arg:expr) => {{
let arg = $arg;
fn typeck<T: $crate::ProcessTransfer>(_: fn(&T, Vec<$crate::RawSender>, Vec<$crate::RawReceiver>, Vec<$crate::Connection>), _: &T) {}
typeck($main, &arg);
let start_fns = $crate::hoff::get_start_fns($main);
$crate::Process::new(start_fns, arg)
}};
}
impl Process {
#[doc(hidden)]
pub fn new<T: ProcessTransfer>(start_fns: StartFns, arg: T) -> Process {
let process_data = Box::new(ProcessStartData {
start_arg: arg,
channel_opens_end: 0,
channel_opens: [OpenChannel::None; 32],
});
let process_data: Box<ProcessData> = process_data;
Process { start_fns, process_data }
}
fn into_haprocess_and_box(self) -> (link::Process, Box<Any>) {
if unsafe { link::__hadean_platform == 0 } {
let arg = self.process_data.get_data();
let hoff = hoff::mkhoff(self.start_fns, &arg);
let process = link::Process {
hoff: hoff.as_ptr() as *const libc::c_void,
hoff_len: hoff.len() as u64,
};
(process, Box::new(hoff))
} else {
let mut arg = vec![0; 16];
set_u64(&mut arg, 0, self.start_fns.user_main as *const () as u64);
set_u64(&mut arg, 8, self.start_fns.lib_main as *const () as u64);
arg.extend(self.process_data.get_data());
let shlp = Box::new(link::__secret_hadean_local_process {
secmain: hoff::hadean_local_rust_shim_main as *const _,
secarg: arg.as_ptr(),
secarglen: arg.len() as u64,
});
let shlp_ptr = &*shlp as *const _ as *const _;
let process = link::Process {
hoff: shlp_ptr,
hoff_len: 0,
};
(process, Box::new((shlp, arg)))
}
}
}
#[derive(Clone, Debug)]
pub enum ChannelEndpoint {
Sibling(usize),
Pid(Pid),
#[doc(hidden)]
Tcp(net::SocketAddrV4),
}
impl ChannelEndpoint {
fn to_hachanneltype(&self) -> link::Endpoint {
fn into_union(from: &[u8]) -> [u8; 8] {
let mut b = [0u8; 8];
b[..from.len()].copy_from_slice(from);
b
}
match *self {
ChannelEndpoint::Sibling(n) => link::Endpoint {typ:link::EndpointType::Job as u8, dat:into_union(&unsafe {mem::transmute::<u64,[u8;8]>(n as u64)})},
ChannelEndpoint::Pid(Pid(n)) => link::Endpoint {typ:link::EndpointType::Pid as u8, dat:into_union(&unsafe {mem::transmute::<u64,[u8;8]>(n as u64)})},
ChannelEndpoint::Tcp(addr) => link::Endpoint {typ:link::EndpointType::TCP as u8, dat:into_union(&unsafe {mem::transmute::<link::TcpEndpoint,[u8;6]>(link::TcpEndpoint{port:addr.port(), addr:mem::transmute(addr.ip().octets())})})},
}
}
}
#[derive(Clone, Debug)]
pub struct Channel {
src: ChannelEndpoint,
dst: ChannelEndpoint,
ty: TypeId,
}
impl Channel {
pub fn new<T: ProcessTransfer>(src: ChannelEndpoint, dst: ChannelEndpoint) -> Channel {
Channel { src:src, dst:dst, ty: TypeId::of::<T>() }
}
fn to_hachannel(&self) -> link::Channel {
link::Channel {
src: self.src.to_hachanneltype(),
dst: self.dst.to_hachanneltype(),
}
}
}
pub fn spawn(mut processes: Vec<Process>, channels: Vec<Channel>) -> (Vec<RawSender>, Vec<RawReceiver>) {
let mut hachannels = vec![];
let mut my_channels = vec![];
for channel in channels.into_iter() {
let ty = MyTypeId(channel.ty);
for &(c, t) in &[(&channel.src, OpenChannel::Send(ty)), (&channel.dst, OpenChannel::Receive(ty))] {
match *c {
ChannelEndpoint::Sibling(n) => processes[n].process_data.add_channel_open(t),
ChannelEndpoint::Pid(p) if p == pid() => my_channels.push(t),
ChannelEndpoint::Pid(_) => unimplemented!(),
ChannelEndpoint::Tcp(_) => unimplemented!(),
}
}
let hachan = channel.to_hachannel();
hachannels.push(hachan)
}
let mut haprocesses = vec![];
let mut haprocess_datas = vec![];
for (haprocess, data) in processes.into_iter().map(Process::into_haprocess_and_box) {
haprocesses.push(haprocess);
haprocess_datas.push(data);
}
let mut ps = link::ProcessSet {
n_processes: haprocesses.len(),
processes: haprocesses.as_mut_ptr(),
n_channels: hachannels.len(),
channels: hachannels.as_mut_ptr(),
};
unsafe { link::HSpawn(&mut ps as *mut _) };
let (senders, receivers, _) = open_channels(&my_channels);
(senders, receivers)
}
#[derive(Clone,Copy,PartialEq,Eq,Hash,Debug)]
pub struct Pid(u64);
pub fn pid() -> Pid { *MYPID }
lazy_static! {
static ref MYPID: Pid = Pid(unsafe { link::HGetPid() });
}
pub fn sleep(duration: std::time::Duration) {
let nanoseconds = duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64;
unsafe { link::hadean_sleep(nanoseconds) }
}
mod link {
use libc;
#[repr(C, packed)]
pub struct __secret_hadean_local_process {
pub secmain: *const libc::c_void,
pub secarg: *const libc::uint8_t,
pub secarglen: libc::uint64_t,
}
#[repr(C, packed)]
pub struct Process {
pub hoff: *const libc::c_void,
pub hoff_len: libc::uint64_t,
}
#[repr(u8)]
pub enum EndpointType {
Job = 0,
Pid = 1,
TCP = 2,
}
#[repr(C, packed)]
pub struct TcpEndpoint {
pub port: u16,
pub addr: u32
}
#[repr(C, packed)]
pub struct Endpoint {
pub typ: u8,
pub dat: [u8; 8]
}
#[repr(C, packed)]
pub struct Channel {
pub src: Endpoint,
pub dst: Endpoint,
}
#[repr(C, packed)]
pub struct ProcessSet {
pub n_processes: libc::size_t,
pub processes: *mut Process,
pub n_channels: libc::size_t,
pub channels: *mut Channel,
}
extern {
pub static __hadean_host: usize;
pub static __hadean_platform: usize;
pub fn HOpenSender(buf: *mut libc::c_void, len: libc::size_t) -> *mut libc::c_void;
pub fn HOpenReceiver(buf: *mut libc::c_void, len: libc::size_t) -> *mut libc::c_void;
pub fn HSend(sender: *mut libc::c_void, buf: *const libc::c_void, len: libc::size_t);
pub fn HReceive(receiver: *mut libc::c_void, buf: *mut libc::c_void, len: libc::size_t);
pub fn HSendAvailable(sender: *const libc::c_void) -> libc::size_t;
pub fn HReceiveAvailable(receiver: *const libc::c_void) -> libc::size_t;
pub fn HSpawn(processSet: *const ProcessSet);
pub fn HGetPid() -> libc::uint64_t;
pub fn hadean_sleep(nanoseconds: libc::uint64_t);
}
}