/// <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(); }
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 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); } }
public static string Base85Decode(this string encoded) { try { return(Encoding.ASCII.GetString(Ascii85.Decode(encoded))); } catch (Exception) { return(null); } }
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 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 EncodeRoundtripVsReference(int length) { var random = new Random(1337); // same seed var original = new byte[length]; random.NextBytes(original); var encoded = Base85.Default.Encode(original); var decoded = Ascii85.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); }
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); }
/// <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(); }
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 DecodeOverflow(string encoded) { Ascii85.Decode(encoded); }
public void MisplacedTilde() { Ascii85.Decode("a~z"); }
public void DecodeNull() { Ascii85.Decode(null); }
public void ZInBlock() { Ascii85.Decode("abzde"); }
public void InvalidCharacterInBlock() { Ascii85.Decode("rstuv"); }
/// <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); } } } }
/// <summary> /// Attempts to transform each block as they are placed in directions different from the schematic. /// </summary> /// <param name="worldForResolve"></param> /// <param name="aroundOrigin"></param> /// <param name="angle"></param> /// <param name="flipAxis"></param> public virtual void TransformWhilePacked(IWorldAccessor worldForResolve, EnumOrigin aroundOrigin, int angle, EnumAxis?flipAxis = null) { BlockPos curPos = new BlockPos(); BlockPos startPos = new BlockPos(1024, 1024, 1024); BlocksUnpacked.Clear(); BlockEntitiesUnpacked.Clear(); EntitiesUnpacked.Clear(); angle = GameMath.Mod(angle, 360); for (int i = 0; i < Indices.Count; i++) { uint index = Indices[i]; int storedBlockid = BlockIds[i]; int dx = (int)(index & 0x1ff); int dy = (int)((index >> 20) & 0x1ff); int dz = (int)((index >> 10) & 0x1ff); AssetLocation blockCode = BlockCodes[storedBlockid]; Block newBlock = worldForResolve.GetBlock(blockCode); if (newBlock == null) { BlockEntities.Remove(index); continue; } if (flipAxis != null) { if (flipAxis == EnumAxis.Y) { dy = SizeY - dy; AssetLocation newCode = newBlock.GetVerticallyFlippedBlockCode(); newBlock = worldForResolve.GetBlock(newCode); } if (flipAxis == EnumAxis.X) { dx = SizeX - dx; AssetLocation newCode = newBlock.GetHorizontallyFlippedBlockCode((EnumAxis)flipAxis); newBlock = worldForResolve.GetBlock(newCode); } if (flipAxis == EnumAxis.Z) { dz = SizeZ - dz; AssetLocation newCode = newBlock.GetHorizontallyFlippedBlockCode((EnumAxis)flipAxis); newBlock = worldForResolve.GetBlock(newCode); } } if (angle != 0) { AssetLocation newCode = newBlock.GetRotatedBlockCode(angle); newBlock = worldForResolve.GetBlock(newCode); } if (aroundOrigin != EnumOrigin.StartPos) { dx -= SizeX / 2; dz -= SizeZ / 2; } BlockPos pos = new BlockPos(dx, dy, dz); // 90 deg: // xNew = -yOld // yNew = xOld // 180 deg: // xNew = -xOld // yNew = -yOld // 270 deg: // xNew = yOld // yNew = -xOld switch (angle) { case 90: pos.Set(-dz, dy, dx); break; case 180: pos.Set(-dx, dy, -dz); break; case 270: pos.Set(dz, dy, -dx); break; } if (aroundOrigin != EnumOrigin.StartPos) { pos.X += SizeX / 2; pos.Z += SizeZ / 2; } curPos.Set(pos.X + startPos.X, pos.Y + startPos.Y, pos.Z + startPos.Z); BlocksUnpacked[pos] = newBlock.BlockId; } 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); dx -= SizeX / 2; dz -= SizeZ / 2; BlockPos pos = new BlockPos(dx, dy, dz); // 90 deg: // xNew = -yOld // yNew = xOld // 180 deg: // xNew = -xOld // yNew = -yOld // 270 deg: // xNew = yOld // yNew = -xOld switch (angle) { case 90: pos.Set(-dz, dy, dx); break; case 180: pos.Set(-dx, dy, -dz); break; case 270: pos.Set(dz, dy, -dx); break; } pos.X += SizeX / 2; pos.Z += SizeZ / 2; curPos.Set(pos.X + startPos.X, pos.Y + startPos.Y, pos.Z + startPos.Z); string beData = val.Value; string entityclass = worldForResolve.GetBlock(BlocksUnpacked[pos]).EntityClass; if (entityclass != null) { BlockEntity be = worldForResolve.ClassRegistry.CreateBlockEntity(entityclass); if (be is IBlockEntityRotatable) { ITreeAttribute tree = DecodeBlockEntityData(beData); (be as IBlockEntityRotatable).OnTransformed(tree, angle, flipAxis); beData = StringEncodeTreeAttribute(tree); } BlockEntitiesUnpacked[pos] = beData; } } foreach (string entityData in Entities) { using (MemoryStream ms = new MemoryStream(Ascii85.Decode(entityData))) { BinaryReader reader = new BinaryReader(ms); string className = reader.ReadString(); Entity entity = worldForResolve.ClassRegistry.CreateEntity(className); entity.FromBytes(reader, false); entity.DidImportOrExport(startPos); double dx = entity.ServerPos.X - startPos.X; double dy = entity.ServerPos.Y - startPos.Y; double dz = entity.ServerPos.Z - startPos.Z; dx -= SizeX / 2; dz -= SizeZ / 2; Vec3d pos = new Vec3d(); // 90 deg: // xNew = -yOld // yNew = xOld // 180 deg: // xNew = -xOld // yNew = -yOld // 270 deg: // xNew = yOld // yNew = -xOld switch (angle) { case 90: pos.Set(-dz, dy, dx); break; case 180: pos.Set(-dx, dy, -dz); break; case 270: pos.Set(dz, dy, -dx); break; } pos.X += SizeX / 2; pos.Z += SizeZ / 2; entity.ServerPos.SetPos(startPos.X + pos.X, entity.ServerPos.Y, startPos.Z + pos.Z); entity.Pos.SetPos(startPos.X + pos.X, entity.Pos.Y, startPos.Z + pos.Z); entity.PositionBeforeFalling.Set(startPos.X + pos.X, entity.PositionBeforeFalling.Y, startPos.Z + pos.Z); EntitiesUnpacked.Add(entity); } } Pack(worldForResolve, startPos); }
public void ShortFinalBlock() { Ascii85.Decode("a"); }
public void FinalTilde() { Ascii85.Decode("~"); }
public void RoundTrip(byte[] bytes, string encoded) { Assert.That(Ascii85.Encode(bytes), Is.EqualTo(encoded)); Assert.That(Ascii85.Decode(encoded), Is.EqualTo(bytes)); }