forked from zeromq/clrzmq4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZFrame.cs
920 lines (767 loc) · 16.8 KB
/
ZFrame.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using ZeroMQ.lib;
namespace ZeroMQ
{
/// <summary>
/// A single part message, sent or received via a <see cref="ZSocket"/>.
/// </summary>
public sealed class ZFrame : Stream, ICloneable
{
public static ZFrame FromStream(Stream stream, long i, int l)
{
stream.Position = i;
if (l == 0) return new ZFrame();
var frame = ZFrame.Create(l);
var buf = new byte[65535];
int bufLen, remaining, current = -1;
do {
++current;
remaining = Math.Min(Math.Max(0, l - current * buf.Length), buf.Length);
if (remaining < 1) break;
bufLen = stream.Read(buf, 0, remaining);
frame.Write(buf, 0, bufLen);
} while (bufLen > 0);
frame.Position = 0;
return frame;
}
public static ZFrame CopyFrom(ZFrame frame)
{
return frame.Duplicate();
}
public static ZFrame Create(int size)
{
if (size < 0)
{
throw new ArgumentOutOfRangeException("size");
}
return new ZFrame(CreateNative(size), size);
}
public static ZFrame CreateEmpty()
{
return new ZFrame(CreateEmptyNative(), -1);
}
public const int DefaultFrameSize = 4096;
public static readonly int MinimumFrameSize = zmq.sizeof_zmq_msg_t;
private DispoIntPtr framePtr;
private int length;
private int position;
// private ZeroMQ.lib.FreeMessageDelegate _freePtr;
public ZFrame(byte[] buffer)
: this (CreateNative(buffer.Length), buffer.Length)
{
this.Write(buffer, 0, buffer.Length);
}
public ZFrame(byte[] buffer, int offset, int count)
: this(CreateNative(count), count)
{
this.Write(buffer, offset, count);
}
public ZFrame(byte value)
: this(CreateNative(1), 1)
{
this.Write(value);
}
public ZFrame(Int16 value)
: this(CreateNative(2), 2)
{
this.Write(value);
}
public ZFrame(UInt16 value)
: this(CreateNative(2), 2)
{
this.Write(value);
}
public ZFrame(Char value)
: this(CreateNative(2), 2)
{
this.Write(value);
}
public ZFrame(Int32 value)
: this(CreateNative(4), 4)
{
this.Write(value);
}
public ZFrame(UInt32 value)
: this(CreateNative(4), 4)
{
this.Write(value);
}
public ZFrame(Int64 value)
: this(CreateNative(8), 8)
{
this.Write(value);
}
public ZFrame(UInt64 value)
: this(CreateNative(8), 8)
{
this.Write(value);
}
public ZFrame(string str)
: this(str, ZContext.Encoding)
{ }
public ZFrame(string str, Encoding encoding)
{
WriteStringNative(str, encoding, true);
}
public ZFrame()
: this(CreateNative(0), 0)
{ }
/* protected ZFrame(IntPtr data, int size)
: this(Alloc(data, size), size)
{ } */
internal ZFrame(DispoIntPtr frameIntPtr, int size)
: base()
{
framePtr = frameIntPtr;
length = size;
position = 0;
}
~ZFrame()
{
Dispose(false);
}
internal static DispoIntPtr CreateEmptyNative()
{
var msg = DispoIntPtr.Alloc(zmq.sizeof_zmq_msg_t);
ZError error;
while (-1 == zmq.msg_init(msg))
{
error = ZError.GetLastErr();
if (error == ZError.EINTR)
{
error = default(ZError);
continue;
}
msg.Dispose();
throw new ZException(error, "zmq_msg_init");
}
return msg;
}
internal static DispoIntPtr CreateNative(int size)
{
var msg = DispoIntPtr.Alloc(zmq.sizeof_zmq_msg_t);
ZError error;
while (-1 == zmq.msg_init_size(msg, size))
{
error = ZError.GetLastErr();
if (error == ZError.EINTR)
{
error = default(ZError);
continue;
}
msg.Dispose();
if (error == ZError.ENOMEM)
{
throw new OutOfMemoryException("zmq_msg_init_size");
}
throw new ZException(error, "zmq_msg_init_size");
}
return msg;
}
/* internal static DispoIntPtr Alloc(IntPtr data, int size)
{
var msg = DispoIntPtr.Alloc(zmq.sizeof_zmq_msg_t);
ZError error;
while (-1 == zmq.msg_init_data(msg, data, size, /* msg_free_delegate null, /* hint IntPtr.Zero)) {
error = ZError.GetLastError();
if (error == ZError.EINTR) {
continue;
}
msg.Dispose();
if (error == ZError.ENOMEM) {
throw new OutOfMemoryException ("zmq_msg_init_size");
}
throw new ZException (error, "zmq_msg_init_size");
}
return msg;
} */
protected override void Dispose(bool disposing)
{
if (framePtr != null)
{
if (framePtr.Ptr != IntPtr.Zero)
{
Close();
}
}
GC.SuppressFinalize(this);
base.Dispose(disposing);
}
public void Dismiss()
{
if (framePtr != null)
{
framePtr.Dispose();
framePtr = null;
}
GC.SuppressFinalize(this);
}
public bool IsDismissed
{
get { return framePtr == null; }
}
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanTimeout { get { return false; } }
public override bool CanWrite { get { return true; } }
private void EnsureCapacity()
{
if (framePtr != IntPtr.Zero)
{
length = zmq.msg_size(framePtr);
}
else
{
length = -1;
}
}
public override long Length
{
get
{
EnsureCapacity();
return length;
}
}
public override void SetLength(long length)
{
throw new NotSupportedException();
}
public override long Position
{
get { return position; }
set
{
Seek(value, SeekOrigin.Begin);
}
}
public IntPtr Ptr { get { return framePtr; } }
public IntPtr DataPtr()
{
if (framePtr == IntPtr.Zero)
{
return IntPtr.Zero;
}
return zmq.msg_data(framePtr);
}
public override long Seek(long offset, SeekOrigin origin)
{
long pos;
if (origin == SeekOrigin.Current)
pos = position + offset;
else if (origin == SeekOrigin.End)
pos = Length + offset;
else // if (origin == SeekOrigin.Begin)
pos = offset;
if (pos < 0 || pos > Length)
throw new ArgumentOutOfRangeException("offset");
position = (int)pos;
return pos;
}
public byte[] Read()
{
int remaining = Math.Max(0, (int)(Length - position));
return Read(remaining);
}
public byte[] Read(int count)
{
int remaining = Math.Min(count, Math.Max(0, (int)(Length - position)));
if (remaining == 0) {
return new byte[0];
}
if (remaining < 0)
{
return null;
}
var bytes = new byte[remaining];
/* int bytesLength = */ Read(bytes, 0, remaining);
return bytes;
}
public override int Read(byte[] buffer, int offset, int count)
{
int remaining = Math.Min(count, Math.Max(0, (int)(Length - position)));
if (remaining == 0) {
return 0;
}
if (remaining < 0)
{
return -1;
}
Marshal.Copy(DataPtr() + position, buffer, offset, (int)remaining);
position += remaining;
return remaining;
}
public override int ReadByte()
{
if (position + 1 > Length)
return -1;
int byt = Marshal.ReadByte(DataPtr() + (int)position);
++position;
return byt;
}
public byte ReadAsByte()
{
if (position + 1 > Length)
return default(byte);
byte byt = Marshal.ReadByte(DataPtr() + position);
++position;
return byt;
}
public Int16 ReadInt16()
{
var bytes = new byte[2];
int len = Read(bytes, 0, 2);
if (len < 2)
{
return default(Int16);
}
return BitConverter.ToInt16(bytes, 0);
}
public UInt16 ReadUInt16()
{
var bytes = new byte[2];
int len = Read(bytes, 0, 2);
if (len < 2)
{
return default(UInt16);
}
return BitConverter.ToUInt16(bytes, 0);
}
public Char ReadChar()
{
var bytes = new byte[2];
int len = Read(bytes, 0, 2);
if (len < 2)
{
return default(Char);
}
return BitConverter.ToChar(bytes, 0);
}
public Int32 ReadInt32()
{
var bytes = new byte[4];
int len = Read(bytes, 0, 4);
if (len < 4)
{
return default(Int32);
}
return BitConverter.ToInt32(bytes, 0);
}
public UInt32 ReadUInt32()
{
var bytes = new byte[4];
int len = Read(bytes, 0, 4);
if (len < 4)
{
return default(UInt32);
}
return BitConverter.ToUInt32(bytes, 0);
}
public Int64 ReadInt64()
{
var bytes = new byte[8];
int len = Read(bytes, 0, 8);
if (len < 8)
{
return default(Int64);
}
return BitConverter.ToInt64(bytes, 0);
}
public UInt64 ReadUInt64()
{
var bytes = new byte[8];
int len = Read(bytes, 0, 8);
if (len < 8)
{
return default(UInt64);
}
return BitConverter.ToUInt64(bytes, 0);
}
public string ReadString()
{
return ReadString(ZContext.Encoding);
}
public string ReadString(Encoding encoding)
{
return ReadString( /* byteCount */ (int)Length - position, encoding);
}
public string ReadString(int length)
{
return ReadString(/* byteCount */ length, ZContext.Encoding);
}
public string ReadString(int byteCount, Encoding encoding)
{
int remaining = Math.Min(byteCount, Math.Max(0, (int)Length - position));
if (remaining == 0)
{
return string.Empty;
}
if (remaining < 0)
{
return null;
}
unsafe
{
var bytes = (byte*)(this.DataPtr() + position);
Decoder dec = encoding.GetDecoder();
int charCount = dec.GetCharCount(bytes, remaining, false);
if (charCount == 0)
{
return string.Empty;
}
var resultChars = new char[charCount];
fixed (char* chars = resultChars)
{
charCount = dec.GetChars(bytes, remaining, chars, charCount, true);
int i = -1, z = 0;
while (i < charCount)
{
++i;
if (chars[i] == '\0')
{
charCount = i;
++z;
break;
}
}
Encoder enc = encoding.GetEncoder();
position += enc.GetByteCount(chars, charCount + z, true);
if (charCount == 0) return string.Empty;
return new string(chars, 0, charCount);
}
}
}
public string ReadLine()
{
return ReadLine((int)Length - position, ZContext.Encoding);
}
public string ReadLine(Encoding encoding)
{
return ReadLine((int)Length - position, encoding);
}
public string ReadLine(int byteCount, Encoding encoding)
{
int remaining = Math.Min(byteCount, Math.Max(0, (int)Length - position));
if (remaining == 0)
{
return string.Empty;
}
if (remaining < 0)
{
return null;
}
unsafe
{
var bytes = (byte*)(this.DataPtr() + position);
Decoder dec = encoding.GetDecoder();
int charCount = dec.GetCharCount(bytes, remaining, false);
if (charCount == 0) return string.Empty;
var resultChars = new char[charCount];
fixed (char* chars = resultChars)
{
charCount = dec.GetChars(bytes, remaining, chars, charCount, true);
int i = -1, z = 0;
while (i < charCount)
{
++i;
if (chars[i] == '\n')
{
charCount = i;
++z;
if (i - 1 > -1 && chars[i - 1] == '\r')
{
--charCount;
++z;
}
break;
}
if (chars[i] == '\0')
{
charCount = i;
++z;
break;
}
}
Encoder enc = encoding.GetEncoder();
position += enc.GetByteCount(chars, charCount + z, true);
if (charCount == 0) return string.Empty;
return new string(chars, 0, charCount);
}
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (position + count > Length)
{
throw new InvalidOperationException();
}
Marshal.Copy(buffer, offset, DataPtr() + position, count);
position += count;
}
public void Write(byte value)
{
if (position + 1 > Length)
{
throw new InvalidOperationException();
}
Marshal.WriteByte(DataPtr() + position, value);
++position;
}
public override void WriteByte(byte value)
{
Write(value);
}
public void Write(Int16 value)
{
if (position + 2 > Length)
{
throw new InvalidOperationException();
}
Marshal.WriteInt16(DataPtr() + position, value);
position += 2;
}
public void Write(UInt16 value)
{
Write((Int16)value);
}
public void Write(Char value)
{
Write((Int16)value);
}
public void Write(Int32 value)
{
if (position + 4 > Length)
{
throw new InvalidOperationException();
}
Marshal.WriteInt32(DataPtr() + position, value);
position += 4;
}
public void Write(UInt32 value)
{
Write((Int32)value);
}
public void Write(Int64 value)
{
if (position + 8 > Length)
{
throw new InvalidOperationException();
}
Marshal.WriteInt64(DataPtr() + position, value);
position += 8;
}
public void Write(UInt64 value)
{
Write((Int64)value);
}
public void Write(string str)
{
Write(str, ZContext.Encoding);
}
public void Write(string str, Encoding encoding)
{
WriteStringNative(str, encoding, false);
}
public void WriteLine(string str)
{
WriteLine(str, ZContext.Encoding);
}
public void WriteLine(string str, Encoding encoding)
{
WriteStringNative(string.Format("{0}\r\n", str), encoding, false);
}
unsafe internal void WriteStringNative(string str, Encoding encoding, bool create)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str == string.Empty)
{
if (create)
{
this.framePtr = CreateNative(0);
this.length = 0;
this.position = 0;
}
return;
}
int charCount = str.Length;
Encoder enc = encoding.GetEncoder();
fixed (char* strP = str)
{
int byteCount = enc.GetByteCount(strP, charCount, false);
if (create)
{
this.framePtr = CreateNative(byteCount);
this.length = byteCount;
this.position = 0;
}
else if (this.position + byteCount > this.Length)
{
// fail if frame is too small
throw new InvalidOperationException();
}
byteCount = enc.GetBytes(strP, charCount, (byte*)(this.DataPtr() + this.position), byteCount, true);
this.position += byteCount;
}
}
public override void Flush()
{
throw new NotSupportedException();
}
public override void Close()
{
if (framePtr == null)
return;
if (framePtr.Ptr == IntPtr.Zero)
{
Dismiss();
return;
}
ZError error;
while (-1 == zmq.msg_close(framePtr))
{
error = ZError.GetLastErr();
if (error == ZError.EINTR)
{
error = default(ZError);
continue;
}
if (error == ZError.EFAULT)
{
// Ignore: Invalid message.
break;
}
return;
}
// Go unallocating the HGlobal
Dismiss();
}
public void CopyZeroTo(ZFrame other)
{
// zmq.msg_copy(dest, src)
ZError error;
while (-1 == zmq.msg_copy(other.framePtr, framePtr))
{
error = ZError.GetLastErr();
if (error == ZError.EINTR)
{
error = default(ZError);
continue;
}
if (error == ZError.EFAULT)
{
// Invalid message.
}
throw new ZException(error, "zmq_msg_copy");
}
}
public void MoveZeroTo(ZFrame other)
{
// zmq.msg_copy(dest, src)
ZError error;
while (-1 == zmq.msg_move(other.framePtr, framePtr))
{
error = ZError.GetLastErr();
if (error == ZError.EINTR)
{
error = default(ZError);
continue;
}
if (error == ZError.EFAULT)
{
// Invalid message.
}
throw new ZException(error, "zmq_msg_move");
}
// When move, msg_close this _framePtr
Close();
}
public Int32 GetOption(ZFrameOption property)
{
Int32 result;
ZError error;
if (-1 == (result = GetOption(property, out error)))
{
throw new ZException(error);
}
return result;
}
public Int32 GetOption(ZFrameOption property, out ZError error)
{
error = ZError.None;
int result;
if (-1 == (result = zmq.msg_get(this.framePtr, (Int32)property)))
{
error = ZError.GetLastErr();
return -1;
}
return result;
}
public string GetOption(string property)
{
ZError error;
string result;
if (null == (result = GetOption(property, out error))) {
if (error != ZError.None)
{
throw new ZException(error);
}
}
return result;
}
public string GetOption(string property, out ZError error)
{
error = ZError.None;
string result = null;
using (var propertyPtr = DispoIntPtr.AllocString(property))
{
IntPtr resultPtr;
if (IntPtr.Zero == (resultPtr = zmq.msg_gets(this.framePtr, propertyPtr)))
{
error = ZError.GetLastErr();
return null;
}
else
{
result = Marshal.PtrToStringAnsi(resultPtr);
}
}
return result;
}
#region ICloneable implementation
public object Clone()
{
return Duplicate();
}
public ZFrame Duplicate()
{
var frame = ZFrame.CreateEmpty();
this.CopyZeroTo(frame);
return frame;
}
#endregion
public override string ToString()
{
return ToString(ZContext.Encoding);
}
public string ToString(Encoding encoding)
{
if (Length > -1)
{
long old = position;
Position = 0;
string retur = ReadString(encoding);
Position = old;
return retur;
}
return GetType().FullName;
}
}
}