private static void WriteObject(Script script, ScorpioWriter writer, string type, ScriptObject value) { if (!WriteField(writer, type, value.ObjectValue)) { Write(script, writer, (ScriptTable)value, type); } }
/// <summary> /// 序列化一个网络协议 /// </summary> /// <param name="script">脚本引擎</param> /// <param name="table">协议内容</param> /// <param name="name">协议结构</param> /// <returns></returns> public static byte[] Serialize(Script script, ScriptTable table, string name) { ScorpioWriter writer = new ScorpioWriter(); Write(script, writer, table, name); return(writer.ToArray()); }
private static bool WriteField(ScorpioWriter write, string type, object value) { if (type == BoolType) { write.WriteBool((bool)value); } else if (type == Int8Type) { write.WriteInt8(ScorpioUtil.ToInt8(value)); } else if (type == Int16Type) { write.WriteInt16(ScorpioUtil.ToInt16(value)); } else if (type == Int32Type || type == IntType) { write.WriteInt32(ScorpioUtil.ToInt32(value)); } else if (type == Int64Type) { write.WriteInt64(ScorpioUtil.ToInt64(value)); } else if (type == FloatType) { write.WriteFloat(ScorpioUtil.ToFloat(value)); } else if (type == DoubleType) { write.WriteDouble(ScorpioUtil.ToDouble(value)); } else if (type == StringType) { write.WriteString((string)value); } else if (type == BytesType) { write.WriteBytes((byte[])value); } else { return(false); } return(true); }
private static void Write(Script script, ScorpioWriter writer, ScriptTable table, string tableName) { ScriptArray layout = (ScriptArray)script.GetValue(tableName); int sign = 0; for (int i = 0; i < layout.Count(); ++i) { ScriptObject config = layout.GetValue(i); if (table != null && table.HasValue(config.GetValue(Name).ObjectValue)) { sign = ScorpioUtil.AddSign(sign, ScorpioUtil.ToInt32(config.GetValue(Index).ObjectValue)); } } writer.WriteInt32(sign); for (int i = 0; i < layout.Count(); ++i) { ScriptObject config = layout.GetValue(i); string name = (string)config.GetValue(Name).ObjectValue; if (table != null && table.HasValue(name)) { string type = (string)config.GetValue(Type).ObjectValue; bool array = (bool)config.GetValue(Array).ObjectValue; if (array) { ScriptArray arr = table.GetValue(name) as ScriptArray; writer.WriteInt32(arr.Count()); for (int j = 0; j < arr.Count(); ++j) { WriteObject(script, writer, type, arr.GetValue(j)); } } else { WriteObject(script, writer, type, table.GetValue(name)); } } } }