Пример #1
0
        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));
            }
        }
Пример #2
0
	/// <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();			
	}
Пример #3
0
    /// <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();
    }
Пример #4
0
        public static string Serialize(Graph g)
        {
            var bytes      = SerializeToByteArray(g);
            var compressed = QuickLZ.compress(bytes);
            var Ascii85    = new Ascii85();

            return(Prefix + Ascii85.Encode(compressed));
        }
Пример #5
0
        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));
        }
Пример #6
0
        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));
        }
Пример #7
0
        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);
		}
Пример #9
0
        /// <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));
        }
Пример #10
0
        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);
            }
        }
Пример #12
0
	/// <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();
	}
Пример #13
0
        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));
        }
Пример #14
0
    /// <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();
    }
Пример #15
0
        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" + "~>");
        }
Пример #16
0
        /// <summary>
        /// To ASCII 85 encoded string
        /// </summary>
        /// <param name="value">Guid</param>
        /// <returns>ASCII85</returns>
        public static string ToAscii85(this Guid value)
        {
            var a = new Ascii85();

            return(a.Encode(value.ToByteArray()));
        }
Пример #17
0
        public string GetKey()
        {
            var guid = System.Guid.NewGuid();

            return(_encoder.Encode(guid.ToByteArray()));
        }
Пример #18
0
        public virtual bool Pack(IWorldAccessor world, BlockPos startPos)
        {
            Indices.Clear();
            BlockIds.Clear();
            BlockEntities.Clear();
            Entities.Clear();
            SizeX = 0;
            SizeY = 0;
            SizeZ = 0;

            int minX = int.MaxValue, minY = int.MaxValue, minZ = int.MaxValue;

            foreach (var val in BlocksUnpacked)
            {
                minX = Math.Min(minX, val.Key.X);
                minY = Math.Min(minY, val.Key.Y);
                minZ = Math.Min(minZ, val.Key.Z);

                // Store relative position and the block id
                int dx = val.Key.X - startPos.X;
                int dy = val.Key.Y - startPos.Y;
                int dz = val.Key.Z - startPos.Z;

                if (dx >= 1024 || dy >= 1024 || dz >= 1024)
                {
                    world.Logger.Warning("Export format does not support areas larger than 1024 blocks in any direction. Will not pack.");
                    return(false);
                }
            }

            foreach (var val in BlocksUnpacked)
            {
                if (val.Value == 0)
                {
                    continue;
                }

                // Store a block mapping
                BlockCodes[val.Value] = world.BlockAccessor.GetBlock(val.Value).Code;

                // Store relative position and the block id
                int dx = val.Key.X - minX;
                int dy = val.Key.Y - minY;
                int dz = val.Key.Z - minZ;

                SizeX = Math.Max(dx, SizeX);
                SizeY = Math.Max(dy, SizeY);
                SizeZ = Math.Max(dz, SizeZ);

                Indices.Add((uint)((dy << 20) | (dz << 10) | dx));
                BlockIds.Add(val.Value);
            }

            // off-by-one problem as usual. A block at x=3 and x=4 means a sizex of 2
            SizeX++;
            SizeY++;
            SizeZ++;

            foreach (var val in BlockEntitiesUnpacked)
            {
                int dx = val.Key.X - minX;
                int dy = val.Key.Y - minY;
                int dz = val.Key.Z - minZ;
                BlockEntities[(uint)((dy << 20) | (dz << 10) | dx)] = val.Value;
            }

            foreach (Entity e in EntitiesUnpacked)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    BinaryWriter writer = new BinaryWriter(ms);

                    writer.Write(world.ClassRegistry.GetEntityClassName(e.GetType()));

                    e.WillExport(startPos);
                    e.ToBytes(writer, false);
                    e.DidImportOrExport(startPos);

                    Entities.Add(Ascii85.Encode(ms.ToArray()));
                }
            }

            return(true);
        }
Пример #19
0
 public void EncodeNull()
 {
     Ascii85.Encode(null);
 }
Пример #20
0
 public void RoundTrip(byte[] bytes, string encoded)
 {
     Assert.That(Ascii85.Encode(bytes), Is.EqualTo(encoded));
     Assert.That(Ascii85.Decode(encoded), Is.EqualTo(bytes));
 }
Пример #21
0
 public static string Base85Encode(this string str)
 {
     return(Ascii85.Encode(Encoding.ASCII.GetBytes(str)));
 }
Пример #22
0
        public static string getAnswer(string Headers, byte[] Content)
        {
            string Line      = string.Empty;
            string ResHeader = string.Empty;
            int    len       = -1;

            TcpClient C = new TcpClient();

            C.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.13"), 80));
            NetworkStream NS = new NetworkStream(C.Client, false);

            NS.Write(s2b(Headers.Trim() + CRLF + CRLF), 0, s2b(Headers.Trim() + CRLF + CRLF).Length);

            if (Content != null && Content.Length > 0)
            {
                NS.Write(Content, 0, Content.Length);
                NS.Flush();
            }

            //reads all headers
            while (!string.IsNullOrEmpty(Line = rl(NS)))
            {
                ResHeader += Line + CRLF;
                if (Line.ToLower().StartsWith("content-length:"))
                {
                    try
                    {
                        len = int.Parse(Line.Split(':')[1].Trim());
                    }
                    catch
                    {
                        len = 0;
                    }
                }
            }

            //check if content of defined length is there to read
            if (len > 0)
            {
                byte[]       data = new byte[100];
                MemoryStream MS   = new MemoryStream(len);
                while (MS.Position < len)
                {
                    MS.Write(data, 0, NS.Read(data, 0, data.Length));
                }
                if (MS.Length > 0)
                {
                    Ascii85 A5 = new Ascii85();
                    ResHeader += CRLF + A5.Encode(MS.ToArray());
                }
                MS.Close();
                MS.Dispose();
            }
            //content of undefined length probably.
            //In this case, read everything until disconnect.
            if (len == -1)
            {
                byte[]       data = new byte[100];
                MemoryStream MS   = new MemoryStream();
                while (C.Connected)
                {
                    try
                    {
                        MS.Write(data, 0, NS.Read(data, 0, data.Length));
                    }
                    catch
                    {
                        //Connection closed
                    }
                }
                if (MS.Length > 0)
                {
                    Ascii85 A5 = new Ascii85();
                    ResHeader += CRLF + A5.Encode(MS.ToArray());
                }
                MS.Close();
                MS.Dispose();
            }
            NS.Close();
            NS.Dispose();

            try
            {
                C.Client.Disconnect(true);
            }
            finally
            {
                C.Close();
                C = null;
            }

            return(ResHeader);
        }