private static void msgListen() { cont = true; while (cont) { BitMsg[] Messages = JsonConverter.getMessages(BA.getAllInboxMessages()); foreach (BitMsg m in Messages) { if (m.message.StartsWith("GET ") || m.message.StartsWith("POST ")) { string[] Parts = m.message.Split(new string[] { "\r\n\r\n" }, 2, StringSplitOptions.None); //Decode content, if present byte[] content = null; if (Parts.Length == 2 && Parts[1].Length > 0) { Ascii85 A5 = new Ascii85(); content = A5.Decode(Parts[1]); } Thread t = new Thread(new ParameterizedThreadStart(sr)); t.IsBackground = true; t.Start(new object[] { m.fromAddress, m.toAddress, m.subject, Parts[0], content }); BA.trashMessage(m.msgid); } } Thread.Sleep(2000); } }
private static void c_Request(HTTPConnection Sender, string Address, string Headers, byte[] Content) { string ID = getID(); string Enc = string.Empty; Address = parseAddress(Address); if (string.IsNullOrEmpty(Address)) { Sender.Send(Base.HTTP_NODNS, null); } else { if (Req.ContainsKey(ID)) { Req[ID] = Sender; } else { Req.Add(ID, Sender); } if (Content != null && Content.Length > 0) { Ascii85 A5 = new Ascii85(); Enc = A5.Encode(Content); } BA.sendMessage(Address, LOCAL, JsonConverter.B64enc(ID), JsonConverter.B64enc(Headers + "\r\n\r\n" + Enc)); } }
private static void msgListen() { while (s != null) { BitMsg[] Messages = JsonConverter.getMessages(BA.getAllInboxMessages()); foreach (BitMsg m in Messages) { if (Req.ContainsKey(m.subject) && m.message.StartsWith("HTTP")) { string[] Parts = m.message.Split(new string[] { "\r\n\r\n" }, 2, StringSplitOptions.None); if (Parts.Length == 2) { //Decode content, if present byte[] content = null; if (Parts[1].Length > 0) { Ascii85 A5 = new Ascii85(); content = A5.Decode(Parts[1]); } BA.trashMessage(m.msgid); Req[m.subject].Send(Parts[0], content); //Remove connection and request cc.Remove(Req[m.subject]); Req.Remove(m.subject); } } } Thread.Sleep(2000); } }
/// <summary> /// Tests binary file encoding and decoding /// </summary> static void TestFile() { Ascii85 a = new Ascii85(); a.EnforceMarks = false; a.LineLength = 0; // read the file FileStream fs = new FileStream(@"c:\test.gif", FileMode.Open); byte[] ba = new byte[fs.Length]; fs.Read(ba, 0, (int)fs.Length); fs.Close(); // encode it string encoded; encoded = a.Encode(ba); Console.WriteLine("file encoded in string of length " + encoded.Length); // decode it byte[] decoded = a.Decode(encoded); // write the file FileStream fs2 = new FileStream(@"c:\test_out.gif", FileMode.OpenOrCreate); fs2.Write(decoded, 0, decoded.Length); fs2.Close(); }
public static string Serialize(Graph g) { var bytes = SerializeToByteArray(g); var compressed = QuickLZ.compress(bytes); var Ascii85 = new Ascii85(); return(Prefix + Ascii85.Encode(compressed)); }
static void DecodeLayer0() { var payload = GetPayload(Layer0Data); var decoded = Ascii85.Decode(payload); var output = Encoding.ASCII.GetString(decoded, 0, decoded.Length); File.WriteAllText($"{DataDirectory}{Layer1Data}", output); }
public static string ConvertBase85ToAscii(string s) { Ascii85 ascii85 = new Ascii85(); byte[] output = ascii85.Decode(s); return(Encoding.ASCII.GetString(output)); }
public static string Base85Decode(this string encoded) { try { return(Encoding.ASCII.GetString(Ascii85.Decode(encoded))); } catch (Exception) { return(null); } }
public void DecodeTest() { Ascii85 target = new Ascii85(); Guid original = Guid.NewGuid(); string encoded = target.Encode(original.ToByteArray()); var actual = target.Decode(encoded); Assert.AreEqual <Guid>(original, new Guid(actual)); }
public void ShouldThrowErrorWhenDecodeAValueWithoutPrefixOrSufix(string value) { // Arrange var sut = new Ascii85(); sut.EnforceMarks = true; // Act & Assert Assert.Throws <NHiLoException>(() => sut.Decode(value)); }
static void DecodeLayer4() { var payload = GetPayload(Layer4Data); var decoded = Ascii85.Decode(payload); decoded = Layer4.NetworkStreamToPayload(decoded); var output = Encoding.ASCII.GetString(decoded, 0, decoded.Length); File.WriteAllText($"{DataDirectory}{Layer5Data}", output); }
public void WikipediaSample() { const string c_text = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure."; const string c_encoded = @"9jqo^BlbD-BleB1DJ+*+F(f,q/0JhKF<GL>[email protected]$d7F!,L7@<6@)/0JDEF<G%<+EV:2F!,O<DJ+*.@<*K0@<6L(Df-\0Ec5e;DffZ(EZee.Bl.9pF""AGXBPCsi+DGm>@3BB/F*&OCAfu2/AKYi(DIb:@FD,*)+C]U=@3BN#EcYf8ATD3s@q?d$AftVqCh[NqF<G:8+EV:.+Cf>-FD5W8ARlolDIal(DId<j@<?3r@:F%a+D58'ATD4$Bl@l3De:,-DJs`8ARoFb/0JMK@qB4^F!,R<AKZ&-DfTqBG%G>uD.RTpAKYo'+CT/5+Cei#DII?(E,9)oF*2M7/c"; byte[] bytes = Encoding.ASCII.GetBytes(c_text); Assert.That(Ascii85.Encode(bytes), Is.EqualTo(c_encoded)); Assert.That(Ascii85.Decode(c_encoded), Is.EqualTo(bytes)); }
public void EncodeTest() { Ascii85 target = new Ascii85(); Guid val = "462b9417-77e5-4681-aafc-4b40529362d6".ToGuid(); byte[] binary = val.ToByteArray(); string expected = "(R-F>j`c8FWr,LT;NkS@"; string actual = target.Encode(binary); Assert.AreEqual(expected, actual); }
public void DecoderRoundtripVsReference(int length) { var random = new Random(1337); // same seed var original = new byte[length]; random.NextBytes(original); var encoded = Ascii85.Encode(original); var decoded = Base85.Default.Decode(encoded); Assert.Equal(decoded, original); }
/// <summary> /// Tests bad data scenarios that should result in an exception /// </summary> static void TestError() { Ascii85 a = new Ascii85(); string encoded = ""; //encoded = "<~blocz~>"; //encoded = "<~bloc|~>"; //encoded = "<~block"; //encoded = "<~blocku~>"; a.Decode(encoded); }
/// <summary> /// Exports the tree attribute data to a string. /// </summary> /// <param name="tree"></param> /// <returns></returns> public virtual string StringEncodeTreeAttribute(ITreeAttribute tree) { byte[] data; using (MemoryStream ms = new MemoryStream()) { BinaryWriter writer = new BinaryWriter(ms); tree.ToBytes(writer); data = ms.ToArray(); } return(Ascii85.Encode(data)); }
public static Graph Deserialize(string s) { try { var Ascii85 = new Ascii85(); var compressed = Ascii85.Decode(s.Substring(Prefix.Length)); var bytes = QuickLZ.decompress(compressed); return(DeserializeFromByteArray(bytes)); } catch { } return(null); }
public void ShouldAEncondedValueBeDecodedToTheOriginal(string value) { // Arrange var sut = new Ascii85(); // Act string encoded = sut.Encode(Encoding.ASCII.GetBytes(value)); byte[] decoded = sut.Decode($"<~{encoded}~>"); string result = Encoding.ASCII.GetString(decoded); // Assert result.Should().Be(value); }
public void SaveEntityInAttributes(Entity entity, ItemStack stack, string key) { using (MemoryStream ms = new MemoryStream()) { BinaryWriter writer = new BinaryWriter(ms); ICoreAPI api = entity.Api; writer.Write(api.World.ClassRegistry.GetEntityClassName(entity.GetType())); entity.ToBytes(writer, false); string value = Ascii85.Encode(ms.ToArray()); stack.Attributes.SetString(key, value); } }
/// <summary> /// Imports the tree data from a string. /// </summary> /// <param name="data"></param> /// <returns></returns> public virtual TreeAttribute DecodeBlockEntityData(string data) { byte[] bedata = Ascii85.Decode(data); TreeAttribute tree = new TreeAttribute(); using (MemoryStream ms = new MemoryStream(bedata)) { BinaryReader reader = new BinaryReader(ms); tree.FromBytes(reader); } return(tree); }
public static Graph Deserialize(string s) { try { var Ascii85 = new Ascii85(); var compressed = Ascii85.Decode(s.Substring(Prefix.Length)); var bytes = QuickLZ.decompress(compressed); return(DeserializeFromByteArray(bytes)); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(null); }
/// <summary> /// Converts this string to a Guid which is encoded in ASCII85 /// </summary> /// <param name="convert">String to convert</param> /// <returns>Resulting Guid</returns> public static Guid ToGuidAscii85(this string convert) { Contract.Requires(null != convert); var ascii = new Ascii85(); var bytes = ascii.Decode(convert); if (null != bytes && 16 == bytes.Length) { return(new Guid(bytes)); } else { throw new FormatException("Invalid string for decoding into Guid."); } }
/// <summary> /// Tests text encoding and decoding, /// derived from Wikipedia entry on ASCII85 /// http://en.wikipedia.org/wiki/Ascii85 /// </summary> static void TestString() { Ascii85 a = new Ascii85(); string s = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure."; byte[] ba = Encoding.ASCII.GetBytes(s); string encoded = a.Encode(ba); Console.WriteLine(); Console.WriteLine(encoded); Console.WriteLine(); Console.WriteLine("Encoded in " + encoded.Length + " chars"); Console.WriteLine(); byte[] decoded = a.Decode(encoded); Console.WriteLine(Encoding.ASCII.GetString(decoded)); Console.WriteLine(); Console.WriteLine("Decoded " + decoded.Length + " chars"); Console.WriteLine(); }
private string CompressApi(string api) { var output = new MemoryStream(); var gzip = new GZipStream(output, CompressionLevel.Optimal); var bytes = Encoding.UTF8.GetBytes(api); gzip.Write(bytes, 0, bytes.Length); gzip.Close(); var ascii85 = Ascii85.Encode(output.ToArray()); var result = new List <string>(); var rest = ascii85.Length; const int lineLength = 80; for (var i = 0; i < ascii85.Length; i += lineLength, rest -= lineLength) { result.Add(ascii85.Substring(i, Math.Min(rest, lineLength))); } return(string.Join("\r\n", result)); }
public void Encode() { PAssert.That(() => Ascii85.Encode(new byte [0]) == "<~~>"); var expected = new[] { "", "!!", "!!*", "!!*-", "!!*-'", "!!*-'\"9", "!!*-'\"9e", "!!*-'\"9eu" }; var input = new List <byte>(); for (var i = 0; i < expected.Length; input.Add((byte)i), i++) { var i1 = i; PAssert.That(() => Ascii85.Encode(input.ToArray()) == "<~" + expected[i1] + "~>", $"Length: {i1}"); } PAssert.That(() => Ascii85.Encode(new byte[] { 0, 0, 0, 0 }) == "<~" + "z" + "~>"); }
static void DecodeLayer6() { byte[] decoded; var runSampleProgram = false; if (runSampleProgram) { var lines = File.ReadLines($"{DataDirectory}{Layer6Data}"); decoded = Layer6.GetSampleProgramTestBytes(lines); } else { var payload = GetPayload(Layer6Data); decoded = Ascii85.Decode(payload); } File.WriteAllText($"{DataDirectory}{Layer7Data}", $"Begin decoding {nameof(Layer6Data)} at {System.DateTime.Now}"); var decrypted = Layer6.Decrypt(decoded); var output = Encoding.ASCII.GetString(decrypted, 0, decrypted.Length); File.WriteAllText($"{DataDirectory}{Layer7Data}", output); }
public Entity GetEntityFromAttributes(ItemStack stack, string key, IWorldAccessor world) { string value = null; if (stack.Attributes.HasAttribute(key)) { value = stack.Attributes.GetString(key); } if (value == null) { return(null); } using (MemoryStream ms = new MemoryStream(Ascii85.Decode(value))) { BinaryReader reader = new BinaryReader(ms); string className = reader.ReadString(); Entity entity = world.ClassRegistry.CreateEntity(className); entity.FromBytes(reader, false); return(entity); } }
public void MisplacedTilde() { Ascii85.Decode("a~z"); }
public void FinalTilde() { Ascii85.Decode("~"); }
/// <summary> /// Places all the entities and blocks in the schematic at the position. /// </summary> /// <param name="blockAccessor"></param> /// <param name="worldForCollectibleResolve"></param> /// <param name="startPos"></param> public void PlaceEntitiesAndBlockEntities(IBlockAccessor blockAccessor, IWorldAccessor worldForCollectibleResolve, BlockPos startPos) { BlockPos curPos = new BlockPos(); int schematicSeed = worldForCollectibleResolve.Rand.Next(); foreach (var val in BlockEntities) { uint index = val.Key; int dx = (int)(index & 0x1ff); int dy = (int)((index >> 20) & 0x1ff); int dz = (int)((index >> 10) & 0x1ff); curPos.Set(dx + startPos.X, dy + startPos.Y, dz + startPos.Z); BlockEntity be = blockAccessor.GetBlockEntity(curPos); // Block entities need to be manually initialized for world gen block access if (be == null && blockAccessor is IWorldGenBlockAccessor) { Block block = blockAccessor.GetBlock(curPos); if (block.EntityClass != null) { blockAccessor.SpawnBlockEntity(block.EntityClass, curPos); be = blockAccessor.GetBlockEntity(curPos); } } if (be != null) { Block block = blockAccessor.GetBlock(curPos); if (block.EntityClass != worldForCollectibleResolve.ClassRegistry.GetBlockEntityClass(be.GetType())) { worldForCollectibleResolve.Logger.Warning("Could not import block entity data for schematic at {0}. There is already {1}, expected {2}. Probably overlapping ruins.", curPos, be.GetType(), block.EntityClass); continue; } ITreeAttribute tree = DecodeBlockEntityData(val.Value); tree.SetInt("posx", curPos.X); tree.SetInt("posy", curPos.Y); tree.SetInt("posz", curPos.Z); be.FromTreeAttributes(tree, worldForCollectibleResolve); be.OnLoadCollectibleMappings(worldForCollectibleResolve, BlockCodes, ItemCodes, schematicSeed); be.Pos = curPos.Copy(); } } foreach (string entityData in Entities) { using (MemoryStream ms = new MemoryStream(Ascii85.Decode(entityData))) { BinaryReader reader = new BinaryReader(ms); string className = reader.ReadString(); Entity entity = worldForCollectibleResolve.ClassRegistry.CreateEntity(className); entity.FromBytes(reader, false); entity.DidImportOrExport(startPos); // Not ideal but whatever if (blockAccessor is IWorldGenBlockAccessor) { (blockAccessor as IWorldGenBlockAccessor).AddEntity(entity); } else { worldForCollectibleResolve.SpawnEntity(entity); } } } }