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
|
/* Copyright (c) 2008-2011 - Eric P. Mangold
* Released under the terms of the MIT/X11 license - see LICENSE.txt */
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
namespace AMP
{
// TODO implement AMPList
public interface IAmpType
{
byte[] ToAmpBytes(Object obj);
Object FromAmpBytes(byte[] bytes);
}
namespace Type
{
/// <summary>
/// Encoder/Decoder for .NET `string' type
/// </summary>
public class String : IAmpType
{
public byte[] ToAmpBytes(Object obj)
{
return Encoding.UTF8.GetBytes((string)obj);
}
public Object FromAmpBytes(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
}
/// <summary>
/// Encoder/Decoder for .NET `byte[]' type
/// </summary>
public class Bytes : IAmpType
{
public byte[] ToAmpBytes(Object obj)
{
return (byte[])obj;
}
public Object FromAmpBytes(byte[] bytes)
{
return bytes;
}
}
/// <summary>
/// Encoder/Decoder for .NET `bool' type
/// </summary>
public class Bool : IAmpType
{
private byte[] TRUE = Encoding.UTF8.GetBytes("True");
private byte[] FALSE = Encoding.UTF8.GetBytes("False");
public byte[] ToAmpBytes(Object obj)
{
return (bool)obj ? TRUE : FALSE;
}
public Object FromAmpBytes(byte[] bytes)
{
if (BytesUtil.AreEqual(TRUE, bytes))
{
return true;
}
if (BytesUtil.AreEqual(FALSE, bytes))
{
return false;
}
/// XXX If this throws it blows up when passing this error across thread boundaries
/// with SerializationException. test_AMP_error will demonstrate if you
/// change this method to always throw
throw new Error.TypeDecodeError();
}
}
/// <summary>
/// Encoder/Decoder for .NET `int' type
/// </summary>
public class Int32 : IAmpType
{
public byte[] ToAmpBytes(Object obj)
{
return Encoding.UTF8.GetBytes(((int)obj).ToString());
}
public Object FromAmpBytes(byte[] bytes)
{
return System.Int32.Parse(Encoding.UTF8.GetString(bytes));
}
}
/// <summary>
/// Encoder/Decoder for .NET `uint' type
/// </summary>
public class UInt32 : IAmpType
{
public byte[] ToAmpBytes(Object obj)
{
return Encoding.UTF8.GetBytes(((uint)obj).ToString());
}
public Object FromAmpBytes(byte[] bytes)
{
return System.UInt32.Parse(Encoding.UTF8.GetString(bytes));
}
}
/// <summary>
/// Encoder/Decoder for .NET `long' type
/// </summary>
public class Int64 : IAmpType
{
public byte[] ToAmpBytes(Object obj)
{
return Encoding.UTF8.GetBytes(((long)obj).ToString());
}
public Object FromAmpBytes(byte[] bytes)
{
return System.Int64.Parse(Encoding.UTF8.GetString(bytes));
}
}
/// <summary>
/// Encoder/Decoder for .NET `ulong' type
/// </summary>
public class UInt64 : IAmpType
{
public byte[] ToAmpBytes(Object obj)
{
return Encoding.UTF8.GetBytes(((ulong)obj).ToString());
}
public Object FromAmpBytes(byte[] bytes)
{
return System.UInt64.Parse(Encoding.UTF8.GetString(bytes));
}
}
/// <summary>
/// Encoder/Decoder for .NET `decimal' type
/// </summary>
public class Decimal : IAmpType
{
public byte[] ToAmpBytes(Object obj)
{
return Encoding.UTF8.GetBytes(((decimal)obj).ToString());
}
public Object FromAmpBytes(byte[] bytes)
{
string s = Encoding.UTF8.GetString(bytes);
string[] parts = s.Split('E'); // might use Engineering notation
if (parts.Length == 1)
{
return decimal.Parse(s);
}
else if (parts.Length == 2)
{
decimal d = decimal.Parse(parts[0]);
int i = int.Parse(parts[1]);
if (i != 0)
{
decimal factor = (i > 0) ? 10m : 0.1m;
for (int j = Math.Abs(i); j > 0; j--)
{
d *= factor;
}
}
return d;
}
else
{
throw new Error.TypeDecodeError();
}
}
}
/// <summary>
/// Encoder/Decoder for .NET `double' type
/// </summary>
public class Double : IAmpType
{
public static byte[] NAN = Encoding.UTF8.GetBytes("nan");
public static byte[] POSINF = Encoding.UTF8.GetBytes("inf");
public static byte[] NEGINF = Encoding.UTF8.GetBytes("-inf");
static bool arraysEqual(byte[] a, byte[] b)
{
if (a.Length != b.Length)
return false;
int i;
for (i = 0; i < a.Length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
public byte[] ToAmpBytes(Object obj)
{
double d = (double)obj;
if (double.IsNaN(d)) {
return NAN;
} else if (double.IsPositiveInfinity(d)) {
return POSINF;
} else if (double.IsNegativeInfinity(d)) {
return NEGINF;
} else {
return Encoding.UTF8.GetBytes(d.ToString());
}
}
public Object FromAmpBytes(byte[] bytes)
{
if (arraysEqual(bytes, NAN)) {
return double.NaN;
} else if (arraysEqual(bytes, POSINF)) {
return double.PositiveInfinity;
} else if (arraysEqual(bytes, NEGINF)) {
return double.NegativeInfinity;
} else {
return double.Parse(Encoding.UTF8.GetString(bytes));
}
}
}
/// <summary>
/// Encoder/Decoder for .NET `DateTimeOffset' type, using the standard AMP `DateTime' format.
/// If you wish to send .NET `DateTime' instances over the wire, convert them to a `DateTimeOffset' first.
/// </summary>
public class DateTimeOffset : IAmpType
{
public byte[] ToAmpBytes(Object obj)
{
var dt = (System.DateTimeOffset)obj;
var fmt = new System.Globalization.DateTimeFormatInfo();
fmt.TimeSeparator = ":";
string s = dt.ToString("yyyy-MM-ddTHH:mm:ss.ffffffzzz", fmt);
System.Diagnostics.Debug.Assert(s.Length == 32);
return Encoding.UTF8.GetBytes(s);
}
public Object FromAmpBytes(byte[] bytes)
{
// "2012-01-23T12:34:56.054321+01:23"
string s = Encoding.UTF8.GetString(bytes);
System.Diagnostics.Debug.Assert(s.Length == 32);
int year = int.Parse(s.Substring(0, 4));
int month = int.Parse(s.Substring(5, 2));
int day = int.Parse(s.Substring(8, 2));
int hour = int.Parse(s.Substring(11, 2));
int min = int.Parse(s.Substring(14, 2));
int sec = int.Parse(s.Substring(17, 2));
// The AMP spec specifies 6 decimal places for the fractional portion of the seconds.
// But a DateTimeOffset can only hold miliseconds (3 decimal places), so we just
// take the first 3 and ignore the rest.
int miliseconds = int.Parse(s.Substring(20, 3));
string offsetDirection = s.Substring(26, 1);
int offsetHour = int.Parse(s.Substring(27, 2));
int offsetMinute = int.Parse(s.Substring(30, 2));
TimeSpan offset;
if (offsetDirection == "+")
{
offset = new TimeSpan(offsetHour, offsetMinute, 0);
}
else if (offsetDirection == "-")
{
offset = new TimeSpan(offsetHour, offsetMinute, 0).Negate();
}
else
{
throw new AMP.Error.TypeDecodeError();
}
return new System.DateTimeOffset(year, month, day, hour, min, sec, miliseconds, offset);
}
}
/// <summary>
/// Encoder/Decoder for .NET `DateTime' type. Encodes and decodes as UTC - timezone information is not retained.
/// **DEPRECATED** - use Amp.Type.DateTimeOffset
/// </summary>
public class TimeArgument : IAmpType
{
public byte[] ToAmpBytes(Object obj)
{
DateTime dt = ((DateTime)obj).ToUniversalTime();
string s = dt.ToString("yyyy/M/d HH:mm:ss");
return Encoding.UTF8.GetBytes(s);
}
public Object FromAmpBytes(byte[] bytes)
{
string s = Encoding.UTF8.GetString(bytes);
string[] parts = s.Split(' ');
string[] date_parts = parts[0].Split('/');
string[] time_parts = parts[1].Split(':');
int year = int.Parse(date_parts[0]);
int month = int.Parse(date_parts[1]);
int day = int.Parse(date_parts[2]);
int hour = int.Parse(time_parts[0]);
int min = int.Parse(time_parts[1]);
int sec = int.Parse(time_parts[2]);
var dt = new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc);
return dt;
}
}
/// <summary>
/// Encoder/Decoder for a List of one of the other IAmpType classes
/// e.g. new ListOf(new AMP.Type.String())
/// </summary>
public class ListOf : IAmpType
{
private IAmpType listType;
public ListOf(IAmpType type)
{
listType = type;
}
public byte[] ToAmpBytes(Object obj)
{
var chunks = new List<byte[]>();
byte[] chunkLen;
byte[] chunk;
byte[] result;
int totalLen = 0;
if (BitConverter.IsLittleEndian)
{
foreach (Object item in (IEnumerable)obj)
{
chunk = listType.ToAmpBytes(item);
totalLen += chunk.Length + 2;
chunkLen = BitConverter.GetBytes((UInt16)chunk.Length);
// XOR SWAP the bytes because we're on little-endian but the value
// needs to be in big-endian order.
chunkLen[0] ^= chunkLen[1];
chunkLen[1] ^= chunkLen[0];
chunkLen[0] ^= chunkLen[1];
chunks.Add(chunkLen);
chunks.Add(chunk);
}
}
else
{
foreach (Object item in (IEnumerable)obj)
{
chunk = listType.ToAmpBytes(item);
totalLen += chunk.Length + 2;
chunkLen = BitConverter.GetBytes((UInt16)chunk.Length);
chunks.Add(chunkLen);
chunks.Add(chunk);
}
}
result = new byte[totalLen];
// blit each sub-array to the result array
int i = 0;
foreach (byte[] c in chunks)
{
c.CopyTo(result, i);
i += c.Length;
}
return result;
}
public Object FromAmpBytes(byte[] bytes)
{
int idx = 0;
byte[] chunkLen = new byte[2];
int chunkLenInt;
var result = new List<Object>();
while (idx < bytes.Length)
{
// got 2 bytes remaining at least?
if (bytes.Length - idx < 2)
{
throw new Error.TypeDecodeError();
}
// read the length prefix
chunkLen[0] = bytes[idx];
chunkLen[1] = bytes[idx + 1];
idx += 2;
if (BitConverter.IsLittleEndian)
{
// on a little-endian machine, but value is in big-endian, so
// XOR SWAP bytes before decoding integer
chunkLen[0] ^= chunkLen[1];
chunkLen[1] ^= chunkLen[0];
chunkLen[0] ^= chunkLen[1];
}
chunkLenInt = BitConverter.ToUInt16(chunkLen, 0);
// We *should* have at least chunkLenInt bytes remaining in the array...
if (bytes.Length - idx < chunkLenInt)
{
throw new Error.TypeDecodeError();
}
var tmp = new byte[chunkLenInt];
Array.Copy(bytes, idx, tmp, 0, chunkLenInt);
idx += chunkLenInt;
result.Add(listType.FromAmpBytes(tmp));
}
return result;
}
}
/// <summary>
/// Encoder/Decoder for a List of AMP messages. E.g.
/// <code>
/// var aList = new AMP.Type.AmpList();
/// aList.AddParameter("full_name", new AMP.Type.String());
/// aList.AddParameter("age", new AMP.Type.Int32());
/// </code>
/// Then each item of the List that you send or receive using aList
/// will be an AMP.Msg containing a "full_name" and an "age" key
/// with values of the appropriate type (though casted to Object for
/// storage in an AMP.Msg)
/// </summary>
public class AmpList : IAmpType
{
// A customized Protocol for parsing and accumulating AMP boxes
private class SubParser : Protocol
{
private List<Msg_Raw> msgs;
public SubParser(List<Msg_Raw> msgs)
: base()
{
this.msgs = msgs;
}
internal override void ProcessFullMessage(Msg_Raw raw_msg)
{
msgs.Add(raw_msg);
}
}
private Command cmd;
public AmpList()
{
// The Command class wasn't really meant to help us parse nested AMP messages
// but it's flexible enough to do so without being refactored, so who am I to argue?
cmd = new Command();
}
public void AddParameter(string keyName, IAmpType type)
{
cmd.AddArgument(keyName, type);
}
public byte[] ToAmpBytes(Object obj)
{
var chunks = new List<byte[]>();
byte[] chunk;
Msg_Raw raw_msg;
int totalLen = 0;
var msgs = (IEnumerable<Msg>)obj;
foreach (Msg msg in msgs)
{
raw_msg = cmd.ToRawMessage(msg, MsgType.REQUEST);
chunk = Protocol.BuildAMPWireCommand(raw_msg);
totalLen += chunk.Length;
chunks.Add(chunk);
}
var result = new byte[totalLen];
// blit each sub-array to the result array
int i = 0;
foreach (byte[] c in chunks)
{
c.CopyTo(result, i);
i += c.Length;
}
return result;
}
public Object FromAmpBytes(byte[] bytes)
{
var msgs = new List<Msg_Raw>();
var subParser = new SubParser(msgs);
var result = new List<Msg>();
subParser.DataReceived(bytes);
Msg typedMsg;
foreach (Msg_Raw raw in msgs)
{
typedMsg = cmd.ToTypedMessage(raw, MsgType.REQUEST);
result.Add(typedMsg);
}
return result;
}
}
}
}
|