1 // Copyright 2006 Alp Toker <alp@atoker.com>
2 // This software is made available under the MIT License
3 // See COPYING for details
6 using System
.Collections
;
7 using System
.Collections
.Generic
;
10 using System
.Reflection
;
16 public class WvDbusWriter
18 readonly DataConverter conv
;
19 readonly Dbus
.Endian endianness
;
20 WvBuf buf
= new WvBuf(1024);
24 endianness
= WvDbusMsg
.NativeEndianness
;
25 if (endianness
== Dbus
.Endian
.Little
)
26 conv
= DataConverter
.LittleEndian
;
28 conv
= DataConverter
.BigEndian
;
31 public byte[] ToArray()
33 return (byte[])buf
.peekall();
36 void p(int align
, WvBytes b
)
42 public void Write(byte val
)
47 public void Write(bool val
)
49 Write((uint)(val
? 1 : 0));
52 public void Write(short val
)
54 p(2, conv
.GetBytes(val
));
57 public void Write(ushort val
)
59 p(2, conv
.GetBytes(val
));
62 public void Write(int val
)
64 p(4, conv
.GetBytes(val
));
67 public void Write(uint val
)
69 p(4, conv
.GetBytes(val
));
72 public void Write(long val
)
74 p(8, conv
.GetBytes(val
));
77 public void Write(ulong val
)
79 p(8, conv
.GetBytes(val
));
82 public void Write(float val
)
84 p(4, conv
.GetBytes(val
));
87 public void Write(double val
)
89 p(8, conv
.GetBytes(val
));
92 public void Write(string val
)
94 byte[] b
= Encoding
.UTF8
.GetBytes(val
);
95 Write((uint)b
.Length
);
100 public void WriteSig(string val
)
102 byte[] b
= val
.ToUTF8();
104 if (b
.Length
> Dbus
.Protocol
.MaxSignatureLength
)
107 + b
.Length
+ " exceeds maximum allowed "
108 + Dbus
.Protocol
.MaxSignatureLength
+ " bytes");
110 Write((byte)b
.Length
);
115 static byte[] zeroes
= new byte[8] { 0,0,0,0,0,0,0,0 }
;
116 public void WriteArray
<T
>(int align
,
118 Action
<WvDbusWriter
,T
> doelement
)
120 // after the arraylength, we'll be aligned to size 4, but that
121 // might not be enough, so maybe we need to fix it up.
124 var tmp
= new WvDbusWriter();
126 int startpad
= (int)(buf
.used
+4) % 8;
127 tmp
.buf
.put(zeroes
.sub(0, startpad
));
129 int first
= tmp
.buf
.used
;
131 foreach (T i
in list
)
137 byte[] a
= tmp
.ToArray();
139 // the length word excludes all padding...
140 Write((uint)(a
.Length
- first
));
142 // ...but we have to copy all the bytes *including* padding
143 buf
.put(a
.sub(startpad
, a
.Length
- startpad
));
146 public void Write(WvBytes b
)
152 public void Write(byte[] b
)
157 public void WriteNull()
162 public void WritePad(int alignment
)
164 int needed
= Dbus
.Protocol
.PadNeeded(buf
.used
, alignment
);
165 buf
.put(zeroes
.sub(0, needed
));