/* Blunk - Multi User Server Framework Copyright 2009 - 2010 Nils W [nillus.net] Michael Graham [script-o-matic.net] This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . * PORTED TO C# BY awa500! */ /** * Provides various helper methods to work with the MultiUserServer. * * @author Nillus * */ using System.IO; using System; using MiscUtil.IO; namespace Holo.Source.Socket_servers.MUS { public class MusUtil { public static string readEvenPaddedString(EndianBinaryReader inData) { // String length int length = inData.ReadInt32(); if (length <= 0) { return ""; } else { // Actual string bytes byte[] bytes = new byte[length]; inData.Read(bytes, 0, bytes.Length); // Advance one byte if uneven if ((length % 2) != 0) { inData.ReadByte(); } // Return the string return System.Text.Encoding.Default.GetString(bytes); } } public static void writeEvenPaddedString(EndianBinaryWriter outData, string str) { // String length outData.Write(str.Length); // Actual string bytes outData.Write(System.Text.Encoding.Default.GetBytes(str)); // Add a null byte if uneven if ((str.Length % 2) != 0) { outData.Write(0); } } public static MusPropList readPropList(EndianBinaryReader inData) { // Length of list int length = inData.ReadInt32(); // Allocate props MusPropList props = new MusPropList(length); // Parse them for (int i = 0; i < length; i++) { // Symbol type (always string) inData.ReadInt16(); // Symbol (key) string symbol = MusUtil.readEvenPaddedString(inData); // Data type short dataType = inData.ReadInt16(); // Data (value) int dataLength; if (dataType == MusTypes.Integer) { dataLength = 4; } else { dataLength = inData.ReadInt32(); } byte[] data = new byte[dataLength]; inData.Read(data, 0, data.Length); if ((dataLength % 2) != 0) { inData.ReadByte(); } // Set prop props.setPropAsBytes(symbol, dataType, data); } return props; } public static void writePropList(EndianBinaryWriter outData, MusPropList props) { // Length outData.Write(props.length()); // Serialize elements for (int i = 0; i < props.length(); i++) { // Symbol outData.Write(MusTypes.Symbol); MusUtil.writeEvenPaddedString(outData, props.getSymbolAt(i)); // Value outData.Write(props.getDataTypeAt(i)); byte[] data = props.getDataAt(i); if (props.getDataTypeAt(i) != MusTypes.Integer) { outData.Write(data.Length); } outData.Write(data); if ((data.Length % 2) != 0) { outData.Write(Convert.ToByte(0)); } } } } }