From 87de7710ae6b3a6b36b869f9d797feecbefa19aa Mon Sep 17 00:00:00 2001 From: Irmen de Jong Date: Sun, 8 Jul 2018 15:49:04 +0200 Subject: [PATCH] massive code style cleanup, c# 6 language level features --- .../Razorvine.Pyrolite/DebugHelper/Program.cs | 10 +- .../Razorvine.Pyrolite/EchoExample/Program.cs | 13 +- .../EchoExample/TestEcho.cs | 20 +- .../EchoExample/TestHandshake.cs | 27 +- .../EchoExample/TestStreaming.cs | 11 +- .../FlameExample/TestFlame.cs | 27 +- .../NamingExample/TestNaming.cs | 28 +- .../PickleExample/PickleTest.cs | 26 +- .../Pyrolite/Pickle/IObjectConstructor.cs | 1 + .../Pyrolite/Pickle/IObjectPickler.cs | 1 + .../Pyrolite/Pickle/InvalidOpcodeException.cs | 18 +- .../Pickle/Objects/AnyClassConstructor.cs | 6 +- .../Pickle/Objects/ArrayConstructor.cs | 98 +++---- .../Pickle/Objects/ByteArrayConstructor.cs | 2 +- .../Pickle/Objects/ClassDictConstructor.cs | 28 +- .../Pyrolite/Pickle/Objects/ComplexNumber.cs | 9 +- .../Pickle/Objects/DateTimeConstructor.cs | 56 ++-- .../Pickle/Objects/ExceptionConstructor.cs | 20 +- .../Pickle/Objects/StringConstructor.cs | 9 +- .../Pyrolite/Pickle/Opcodes.cs | 5 +- .../Pyrolite/Pickle/PickleException.cs | 12 +- .../Pyrolite/Pickle/PickleUtils.cs | 67 ++--- .../Pyrolite/Pickle/Pickler.cs | 211 +++++++------- .../Pyrolite/Pickle/PrettyPrint.cs | 11 +- .../Pyrolite/Pickle/PythonException.cs | 30 +- .../Pyrolite/Pickle/UnpickleStack.cs | 30 +- .../Pyrolite/Pickle/Unpickler.cs | 264 +++++++++--------- .../Pyrolite/Pyro/Config.cs | 5 +- .../Pyrolite/Pyro/DummyPyroSerializer.cs | 2 + .../Pyrolite/Pyro/FlameBuiltin.cs | 28 +- .../Pyrolite/Pyro/FlameModule.cs | 26 +- .../Pyrolite/Pyro/FlameRemoteConsole.cs | 30 +- .../Pyrolite/Pyro/IOUtil.cs | 5 +- .../Pyrolite/Pyro/Message.cs | 57 ++-- .../Pyrolite/Pyro/NameServerProxy.cs | 30 +- .../Pyrolite/Pyro/ProxyClassConstructor.cs | 24 +- .../Pyrolite/Pyro/PyroException.cs | 10 +- .../Pyrolite/Pyro/PyroExceptionPickler.cs | 31 +- .../Pyrolite/Pyro/PyroProxy.cs | 186 ++++++------ .../Pyrolite/Pyro/PyroProxyPickler.cs | 40 +-- .../Pyrolite/Pyro/PyroURI.cs | 24 +- .../Pyrolite/Pyro/PyroUriPickler.cs | 12 +- .../Pyrolite/Pyro/Serializers.cs | 24 +- .../Tests/Pickle/ArrayConstructorTests.cs | 26 +- .../Tests/Pickle/AssertUtils.cs | 19 +- .../Tests/Pickle/PickleUtilsTests.cs | 47 ++-- .../Tests/Pickle/PicklerTests.cs | 135 ++++----- .../Tests/Pickle/UnpickleComplexTests.cs | 136 ++++----- .../Tests/Pickle/UnpickleOpcodesTests.cs | 180 ++++++------ .../Tests/Pickle/UnpickleStackTests.cs | 8 +- .../Tests/Pickle/UnpicklerTests.cs | 111 ++++---- .../Tests/Pyro/MessageTests.cs | 94 ++++--- .../Tests/Pyro/SerializePyroTests.cs | 14 +- .../Tests/Pyro/SerpentSerializerTests.cs | 33 +-- 54 files changed, 1226 insertions(+), 1151 deletions(-) diff --git a/dotnet/Razorvine.Pyrolite/DebugHelper/Program.cs b/dotnet/Razorvine.Pyrolite/DebugHelper/Program.cs index 1ac90d7..995734d 100644 --- a/dotnet/Razorvine.Pyrolite/DebugHelper/Program.cs +++ b/dotnet/Razorvine.Pyrolite/DebugHelper/Program.cs @@ -10,15 +10,13 @@ namespace DebugHelper /// public static class Program { - public static void Main(string[] args) + public static void Main() { Unpickler u=new Unpickler(); - byte[] data; - object result; - + Console.WriteLine("here we go; 1"); - data=PickleUtils.str2bytes("\u0080\u0002carray\narray\nq\u0000U\u0001iq\u0001]q\u0002\u0086q\u0003Rq\u0004."); - result=u.loads(data); + var data = PickleUtils.str2bytes("\u0080\u0002carray\narray\nq\u0000U\u0001iq\u0001]q\u0002\u0086q\u0003Rq\u0004."); + var result = u.loads(data); PrettyPrint.print(result); Console.WriteLine("here we go; 2"); diff --git a/dotnet/Razorvine.Pyrolite/EchoExample/Program.cs b/dotnet/Razorvine.Pyrolite/EchoExample/Program.cs index 016d18c..1cce920 100644 --- a/dotnet/Razorvine.Pyrolite/EchoExample/Program.cs +++ b/dotnet/Razorvine.Pyrolite/EchoExample/Program.cs @@ -3,6 +3,7 @@ using System; using Razorvine.Pyro; // ReSharper disable CheckNamespace +// ReSharper disable PossibleNullReferenceException namespace Pyrolite.TestPyroEcho { @@ -11,7 +12,7 @@ namespace Pyrolite.TestPyroEcho /// public static class Program { - public static void Main(String[] args) { + public static void Main(string[] args) { char test; if(args.Length==1) @@ -21,21 +22,21 @@ public static void Main(String[] args) { test = Console.ReadLine().Trim().ToLowerInvariant()[0]; } - setConfig(); + SetConfig(); try { switch(test) { case 'e': Console.WriteLine("\r\nRunning ECHO test.\r\n"); - new TestEcho().Run(); + TestEcho.Run(); break; case 'h': Console.WriteLine("\r\nRunning HANDSHAKE test.\r\n"); - new TestHandshake().Run(); + TestHandshake.Run(); break; case 's': Console.WriteLine("\r\nRunning STREAMING test.\r\n"); - new TestStreaming().Run(); + TestStreaming.Run(); break; default: Console.Error.WriteLine("invalid choice"); @@ -48,7 +49,7 @@ public static void Main(String[] args) { Console.WriteLine("\r\nEnter to exit:"); Console.ReadLine(); } - static void setConfig() + private static void SetConfig() { string tracedir=Environment.GetEnvironmentVariable("PYRO_TRACE_DIR"); if(tracedir!=null) { diff --git a/dotnet/Razorvine.Pyrolite/EchoExample/TestEcho.cs b/dotnet/Razorvine.Pyrolite/EchoExample/TestEcho.cs index f348b79..ef7868e 100644 --- a/dotnet/Razorvine.Pyrolite/EchoExample/TestEcho.cs +++ b/dotnet/Razorvine.Pyrolite/EchoExample/TestEcho.cs @@ -14,6 +14,8 @@ namespace Pyrolite.TestPyroEcho /// /// This custom proxy adds custom annotations to the pyro messages /// +// ReSharper disable once ArrangeTypeModifiers +// ReSharper disable once UnusedMember.Global class CustomProxy : PyroProxy { public CustomProxy(PyroURI uri): base(uri) @@ -30,11 +32,11 @@ public override IDictionary annotations() /// /// Test Pyro with the Pyro echo server. /// -public class TestEcho { - private static readonly byte[] hmacKey = null; // Encoding.UTF8.GetBytes("foo"); +public static class TestEcho { + private static readonly byte[] HmacKey = null; // Encoding.UTF8.GetBytes("foo"); - public void Run() { + public static void Run() { Console.WriteLine("Testing Pyro echo server (make sure it's running, with nameserver enabled)..."); Console.WriteLine("Pyrolite version: "+Config.PYROLITE_VERSION); @@ -45,17 +47,17 @@ public void Run() { if(Config.SERIALIZER==Config.SerializerType.serpent) Console.WriteLine("note that for the serpent serializer, you need to have the Razorvine.Serpent assembly available."); - NameServerProxy ns = NameServerProxy.locateNS(null, hmacKey: hmacKey); + NameServerProxy ns = NameServerProxy.locateNS(null, hmacKey: HmacKey); using(dynamic p = new PyroProxy(ns.lookup("test.echoserver"))) { - p.pyroHmacKey=hmacKey; + p.pyroHmacKey=HmacKey; p.pyroHandshake = "banana"; // non-dynamic way of constructing a proxy is: // PyroProxy p=new PyroProxy("localhost",9999,"test.echoserver"); Console.WriteLine("echo(), param=42:"); - Object result=p.echo(42); + object result=p.echo(42); Console.WriteLine("return value:"); PrettyPrint.print(result); @@ -76,7 +78,7 @@ public void Run() { // some more examples - String s="This string is way too long. This string is way too long. This string is way too long. This string is way too long. "; + string s="This string is way too long. This string is way too long. This string is way too long. This string is way too long. "; s=s+s+s+s+s; Console.WriteLine("echo param:"); PrettyPrint.print(s); @@ -85,7 +87,7 @@ public void Run() { PrettyPrint.print(result); Console.WriteLine("dict test."); - IDictionary map = new Dictionary() + IDictionary map = new Dictionary { {"value", 42}, {"message", "hello"}, @@ -105,7 +107,7 @@ public void Run() { Debug.Assert(p2.pyroMethods.Contains("echo")); if(p2.pyroHmacKey!=null) { string hmac2 = Encoding.UTF8.GetString(p2.pyroHmacKey); - Debug.Assert(hmac2==Encoding.UTF8.GetString(hmacKey)); + Debug.Assert(hmac2==Encoding.UTF8.GetString(HmacKey)); } Console.WriteLine("remote iterator test."); diff --git a/dotnet/Razorvine.Pyrolite/EchoExample/TestHandshake.cs b/dotnet/Razorvine.Pyrolite/EchoExample/TestHandshake.cs index b3119bd..64e3509 100644 --- a/dotnet/Razorvine.Pyrolite/EchoExample/TestHandshake.cs +++ b/dotnet/Razorvine.Pyrolite/EchoExample/TestHandshake.cs @@ -5,6 +5,8 @@ using System.Collections.Generic; using Razorvine.Pyro; // ReSharper disable CheckNamespace +// ReSharper disable PossibleNullReferenceException +// ReSharper disable once InconsistentNaming namespace Pyrolite.TestPyroEcho { @@ -27,20 +29,25 @@ public override IDictionary annotations() public override void validateHandshake(object handshake_response) { // the handshake example server returns a list. - var response_list = (IList) handshake_response; - Console.WriteLine("Proxy received handshake response data: "+ string.Join(",", response_list)); + var responseList = (IList) handshake_response; + Console.WriteLine("Proxy received handshake response data: "+ string.Join(",", responseList)); } public override void responseAnnotations(IDictionary annotations, ushort msgtype) { Console.WriteLine(" Got response (type={0}). Annotations:", msgtype); foreach(var ann in annotations) { string value; - if(ann.Key=="CORR") { - value = new Guid(ann.Value).ToString(); - } else if (ann.Key=="HMAC") { - value = "[...]"; - } else { - value = ann.Value.ToString(); + switch (ann.Key) + { + case "CORR": + value = new Guid(ann.Value).ToString(); + break; + case "HMAC": + value = "[...]"; + break; + default: + value = ann.Value.ToString(); + break; } Console.WriteLine(" {0} -> {1}", ann.Key, value); } @@ -51,9 +58,9 @@ public override void responseAnnotations(IDictionary annotations /// Test Pyro with the Handshake example server to see /// how custom annotations and handshake handling is done. /// -public class TestHandshake { +public static class TestHandshake { - public void Run() { + public static void Run() { Console.WriteLine("Testing Pyro handshake and custom annotations. Make sure the server from the pyro handshake example is running."); Console.WriteLine("Pyrolite version: "+Config.PYROLITE_VERSION); diff --git a/dotnet/Razorvine.Pyrolite/EchoExample/TestStreaming.cs b/dotnet/Razorvine.Pyrolite/EchoExample/TestStreaming.cs index 57e9435..7485e63 100644 --- a/dotnet/Razorvine.Pyrolite/EchoExample/TestStreaming.cs +++ b/dotnet/Razorvine.Pyrolite/EchoExample/TestStreaming.cs @@ -4,6 +4,7 @@ using System.Collections; using Razorvine.Pyro; // ReSharper disable CheckNamespace +// ReSharper disable PossibleNullReferenceException namespace Pyrolite.TestPyroEcho { @@ -11,11 +12,11 @@ namespace Pyrolite.TestPyroEcho /// /// Test Pyro with streaming. /// -public class TestStreaming { +public static class TestStreaming { - public void Run() { + public static void Run() { - setConfig(); + SetConfig(); // Config.SERIALIZER = Config.SerializerType.pickle; Console.WriteLine("Pyrolite version: "+Config.PYROLITE_VERSION); @@ -71,8 +72,8 @@ public void Run() { } } } - - static void setConfig() + + private static void SetConfig() { string tracedir=Environment.GetEnvironmentVariable("PYRO_TRACE_DIR"); if(tracedir!=null) { diff --git a/dotnet/Razorvine.Pyrolite/FlameExample/TestFlame.cs b/dotnet/Razorvine.Pyrolite/FlameExample/TestFlame.cs index 6aa9ded..7c598c2 100644 --- a/dotnet/Razorvine.Pyrolite/FlameExample/TestFlame.cs +++ b/dotnet/Razorvine.Pyrolite/FlameExample/TestFlame.cs @@ -11,41 +11,40 @@ namespace Pyrolite.TestPyroFlame /// Test Pyro with a Flame server /// public static class TestFlame { + private static readonly byte[] HmacKey = null; - static byte[] hmacKey = null; - - public static void Main(String[] args) { + public static void Main() { try { Test(); } catch (Exception x) { Console.WriteLine("unhandled exception: {0}",x); } } - - public static void Test() { + + private static void Test() { Console.WriteLine("Testing Pyro flame server (make sure it's running on localhost 9999)..."); Console.WriteLine("Pyrolite version: "+Config.PYROLITE_VERSION); - setConfig(); + SetConfig(); using(dynamic flame=new PyroProxy("localhost",9999,"Pyro.Flame")) { - if(hmacKey!=null) flame.pyroHmacKey = hmacKey; + if(HmacKey!=null) flame.pyroHmacKey = HmacKey; Console.WriteLine("builtin:"); - using(dynamic r_max=(FlameBuiltin)flame.builtin("max")) + using(dynamic rMax=(FlameBuiltin)flame.builtin("max")) { - if(hmacKey!=null) r_max.pyroHmacKey = hmacKey; + if(HmacKey!=null) rMax.pyroHmacKey = HmacKey; - int maximum=(int)r_max(new []{22,99,1}); // invoke remote max() builtin function + int maximum=(int)rMax(new []{22,99,1}); // invoke remote max() builtin function Console.WriteLine("maximum="+maximum); } - using(dynamic r_module=(FlameModule)flame.module("socket")) + using(dynamic rModule=(FlameModule)flame.module("socket")) { - if(hmacKey!=null) r_module.pyroHmacKey = hmacKey; + if(HmacKey!=null) rModule.pyroHmacKey = HmacKey; - String hostname=(String)r_module.gethostname(); // get remote hostname + string hostname=(string)rModule.gethostname(); // get remote hostname Console.WriteLine("hostname="+hostname); } @@ -63,7 +62,7 @@ public static void Test() { } } - static void setConfig() + private static void SetConfig() { string tracedir=Environment.GetEnvironmentVariable("PYRO_TRACE_DIR"); if(tracedir!=null) { diff --git a/dotnet/Razorvine.Pyrolite/NamingExample/TestNaming.cs b/dotnet/Razorvine.Pyrolite/NamingExample/TestNaming.cs index 87e0ea9..a5f2170 100644 --- a/dotnet/Razorvine.Pyrolite/NamingExample/TestNaming.cs +++ b/dotnet/Razorvine.Pyrolite/NamingExample/TestNaming.cs @@ -1,7 +1,6 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System; -using System.Collections.Generic; using Razorvine.Pyro; // ReSharper disable CheckNamespace @@ -12,10 +11,9 @@ namespace Pyrolite.TestPyroNaming /// Test Pyro with the Pyro name server. /// public static class TestNaming { + private static readonly byte[] HmacKey = null; - static byte[] hmacKey = null; - - public static void Main(String[] args) { + public static void Main() { try { Test(); } catch (Exception x) { @@ -23,20 +21,20 @@ public static void Main(String[] args) { } Console.WriteLine("\r\nEnter to exit:"); Console.ReadLine(); } - - public static void Test() { + + private static void Test() { Console.WriteLine("Testing Pyro nameserver connection (make sure it's running with a broadcast server)..."); Console.WriteLine("Pyrolite version: "+Config.PYROLITE_VERSION); - setConfig(); + SetConfig(); // Config.SERIALIZER = Config.SerializerType.pickle; Console.WriteLine("serializer used: {0}", Config.SERIALIZER); if(Config.SERIALIZER==Config.SerializerType.serpent) Console.WriteLine("note that for the serpent serializer, you need to have the Razorvine.Serpent assembly available."); - using(NameServerProxy ns=NameServerProxy.locateNS(null, hmacKey: hmacKey)) + using(NameServerProxy ns=NameServerProxy.locateNS(null, hmacKey: HmacKey)) { Console.WriteLine("discovered ns at "+ns.hostname+":"+ns.port); ns.ping(); @@ -54,13 +52,13 @@ public static void Test() { Console.WriteLine("\nobjects registered in the name server:"); - IDictionary objects = ns.list(null, null); + var objects = ns.list(null, null); foreach(string key in objects.Keys) { Console.WriteLine(key + " --> " + objects[key]); } Console.WriteLine("\nobjects registered in the name server, with metadata:"); - IDictionary>> objectsm = ns.list_with_meta(null, null); + var objectsm = ns.list_with_meta(null, null); foreach(string key in objectsm.Keys) { var registration = objectsm[key]; Console.WriteLine(key + " --> " + registration.Item1); @@ -94,12 +92,12 @@ public static void Test() { using(PyroProxy p=new PyroProxy(ns.lookup("Pyro.NameServer"))) { - p.pyroHmacKey = hmacKey; + p.pyroHmacKey = HmacKey; p.call("ping"); } - int num_removed=ns.remove(null, "dotnet.", null); - Console.WriteLine("number of removed entries: {0}",num_removed); + int numRemoved=ns.remove(null, "dotnet.", null); + Console.WriteLine("number of removed entries: {0}",numRemoved); try { Console.WriteLine("uri=" + ns.lookup("dotnet.test")); // should fail.... @@ -110,8 +108,8 @@ public static void Test() { } } - - static void setConfig() + + private static void SetConfig() { string tracedir=Environment.GetEnvironmentVariable("PYRO_TRACE_DIR"); if(tracedir!=null) { diff --git a/dotnet/Razorvine.Pyrolite/PickleExample/PickleTest.cs b/dotnet/Razorvine.Pyrolite/PickleExample/PickleTest.cs index c325183..3c4f97f 100644 --- a/dotnet/Razorvine.Pyrolite/PickleExample/PickleTest.cs +++ b/dotnet/Razorvine.Pyrolite/PickleExample/PickleTest.cs @@ -9,26 +9,28 @@ namespace Pyrolite.PickleExample { - static class PickleTest + internal static class PickleTest { - public static void Main(string[] args) + public static void Main() { // going to pickle a c# datastructure - - var map = new Dictionary(); - map["apple"] = 42; - map["microsoft"] = "hello"; + + var map = new Dictionary + { + ["apple"] = 42, + ["microsoft"] = "hello" + }; var values = new List(); values.AddRange(new [] { 1.11, 2.22, 3.33, 4.44, 5.55} ); map["values"] = values; // You can add many other types if you like. See the readme about the type mappings. - const string PickleFilename = "testpickle.dat"; + const string pickleFilename = "testpickle.dat"; - Console.WriteLine("Writing pickle to '{0}'", PickleFilename); + Console.WriteLine("Writing pickle to '{0}'", pickleFilename); var pickler = new Pickler(true); - using(FileStream fos = new FileStream(PickleFilename, FileMode.Create)) + using(FileStream fos = new FileStream(pickleFilename, FileMode.Create)) { pickler.dump(map, fos); } @@ -39,7 +41,7 @@ public static void Main(string[] args) // the following pickle was created in Python 3.4. // it is this data: [1, 2, 3, (11, 12, 13), {'banana', 'grape', 'apple'}] - byte[] pythonpickle = new byte[] {128, 4, 149, 48, 0, 0, 0, 0, 0, 0, 0, 93, 148, 40, 75, 1, 75, 2, 75, 3, 75, 11, 75, 12, 75, 13, 135, 148, 143, 148, 40, 140, 6, 98, 97, 110, 97, 110, 97, 148, 140, 5, 103, 114, 97, 112, 101, 148, 140, 5, 97, 112, 112, 108, 101, 148, 144, 101, 46}; + byte[] pythonpickle = {128, 4, 149, 48, 0, 0, 0, 0, 0, 0, 0, 93, 148, 40, 75, 1, 75, 2, 75, 3, 75, 11, 75, 12, 75, 13, 135, 148, 143, 148, 40, 140, 6, 98, 97, 110, 97, 110, 97, 148, 140, 5, 103, 114, 97, 112, 101, 148, 140, 5, 97, 112, 112, 108, 101, 148, 144, 101, 46}; var unpickler = new Unpickler(); object result = unpickler.loads(pythonpickle); @@ -48,8 +50,8 @@ public static void Main(string[] args) int integer1 = (int)list[0]; int integer2 = (int)list[1]; int integer3 = (int)list[2]; - object[] tuple = (object[]) list[3]; - HashSet set = (HashSet) list[4]; + var tuple = (object[]) list[3]; + var set = (HashSet) list[4]; Console.WriteLine("1-3: integers: {0}, {1}, {2}", integer1, integer2, integer3); Console.WriteLine("4: tuple: ({0}, {1}, {2})", tuple[0], tuple[1], tuple[2]); Console.WriteLine("5: set: {0}", string.Join(",", set)); diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/IObjectConstructor.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/IObjectConstructor.cs index 80d0a9d..1596981 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/IObjectConstructor.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/IObjectConstructor.cs @@ -1,5 +1,6 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ +// ReSharper disable InconsistentNaming namespace Razorvine.Pickle { diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/IObjectPickler.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/IObjectPickler.cs index 9cf4951..ecf0cc9 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/IObjectPickler.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/IObjectPickler.cs @@ -1,6 +1,7 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System.IO; +// ReSharper disable InconsistentNaming namespace Razorvine.Pickle { diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/InvalidOpcodeException.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/InvalidOpcodeException.cs index a018566..c32db00 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/InvalidOpcodeException.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/InvalidOpcodeException.cs @@ -1,8 +1,5 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ -using System; -using System.Runtime.Serialization; - namespace Razorvine.Pickle { /// @@ -10,20 +7,7 @@ namespace Razorvine.Pickle /// public class InvalidOpcodeException : PickleException { - public InvalidOpcodeException() - { - } - - public InvalidOpcodeException(string message) : base(message) - { - } - - public InvalidOpcodeException(string message, Exception innerException) : base(message, innerException) - { - } - - // This constructor is needed for serialization. - protected InvalidOpcodeException(SerializationInfo info, StreamingContext context) : base(info, context) + public InvalidOpcodeException(string message) : base(message) { } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/AnyClassConstructor.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/AnyClassConstructor.cs index de93d81..cdaea08 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/AnyClassConstructor.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/AnyClassConstructor.cs @@ -10,15 +10,15 @@ namespace Razorvine.Pickle.Objects /// public class AnyClassConstructor : IObjectConstructor { - private Type type; + private readonly Type _type; public AnyClassConstructor(Type type) { - this.type = type; + _type = type; } public object construct(object[] args) { try { - return Activator.CreateInstance(type, args); + return Activator.CreateInstance(_type, args); } catch (Exception x) { throw new PickleException("problem constructing object",x); } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ArrayConstructor.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ArrayConstructor.cs index 02c1602..366f740 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ArrayConstructor.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ArrayConstructor.cs @@ -2,6 +2,7 @@ using System; using System.Collections; +using System.Diagnostics.CodeAnalysis; namespace Razorvine.Pickle.Objects { @@ -10,6 +11,9 @@ namespace Razorvine.Pickle.Objects /// Creates arrays of objects. Returns a primitive type array such as int[] if /// the objects are ints, etc. /// +[SuppressMessage("ReSharper", "InconsistentNaming")] +[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] +[SuppressMessage("ReSharper", "MemberCanBeMadeStatic.Global")] public class ArrayConstructor : IObjectConstructor { public object construct(object[] args) { @@ -19,7 +23,7 @@ public object construct(object[] args) { ArrayConstructor constructor = (ArrayConstructor) args[0]; char arraytype = ((string) args[1])[0]; int machinecodeType = (int) args[2]; - byte[] data = (byte[]) args[3]; + var data = (byte[]) args[3]; return constructor.construct(arraytype, machinecodeType, data); } if (args.Length != 2) { @@ -38,7 +42,7 @@ public object construct(object[] args) { case 'c':// character 1 -> char[] case 'u':// Unicode character 2 -> char[] { - char[] result = new char[values.Count]; + var result = new char[values.Count]; int i = 0; foreach(var c in values) { result[i++] = ((string) c)[0]; @@ -47,7 +51,7 @@ public object construct(object[] args) { } case 'b':// signed char -> sbyte[] { - sbyte[] result = new sbyte[values.Count]; + var result = new sbyte[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToSByte(c); @@ -56,7 +60,7 @@ public object construct(object[] args) { } case 'B':// unsigned char -> byte[] { - byte[] result = new byte[values.Count]; + var result = new byte[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToByte(c); @@ -65,7 +69,7 @@ public object construct(object[] args) { } case 'h':// signed short -> short[] { - short[] result = new short[values.Count]; + var result = new short[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToInt16(c); @@ -74,7 +78,7 @@ public object construct(object[] args) { } case 'H':// unsigned short -> ushort[] { - ushort[] result = new ushort[values.Count]; + var result = new ushort[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToUInt16(c); @@ -83,7 +87,7 @@ public object construct(object[] args) { } case 'i':// signed integer -> int[] { - int[] result = new int[values.Count]; + var result = new int[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToInt32(c); @@ -92,7 +96,7 @@ public object construct(object[] args) { } case 'I':// unsigned integer 4 -> uint[] { - uint[] result = new uint[values.Count]; + var result = new uint[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToUInt32(c); @@ -101,7 +105,7 @@ public object construct(object[] args) { } case 'l':// signed long -> long[] { - long[] result = new long[values.Count]; + var result = new long[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToInt64(c); @@ -110,7 +114,7 @@ public object construct(object[] args) { } case 'L':// unsigned long -> ulong[] { - ulong[] result = new ulong[values.Count]; + var result = new ulong[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToUInt64(c); @@ -119,7 +123,7 @@ public object construct(object[] args) { } case 'f':// floating point 4 -> float[] { - float[] result = new float[values.Count]; + var result = new float[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToSingle(c); @@ -128,7 +132,7 @@ public object construct(object[] args) { } case 'd':// floating point 8 -> double[] { - double[] result = new double[values.Count]; + var result = new double[values.Count]; int i = 0; foreach(var c in values) { result[i++] = Convert.ToDouble(c); @@ -185,18 +189,18 @@ public object construct(char typecode, int machinecode, byte[] data) { if (data.Length % 2 != 0) throw new PickleException("data size alignment error"); return constructCharArrayUTF16(machinecode, data); - } else { - // utf-32, 4 bytes - if (data.Length % 4 != 0) - throw new PickleException("data size alignment error"); - return constructCharArrayUTF32(machinecode, data); } + + // utf-32, 4 bytes + if (data.Length % 4 != 0) + throw new PickleException("data size alignment error"); + return constructCharArrayUTF32(machinecode, data); } case 'b':// signed integer 1 -> sbyte[] { if (machinecode != 1) throw new PickleException("for b type must be 1"); - sbyte[] result=new sbyte[data.Length]; + var result=new sbyte[data.Length]; Buffer.BlockCopy(data,0,result,0,data.Length); return result; } @@ -234,17 +238,17 @@ public object construct(char typecode, int machinecode, byte[] data) { { if (machinecode != 8 && machinecode != 9 && machinecode != 12 && machinecode != 13) throw new PickleException("for l type must be 8/9/12/13"); - if ((machinecode==8 || machinecode==9) && (data.Length % 4 != 0)) + if ((machinecode==8 || machinecode==9) && data.Length % 4 != 0) throw new PickleException("data size alignment error"); - if ((machinecode==12 || machinecode==13) && (data.Length % 8 != 0)) + if ((machinecode==12 || machinecode==13) && data.Length % 8 != 0) throw new PickleException("data size alignment error"); if(machinecode==8 || machinecode==9) { //32 bits return constructIntArrayFromInt32(machinecode, data); - } else { - //64 bits - return constructLongArrayFromInt64(machinecode, data); } + + //64 bits + return constructLongArrayFromInt64(machinecode, data); } case 'I':// unsigned integer 4 -> uint[] { @@ -258,17 +262,17 @@ public object construct(char typecode, int machinecode, byte[] data) { { if (machinecode != 6 && machinecode != 7 && machinecode != 10 && machinecode != 11) throw new PickleException("for L type must be 6/7/10/11"); - if ((machinecode==6 || machinecode==7) && (data.Length % 4 != 0)) + if ((machinecode==6 || machinecode==7) && data.Length % 4 != 0) throw new PickleException("data size alignment error"); - if ((machinecode==10 || machinecode==11) && (data.Length % 8 != 0)) + if ((machinecode==10 || machinecode==11) && data.Length % 8 != 0) throw new PickleException("data size alignment error"); if(machinecode==6 || machinecode==7) { // 32 bits return constructUIntArrayFromUInt32(machinecode, data); - } else { - // 64 bits - return constructULongArrayFromUInt64(machinecode, data); } + + // 64 bits + return constructULongArrayFromUInt64(machinecode, data); } case 'f':// floating point 4 -> float[] { @@ -292,8 +296,8 @@ public object construct(char typecode, int machinecode, byte[] data) { } protected int[] constructIntArrayFromInt32(int machinecode, byte[] data) { - int[] result=new int[data.Length/4]; - byte[] bigendian=new byte[4]; + var result=new int[data.Length/4]; + var bigendian=new byte[4]; for(int i=0; i public class ClassDictConstructor : IObjectConstructor { - - string module; - string name; + public readonly string module; + public readonly string name; public ClassDictConstructor(string module, string name) { this.module=module; @@ -31,36 +33,30 @@ public object construct(object[] args) { /// public class ClassDict : Dictionary { - private string classname; - public ClassDict(string modulename, string classname) { if(string.IsNullOrEmpty(modulename)) - this.classname = classname; + ClassName = classname; else - this.classname = modulename+"."+classname; + ClassName = modulename+"."+classname; - this.Add("__class__", this.classname); + Add("__class__", ClassName); } /// /// for the unpickler to restore state /// public void __setstate__(Hashtable values) { - this.Clear(); - this.Add("__class__", this.classname); + Clear(); + Add("__class__", ClassName); foreach(string x in values.Keys) - this.Add(x, values[x]); + Add(x, values[x]); } /// /// retrieve the (python) class name of the object that was pickled. /// - public string ClassName { - get { - return this.classname; - } - } + public string ClassName { get; } } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ComplexNumber.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ComplexNumber.cs index da3142a..9f6bf61 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ComplexNumber.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ComplexNumber.cs @@ -1,9 +1,11 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System; +using System.Diagnostics.CodeAnalysis; using System.Text; // ReSharper disable CompareOfFloatsByEqualityOperator // ReSharper disable NonReadonlyMemberInGetHashCode +// ReSharper disable UnusedMember.Global namespace Razorvine.Pickle.Objects { @@ -11,10 +13,11 @@ namespace Razorvine.Pickle.Objects /// /// An immutable Complex Number class. /// +[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public class ComplexNumber { - public double Real {get; set;} - public double Imaginary {get; set;} + public double Real {get; } + public double Imaginary {get; } public ComplexNumber(double r, double i) { Real=r; @@ -63,7 +66,7 @@ public override bool Equals(object obj) public override int GetHashCode() { - return (Real.GetHashCode()) ^ (Imaginary.GetHashCode()); + return Real.GetHashCode() ^ Imaginary.GetHashCode(); } public static bool operator ==(ComplexNumber lhs, ComplexNumber rhs) diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/DateTimeConstructor.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/DateTimeConstructor.cs index d6bd144..98c56c3 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/DateTimeConstructor.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/DateTimeConstructor.cs @@ -1,6 +1,7 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System; +using System.Diagnostics.CodeAnalysis; namespace Razorvine.Pickle.Objects { @@ -8,38 +9,40 @@ namespace Razorvine.Pickle.Objects /// /// This constructor can create various datetime related objects. /// +[SuppressMessage("ReSharper", "MergeCastWithTypeCheck")] +[SuppressMessage("ReSharper", "SuggestBaseTypeForParameter")] public class DateTimeConstructor : IObjectConstructor { public enum PythonType { - DATETIME, - DATE, - TIME, - TIMEDELTA + DateTime, + Date, + Time, + TimeDelta } - private PythonType pythontype; + private readonly PythonType _pythontype; public DateTimeConstructor(PythonType pythontype) { - this.pythontype = pythontype; + _pythontype = pythontype; } public object construct(object[] args) { - switch(this.pythontype) + switch(_pythontype) { - case PythonType.DATE: - return createDate(args); - case PythonType.TIME: - return createTime(args); - case PythonType.DATETIME: - return createDateTime(args); - case PythonType.TIMEDELTA: - return createTimedelta(args); + case PythonType.Date: + return CreateDate(args); + case PythonType.Time: + return CreateTime(args); + case PythonType.DateTime: + return CreateDateTime(args); + case PythonType.TimeDelta: + return CreateTimedelta(args); default: throw new PickleException("invalid object type"); } } - private TimeSpan createTimedelta(object[] args) { + private static TimeSpan CreateTimedelta(object[] args) { // python datetime.timedelta -> TimeSpan // args is a tuple of 3 ints: days,seconds,microseconds if (args.Length != 3) @@ -50,16 +53,17 @@ private TimeSpan createTimedelta(object[] args) { return new TimeSpan(days, 0, 0, seconds, micro/1000); } - private DateTime createDateTime(object[] args) { + private static DateTime CreateDateTime(object[] args) { // python datetime.time --> DateTime // args is 10 bytes: yhi, ylo, month, day, hour, minute, second, ms1, ms2, ms3 // (can be String or byte[]) // alternate constructor is with 7 integer arguments: year, month, day, hour, minute, second, microseconds - int yhi, ylo, year, month, day, hour, minute, second, microsec; + int yhi, ylo; + int month, day, hour, minute, second, microsec; if(args.Length==7) { - year = (int)args[0]; + int year = (int)args[0]; month = (int)args[1]; day = (int)args[2]; hour = (int)args[3]; @@ -88,12 +92,12 @@ private DateTime createDateTime(object[] args) { int ms3 = parameters[9]; microsec = ((ms1 << 8) | ms2) << 8 | ms3; } else { - byte[] parameters=(byte[])args[0]; + var parameters=(byte[])args[0]; if (parameters.Length != 10) throw new PickleException("invalid pickle data for datetime; expected arg of length 10, got length "+parameters.Length); yhi=parameters[0]&0xff; ylo=parameters[1]&0xff; - month=(parameters[2]&0xff); + month=parameters[2]&0xff; day=parameters[3]&0xff; hour=parameters[4]&0xff; minute=parameters[5]&0xff; @@ -106,7 +110,7 @@ private DateTime createDateTime(object[] args) { return new DateTime(yhi * 256 + ylo, month, day, hour, minute, second, microsec/1000); } - private TimeSpan createTime(object[] args) { + private static TimeSpan CreateTime(object[] args) { // python datetime.time --> TimeSpan since midnight // args is 6 bytes: hour, minute, second, ms1,ms2,ms3 (String or byte[]) // alternate constructor passes 4 integers args: hour, minute, second, microsecond) @@ -133,7 +137,7 @@ private TimeSpan createTime(object[] args) { int ms3 = parameters[5]; microsec = ((ms1 << 8) | ms2) << 8 | ms3; } else { - byte[] parameters=(byte[])args[0]; + var parameters=(byte[])args[0]; if (parameters.Length != 6) throw new PickleException("invalid pickle data for datetime; expected arg of length 6, got length "+parameters.Length); hour=parameters[0]&0xff; @@ -147,7 +151,7 @@ private TimeSpan createTime(object[] args) { return new TimeSpan(0, hour, minute, second, microsec/1000); } - private DateTime createDate(object[] args) { + private static DateTime CreateDate(object[] args) { // python datetime.date --> DateTime // args is a string of 4 bytes yhi, ylo, month, day (String or byte[]) if (args.Length != 1) @@ -162,12 +166,12 @@ private DateTime createDate(object[] args) { month = parameters[2]; day = parameters[3]; } else { - byte[] parameters=(byte[])args[0]; + var parameters=(byte[])args[0]; if (parameters.Length != 4) throw new PickleException("invalid pickle data for date; expected arg of length 4, got length "+parameters.Length); yhi=parameters[0]&0xff; ylo=parameters[1]&0xff; - month=(parameters[2]&0xff); + month=parameters[2]&0xff; day=parameters[3]&0xff; } return new DateTime(yhi*256+ylo, month, day); diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ExceptionConstructor.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ExceptionConstructor.cs index 39708c7..c0c7fe3 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ExceptionConstructor.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/ExceptionConstructor.cs @@ -12,34 +12,34 @@ namespace Razorvine.Pickle.Objects /// public class ExceptionConstructor : IObjectConstructor { - private readonly string pythonExceptionType; - private readonly Type type; + private readonly string _pythonExceptionType; + private readonly Type _type; public ExceptionConstructor(Type type, string module, string name) { if(!string.IsNullOrEmpty(module)) - pythonExceptionType = module+"."+name; + _pythonExceptionType = module+"."+name; else - pythonExceptionType = name; - this.type = type; + _pythonExceptionType = name; + _type = type; } public object construct(object[] args) { try { - if(!string.IsNullOrEmpty(pythonExceptionType)) { + if(!string.IsNullOrEmpty(_pythonExceptionType)) { // put the python exception type somewhere in the message if(args==null || args.Length==0) { - args = new object[] { "["+pythonExceptionType+"]" }; + args = new object[] { "["+_pythonExceptionType+"]" }; } else { string msg = (string)args[0]; - msg = string.Format("[{0}] {1}", pythonExceptionType, msg); + msg = $"[{_pythonExceptionType}] {msg}"; args = new object[] {msg}; } } - object ex = Activator.CreateInstance(this.type, args); + object ex = Activator.CreateInstance(_type, args); PropertyInfo prop=ex.GetType().GetProperty("PythonExceptionType"); if(prop!=null) { - prop.SetValue(ex, pythonExceptionType, null); + prop.SetValue(ex, _pythonExceptionType, null); } return ex; } catch (Exception x) { diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/StringConstructor.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/StringConstructor.cs index 4ed4e4e..3530e72 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/StringConstructor.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Objects/StringConstructor.cs @@ -1,5 +1,6 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ +// ReSharper disable UnusedMember.Global namespace Razorvine.Pickle.Objects { @@ -14,11 +15,13 @@ public object construct(object[] args) { if(args.Length==0) { return ""; - } else if(args.Length==1 && args[0] is string) { + } + + if(args.Length==1 && args[0] is string) { return (string)args[0]; - } else { - throw new PickleException("invalid string constructor arguments"); } + + throw new PickleException("invalid string constructor arguments"); } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Opcodes.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Opcodes.cs index 3ab28b7..6dd1059 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Opcodes.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Opcodes.cs @@ -1,5 +1,7 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ +using System.Diagnostics.CodeAnalysis; + namespace Razorvine.Pickle { @@ -9,7 +11,8 @@ namespace Razorvine.Pickle /// here is in kind-of alphabetical order of 1-character pickle code. /// pickletools groups them by purpose. /// -public class Opcodes { +[SuppressMessage("ReSharper", "InconsistentNaming")] +public static class Opcodes { // protocol 0 and 1 public const byte MARK = (byte)'('; // push special markobject on stack diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PickleException.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PickleException.cs index 1769341..b4439e7 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PickleException.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PickleException.cs @@ -1,7 +1,6 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System; -using System.Runtime.Serialization; namespace Razorvine.Pickle { @@ -10,21 +9,12 @@ namespace Razorvine.Pickle /// public class PickleException : Exception { - public PickleException() - { - } - - public PickleException(string message) : base(message) + public PickleException(string message) : base(message) { } public PickleException(string message, Exception innerException) : base(message, innerException) { } - - // This constructor is needed for serialization. - protected PickleException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PickleUtils.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PickleUtils.cs index e8cfb2c..85c94d7 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PickleUtils.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PickleUtils.cs @@ -3,6 +3,8 @@ using System; using System.IO; using System.Text; +// ReSharper disable InconsistentNaming +// ReSharper disable InvertIf namespace Razorvine.Pickle { @@ -12,17 +14,10 @@ namespace Razorvine.Pickle /// public static class PickleUtils { - /** - * read a line of text, excluding the terminating LF char - */ - public static string readline(Stream input) { - return readline(input, false); - } - /** * read a line of text, possibly including the terminating LF char */ - public static string readline(Stream input, bool includeLF) { + public static string readline(Stream input, bool includeLF = false) { StringBuilder sb = new StringBuilder(); while (true) { int c = input.ReadByte(); @@ -54,7 +49,7 @@ public static byte readbyte(Stream input) { * read a number of signed bytes */ public static byte[] readbytes(Stream input, int n) { - byte[] buffer = new byte[n]; + var buffer = new byte[n]; readbytes_into(input, buffer, 0, n); return buffer; } @@ -91,27 +86,25 @@ public static void readbytes_into(Stream input, byte[] buffer, int offset, int l public static int bytes_to_integer(byte[] bytes) { return bytes_to_integer(bytes, 0, bytes.Length); } - public static int bytes_to_integer(byte[] bytes, int offset, int size) { + public static int bytes_to_integer(byte[] bytes, int offset, int size) + { // this operates on little-endian bytes - - if (size == 2) { - // 2-bytes unsigned int - if(!BitConverter.IsLittleEndian) { + + switch (size) + { + case 2: + // 2-bytes unsigned int + if (BitConverter.IsLittleEndian) return BitConverter.ToUInt16(bytes, offset); // need to byteswap because the converter needs big-endian... - byte[] bigendian=new byte[] {bytes[1+offset], bytes[0+offset]}; - return BitConverter.ToUInt16(bigendian, 0); - } - return BitConverter.ToUInt16(bytes,offset); - } else if (size == 4) { - // 4-bytes signed int - if(!BitConverter.IsLittleEndian) { + return BitConverter.ToUInt16(new[] {bytes[1+offset], bytes[0+offset]}, 0); + case 4: + // 4-bytes signed int + if (BitConverter.IsLittleEndian) return BitConverter.ToInt32(bytes, offset); // need to byteswap because the converter needs big-endian... - byte[] bigendian=new byte[] {bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset]}; - return BitConverter.ToInt32(bigendian, 0); - } - return BitConverter.ToInt32(bytes,offset); - } else - throw new PickleException("invalid amount of bytes to convert to int: " + size); + return BitConverter.ToInt32(new[] {bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset]}, 0); + default: + throw new PickleException("invalid amount of bytes to convert to int: " + size); + } } /** @@ -124,7 +117,7 @@ public static long bytes_to_long(byte[] bytes, int offset) { return BitConverter.ToInt64(bytes, offset); } // need to byteswap because the converter needs big-endian... - byte[] bigendian=new byte[] {bytes[7+offset], bytes[6+offset], bytes[5+offset], bytes[4+offset], bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset]}; + byte[] bigendian={bytes[7+offset], bytes[6+offset], bytes[5+offset], bytes[4+offset], bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset]}; return BitConverter.ToInt64(bigendian, 0); } @@ -138,7 +131,7 @@ public static uint bytes_to_uint(byte[] bytes, int offset) { return BitConverter.ToUInt32(bytes, offset); } // need to byteswap because the converter needs big-endian... - byte[] bigendian=new byte[] {bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset]}; + byte[] bigendian={bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset]}; return BitConverter.ToUInt32(bigendian, 0); } @@ -146,7 +139,7 @@ public static uint bytes_to_uint(byte[] bytes, int offset) { * Convert a signed integer to its 4-byte representation. (little endian) */ public static byte[] integer_to_bytes(int i) { - byte[] bytes=BitConverter.GetBytes(i); + var bytes=BitConverter.GetBytes(i); if(!BitConverter.IsLittleEndian) { // reverse the bytes to make them little endian Array.Reverse(bytes); @@ -158,7 +151,7 @@ public static byte[] integer_to_bytes(int i) { * Convert a double to its 8-byte representation (big endian). */ public static byte[] double_to_bytes_bigendian(double d) { - byte[] bytes=BitConverter.GetBytes(d); + var bytes=BitConverter.GetBytes(d); if(BitConverter.IsLittleEndian) { // reverse the bytes to make them big endian for the output Array.Reverse(bytes); @@ -175,7 +168,7 @@ public static double bytes_bigendian_to_double(byte[] bytes, int offset) { } if(BitConverter.IsLittleEndian) { // reverse the bytes to make them littleendian for the bitconverter - byte[] littleendian=new byte[] { bytes[7+offset], bytes[6+offset], bytes[5+offset], bytes[4+offset], bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset] }; + byte[] littleendian={ bytes[7+offset], bytes[6+offset], bytes[5+offset], bytes[4+offset], bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset] }; return BitConverter.ToDouble(littleendian,0); } return BitConverter.ToDouble(bytes,offset); @@ -190,7 +183,7 @@ public static float bytes_bigendian_to_float(byte[] bytes, int offset) { } if(BitConverter.IsLittleEndian) { // reverse the bytes to make them littleendian for the bitconverter - byte[] littleendian=new byte[] { bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset] }; + byte[] littleendian={ bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset] }; return BitConverter.ToSingle(littleendian,0); } return BitConverter.ToSingle(bytes,offset); @@ -208,7 +201,7 @@ public static long decode_long(byte[] data) { throw new PickleException("value to large for long, biginteger needed"); if( data.Length<8) { // bitconverter requires exactly 8 bytes so we need to extend it - byte[] larger=new byte[8]; + var larger=new byte[8]; Array.Copy(data,larger,data.Length); // check if we need to sign-extend (if the original number was negative) @@ -243,7 +236,7 @@ public static string rawStringFromBytes(byte[] data) { * Convert a string to a byte array, no encoding is used. String must only contain characters <256. */ public static byte[] str2bytes(string str) { - byte[] b=new byte[str.Length]; + var b=new byte[str.Length]; for(int i=0; i255) throw new ArgumentException("string contained a char > 255, cannot convert to bytes"); @@ -291,7 +284,7 @@ public static string decode_escaped(string str) { default: if(str.Length>80) str=str.Substring(0, 80); - throw new PickleException("invalid escape sequence char \'"+(c2)+"\' in string \""+str+" [...]\" (possibly truncated)"); + throw new PickleException("invalid escape sequence char \'"+c2+"\' in string \""+str+" [...]\" (possibly truncated)"); } } else { sb.Append(str[i]); @@ -338,7 +331,7 @@ public static string decode_unicode_escaped(string str) { default: if(str.Length>80) str=str.Substring(0, 80); - throw new PickleException("invalid escape sequence char \'"+(c2)+"\' in string \""+str+" [...]\" (possibly truncated)"); + throw new PickleException("invalid escape sequence char \'"+c2+"\' in string \""+str+" [...]\" (possibly truncated)"); } } else { sb.Append(str[i]); diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Pickler.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Pickler.cs index 3b7dc6f..44c5412 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Pickler.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Pickler.cs @@ -3,6 +3,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; @@ -10,6 +11,10 @@ using System.Text; // ReSharper disable MemberCanBePrivate.Global // ReSharper disable MemberInitializerValueIgnored +// ReSharper disable InconsistentNaming +// ReSharper disable LoopCanBeConvertedToQuery +// ReSharper disable InvertIf +// ReSharper disable SuggestBaseTypeForParameter namespace Razorvine.Pickle { @@ -22,14 +27,15 @@ namespace Razorvine.Pickle /// public class Pickler : IDisposable { + // ReSharper disable once UnusedMember.Global public static int HIGHEST_PROTOCOL = 2; protected const int MAX_RECURSE_DEPTH = 200; protected Stream outs; protected int recurse; // recursion level - protected int PROTOCOL = 2; - protected static IDictionary customPicklers = new Dictionary(); - protected bool useMemo=true; + protected const int PROTOCOL = 2; + protected static readonly IDictionary customPicklers = new Dictionary(); + protected readonly bool useMemo=true; protected IDictionary memo; // maps objects to memo index /** @@ -85,7 +91,7 @@ public void dump(object o, Stream stream) { if(useMemo) memo = new Dictionary(); outs.WriteByte(Opcodes.PROTO); - outs.WriteByte((byte)PROTOCOL); + outs.WriteByte(PROTOCOL); save(o); memo = null; // get rid of the memo table outs.WriteByte(Opcodes.STOP); @@ -131,7 +137,7 @@ public void save(object o) { * Only works for hashable objects */ protected void WriteMemo(object obj) { - if(!this.useMemo) + if(!useMemo) return; if(!memo.ContainsKey(obj)) { @@ -145,7 +151,7 @@ protected void WriteMemo(object obj) { else { outs.WriteByte(Opcodes.LONG_BINPUT); - byte[] index_bytes = PickleUtils.integer_to_bytes(memo_index); + var index_bytes = PickleUtils.integer_to_bytes(memo_index); outs.Write(index_bytes, 0, 4); } } @@ -155,7 +161,7 @@ protected void WriteMemo(object obj) { * Check the memo table and output a memo lookup if the object is found */ private bool LookupMemo(Type objectType, object obj) { - if(!this.useMemo) + if(!useMemo) return false; if(!objectType.IsPrimitive) { @@ -170,7 +176,7 @@ private bool LookupMemo(Type objectType, object obj) { else { outs.WriteByte(Opcodes.LONG_BINGET); - byte[] index_bytes = PickleUtils.integer_to_bytes(memo_index); + var index_bytes = PickleUtils.integer_to_bytes(memo_index); outs.Write(index_bytes, 0, 4); } return true; @@ -186,7 +192,7 @@ private bool dispatch(Type t, object o) { // is it a primitive array? if(o is Array) { Type componentType=t.GetElementType(); - if(componentType.IsPrimitive) { + if(componentType != null && componentType.IsPrimitive) { put_arrayOfPrimitives(componentType, o); } else { put_arrayOfObjects((object[])o); @@ -196,7 +202,7 @@ private bool dispatch(Type t, object o) { // first the primitive types if(o is bool) { - put_bool((Boolean)o); + put_bool((bool)o); return true; } if(o is byte) { @@ -247,14 +253,15 @@ private bool dispatch(Type t, object o) { // check registry IObjectPickler custompickler = getCustomPickler(t); if(custompickler!=null) { - custompickler.pickle(o, this.outs, this); + custompickler.pickle(o, outs, this); WriteMemo(o); return true; } // more complex types - if(o is string) { - put_string((String)o); + var s = o as string; + if(s != null) { + put_string(s); return true; } if(o is decimal) { @@ -273,16 +280,22 @@ private bool dispatch(Type t, object o) { put_set((IEnumerable)o); return true; } - if(o is IDictionary) { - put_map((IDictionary)o); + + var dictionary = o as IDictionary; + if(dictionary != null) { + put_map(dictionary); return true; } - if(o is IList) { - put_enumerable((IList)o); + + var list = o as IList; + if(list != null) { + put_enumerable(list); return true; } - if(o is IEnumerable) { - put_enumerable((IEnumerable)o); + + var enumerable = o as IEnumerable; + if(enumerable != null) { + put_enumerable(enumerable); return true; } if(o is Enum) { @@ -310,6 +323,7 @@ private bool dispatch(Type t, object o) { return false; } + [SuppressMessage("ReSharper", "MemberCanBeMadeStatic.Global")] protected IObjectPickler getCustomPickler(Type t) { IObjectPickler pickler; @@ -327,15 +341,15 @@ protected IObjectPickler getCustomPickler(Type t) return null; } - bool hasPublicProperties(object o) + private static bool hasPublicProperties(object o) { - PropertyInfo[] props=o.GetType().GetProperties(); + var props=o.GetType().GetProperties(); return props.Length>0; } - - void put_datetime(DateTime dt) { + + private void put_datetime(DateTime dt) { outs.WriteByte(Opcodes.GLOBAL); - byte[] bytes=Encoding.Default.GetBytes("datetime\ndatetime\n"); + var bytes=Encoding.Default.GetBytes("datetime\ndatetime\n"); outs.Write(bytes,0,bytes.Length); outs.WriteByte(Opcodes.MARK); save(dt.Year); @@ -349,10 +363,10 @@ void put_datetime(DateTime dt) { outs.WriteByte(Opcodes.REDUCE); WriteMemo(dt); } - - void put_timespan(TimeSpan ts) { + + private void put_timespan(TimeSpan ts) { outs.WriteByte(Opcodes.GLOBAL); - byte[] bytes=Encoding.Default.GetBytes("datetime\ntimedelta\n"); + var bytes=Encoding.Default.GetBytes("datetime\ntimedelta\n"); outs.Write(bytes,0,bytes.Length); save(ts.Days); save(ts.Hours*3600+ts.Minutes*60+ts.Seconds); @@ -362,7 +376,7 @@ void put_timespan(TimeSpan ts) { WriteMemo(ts); } - void put_enumerable(IEnumerable list) { + private void put_enumerable(IEnumerable list) { outs.WriteByte(Opcodes.EMPTY_LIST); WriteMemo(list); outs.WriteByte(Opcodes.MARK); @@ -372,7 +386,7 @@ void put_enumerable(IEnumerable list) { outs.WriteByte(Opcodes.APPENDS); } - void put_map(IDictionary o) { + private void put_map(IDictionary o) { outs.WriteByte(Opcodes.EMPTY_DICT); WriteMemo(o); outs.WriteByte(Opcodes.MARK); @@ -383,9 +397,9 @@ void put_map(IDictionary o) { outs.WriteByte(Opcodes.SETITEMS); } - void put_set(IEnumerable o) { + private void put_set(IEnumerable o) { outs.WriteByte(Opcodes.GLOBAL); - byte[] output=Encoding.ASCII.GetBytes("__builtin__\nset\n"); + var output=Encoding.ASCII.GetBytes("__builtin__\nset\n"); outs.Write(output,0,output.Length); outs.WriteByte(Opcodes.EMPTY_LIST); outs.WriteByte(Opcodes.MARK); @@ -398,60 +412,69 @@ void put_set(IEnumerable o) { WriteMemo(o); // sets cannot contain self-references (because not hashable) so it is fine to put this at the end } - void put_arrayOfObjects(object[] array) { - // 0 objects->EMPTYTUPLE - // 1 object->TUPLE1 - // 2 objects->TUPLE2 - // 3 objects->TUPLE3 - // 4 or more->MARK+items+TUPLE - if(array.Length==0) { - outs.WriteByte(Opcodes.EMPTY_TUPLE); - } else if(array.Length==1) { - if(array[0]==array) - throw new PickleException("recursive array not supported, use list"); - save(array[0]); - outs.WriteByte(Opcodes.TUPLE1); - } else if(array.Length==2) { - if(array[0]==array || array[1]==array) - throw new PickleException("recursive array not supported, use list"); - save(array[0]); - save(array[1]); - outs.WriteByte(Opcodes.TUPLE2); - } else if(array.Length==3) { - if(array[0]==array || array[1]==array || array[2]==array) - throw new PickleException("recursive array not supported, use list"); - save(array[0]); - save(array[1]); - save(array[2]); - outs.WriteByte(Opcodes.TUPLE3); - } else { - outs.WriteByte(Opcodes.MARK); - foreach(object o in array) { - if(o==array) + private void put_arrayOfObjects(object[] array) + { + switch (array.Length) + { + // 0 objects->EMPTYTUPLE + // 1 object->TUPLE1 + // 2 objects->TUPLE2 + // 3 objects->TUPLE3 + // 4 or more->MARK+items+TUPLE + case 0: + outs.WriteByte(Opcodes.EMPTY_TUPLE); + break; + case 1: + if(array[0]==array) throw new PickleException("recursive array not supported, use list"); - save(o); - } - outs.WriteByte(Opcodes.TUPLE); + save(array[0]); + outs.WriteByte(Opcodes.TUPLE1); + break; + case 2: + if(array[0]==array || array[1]==array) + throw new PickleException("recursive array not supported, use list"); + save(array[0]); + save(array[1]); + outs.WriteByte(Opcodes.TUPLE2); + break; + case 3: + if(array[0]==array || array[1]==array || array[2]==array) + throw new PickleException("recursive array not supported, use list"); + save(array[0]); + save(array[1]); + save(array[2]); + outs.WriteByte(Opcodes.TUPLE3); + break; + default: + outs.WriteByte(Opcodes.MARK); + foreach(object o in array) { + if(o==array) + throw new PickleException("recursive array not supported, use list"); + save(o); + } + outs.WriteByte(Opcodes.TUPLE); + break; } + WriteMemo(array); // tuples cannot contain self-references so it is fine to put this at the end } - void put_arrayOfPrimitives(Type t, object array) { + private void put_arrayOfPrimitives(Type t, object array) { byte[] output; if(t==typeof(bool)) { // a bool[] isn't written as an array but rather as a tuple - bool[] source=(bool[])array; + var source=(bool[])array; // this is stupid, but seems to be necessary because you can't cast a bool[] to an object[] - object[] boolarray=new object[source.Length]; + var boolarray=new object[source.Length]; Array.Copy(source, boolarray, source.Length); put_arrayOfObjects(boolarray); return; } if(t==typeof(char)) { // a char[] isn't written as an array but rather as a unicode string - String s=new String((char[])array); + string s=new string((char[])array); put_string(s); return; } @@ -547,10 +570,10 @@ void put_arrayOfPrimitives(Type t, object array) { WriteMemo(array); // array of primitives can by definition never be recursive, so okay to put this at the end } - void put_decimal(decimal d) { + private void put_decimal(decimal d) { //"cdecimal\nDecimal\nU\n12345.6789\u0085R." outs.WriteByte(Opcodes.GLOBAL); - byte[] output=Encoding.ASCII.GetBytes("decimal\nDecimal\n"); + var output=Encoding.ASCII.GetBytes("decimal\nDecimal\n"); outs.Write(output,0,output.Length); put_string(Convert.ToString(d, CultureInfo.InvariantCulture)); outs.WriteByte(Opcodes.TUPLE1); @@ -558,22 +581,22 @@ void put_decimal(decimal d) { WriteMemo(d); } - void put_string(string str) { - byte[] encoded=Encoding.UTF8.GetBytes(str); + private void put_string(string str) { + var encoded=Encoding.UTF8.GetBytes(str); outs.WriteByte(Opcodes.BINUNICODE); - byte[] output=PickleUtils.integer_to_bytes(encoded.Length); + var output=PickleUtils.integer_to_bytes(encoded.Length); outs.Write(output,0,output.Length); outs.Write(encoded,0,encoded.Length); WriteMemo(str); } - void put_float(double d) { + private void put_float(double d) { outs.WriteByte(Opcodes.BINFLOAT); - byte[] output=PickleUtils.double_to_bytes_bigendian(d); + var output=PickleUtils.double_to_bytes_bigendian(d); outs.Write(output,0,output.Length); - } + } - void put_long(long v) { + private void put_long(long v) { byte[] output; // choose optimal representation // first check 1 and 2-byte unsigned ints: @@ -607,29 +630,27 @@ void put_long(long v) { outs.Write(output, 0, output.Length); outs.WriteByte((byte)'\n'); } - - void put_ulong(ulong u) { + + private void put_ulong(ulong u) { if(u<=long.MaxValue) { long l=(long)u; put_long(l); } else { // ulong too big for a signed long, store it as text instead. outs.WriteByte(Opcodes.INT); - byte[] output=Encoding.ASCII.GetBytes(u.ToString()); + var output=Encoding.ASCII.GetBytes(u.ToString()); outs.Write(output, 0, output.Length); outs.WriteByte((byte)'\n'); } } - - void put_bool(bool b) { - if(b) - outs.WriteByte(Opcodes.NEWTRUE); - else - outs.WriteByte(Opcodes.NEWFALSE); + + private void put_bool(bool b) + { + outs.WriteByte(b ? Opcodes.NEWTRUE : Opcodes.NEWFALSE); } - void put_objwithproperties(object o) { - PropertyInfo[] properties=o.GetType().GetProperties(); + private void put_objwithproperties(object o) { + var properties=o.GetType().GetProperties(); var map=new Dictionary(); foreach(var propinfo in properties) { if(propinfo.CanRead) { @@ -649,10 +670,10 @@ void put_objwithproperties(object o) { save(map); } - void put_serializable(Type t, object o) + private void put_serializable(Type t, object o) { var map=new Dictionary(); - FieldInfo[] fields = t.GetFields(); + var fields = t.GetFields(); foreach(var field in fields) { if(field.GetCustomAttribute(typeof(NonSerializedAttribute))==null) { string name=field.Name; @@ -663,7 +684,7 @@ void put_serializable(Type t, object o) } } } - PropertyInfo[] properties=t.GetProperties(); + var properties=t.GetProperties(); foreach(var propinfo in properties) { if(propinfo.CanRead) { string name=propinfo.Name; @@ -682,9 +703,9 @@ void put_serializable(Type t, object o) save(map); } - void put_datacontract(Type t, object o, DataContractAttribute dca) + private void put_datacontract(Type t, object o, DataContractAttribute dca) { - FieldInfo[] fields = t.GetFields(); + var fields = t.GetFields(); var map=new Dictionary(); foreach(var field in fields) { DataMemberAttribute dma = (DataMemberAttribute) field.GetCustomAttribute(typeof(DataMemberAttribute)); @@ -697,7 +718,7 @@ void put_datacontract(Type t, object o, DataContractAttribute dca) } } } - PropertyInfo[] properties=t.GetProperties(); + var properties=t.GetProperties(); foreach(var propinfo in properties) { if(propinfo.CanRead && propinfo.GetCustomAttribute(typeof(DataMemberAttribute))!=null) { string name=propinfo.Name; @@ -722,7 +743,7 @@ void put_datacontract(Type t, object o, DataContractAttribute dca) public void Dispose() { - this.close(); + close(); } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PrettyPrint.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PrettyPrint.cs index 4a81185..12c0812 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PrettyPrint.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PrettyPrint.cs @@ -2,6 +2,7 @@ using System; using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.IO; namespace Razorvine.Pickle @@ -11,7 +12,9 @@ namespace Razorvine.Pickle /// Object output pretty printing, to help with the test scripts. /// Nothing fancy, just a simple readable output format for a handfull of classes. /// -public class PrettyPrint { +[SuppressMessage("ReSharper", "InconsistentNaming")] +[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] +public static class PrettyPrint { public static string printToString(object o) { StringWriter sw=new StringWriter(); @@ -34,9 +37,9 @@ public static void print(object o, TextWriter w, bool typeheader) { return; } - if (o is IDictionary) { + var map = o as IDictionary; + if (map != null) { if(typeheader) w.WriteLine("hashtable"); - IDictionary map=(IDictionary)o; w.Write("{"); foreach(object key in map.Keys) { w.Write(key+"="+map[key]+", "); @@ -60,7 +63,7 @@ public static void print(object o, TextWriter w, bool typeheader) { w.Flush(); } - static void writeEnumerable(object o, TextWriter w) + public static void writeEnumerable(object o, TextWriter w) { IEnumerable e=(IEnumerable)o; w.Write("["); diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PythonException.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PythonException.cs index 987be58..5d2a888 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PythonException.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/PythonException.cs @@ -2,54 +2,46 @@ using System; using System.Collections; -using System.Runtime.Serialization; +using System.Diagnostics.CodeAnalysis; using System.Text; // ReSharper disable UnusedParameter.Local +// ReSharper disable MemberCanBePrivate.Global +// ReSharper disable UnusedAutoPropertyAccessor.Global namespace Razorvine.Pickle { /// /// Exception thrown that represents a certain Python exception. /// + [SuppressMessage("ReSharper", "InconsistentNaming")] public class PythonException : Exception { - public string _pyroTraceback {get;set;} + public string _pyroTraceback {get; set;} public string PythonExceptionType {get; set;} - public PythonException() - { - } - - public PythonException(string message) : base(message) - { - } - - public PythonException(string message, Exception innerException) : base(message, innerException) + public PythonException(string message) : base(message) { } // special constructor for UnicodeDecodeError - public PythonException(String encoding, byte[] data, int i1, int i2, String message) + // ReSharper disable once UnusedMember.Global + public PythonException(string encoding, byte[] data, int i1, int i2, string message) :base("UnicodeDecodeError: "+encoding+": "+message) { } - // This constructor is needed for serialization. - protected PythonException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - /// /// for the unpickler to restore state /// + // ReSharper disable once UnusedMember.Global public void __setstate__(Hashtable values) { if(!values.ContainsKey("_pyroTraceback")) return; object tb=values["_pyroTraceback"]; // if the traceback is a list of strings, create one string from it - if(tb is ICollection) { + var tbcoll = tb as ICollection; + if(tbcoll != null) { StringBuilder sb=new StringBuilder(); - ICollection tbcoll=(ICollection)tb; foreach(object line in tbcoll) { sb.Append(line); } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/UnpickleStack.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/UnpickleStack.cs index f7b771b..7c17e63 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/UnpickleStack.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/UnpickleStack.cs @@ -1,6 +1,7 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System.Collections; +using System.Diagnostics.CodeAnalysis; namespace Razorvine.Pickle { @@ -8,34 +9,35 @@ namespace Razorvine.Pickle /// /// Helper type that represents the unpickler working stack. /// +[SuppressMessage("ReSharper", "InconsistentNaming")] public class UnpickleStack { - private ArrayList stack; - public object MARKER; + private readonly ArrayList _stack; + public readonly object MARKER; public UnpickleStack() { - stack = new ArrayList(); + _stack = new ArrayList(); MARKER = new object(); // any new unique object } public void add(object o) { - stack.Add(o); + _stack.Add(o); } public void add_mark() { - stack.Add(MARKER); + _stack.Add(MARKER); } public object pop() { - int size = stack.Count; - var result = this.stack[size - 1]; - this.stack.RemoveAt(size-1); + int size = _stack.Count; + var result = _stack[size - 1]; + _stack.RemoveAt(size-1); return result; } public ArrayList pop_all_since_marker() { ArrayList result = new ArrayList(); object o = pop(); - while (o != this.MARKER) { + while (o != MARKER) { result.Add(o); o = pop(); } @@ -45,20 +47,20 @@ public ArrayList pop_all_since_marker() { } public object peek() { - return this.stack[this.stack.Count-1]; + return _stack[_stack.Count-1]; } public void trim() { - this.stack.TrimToSize(); + _stack.TrimToSize(); } public int size() { - return this.stack.Count; + return _stack.Count; } public void clear() { - this.stack.Clear(); - this.stack.TrimToSize(); + _stack.Clear(); + _stack.TrimToSize(); } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Unpickler.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Unpickler.cs index c83945d..6e7be04 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Unpickler.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pickle/Unpickler.cs @@ -3,6 +3,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; @@ -18,33 +19,39 @@ namespace Razorvine.Pickle /// This class is NOT threadsafe! (Don't use the same unpickler from different threads) /// See the README.txt for a table with the type mappings. /// +[SuppressMessage("ReSharper", "InconsistentNaming")] +[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] +[SuppressMessage("ReSharper", "InvertIf")] public class Unpickler : IDisposable { protected const int HIGHEST_PROTOCOL = 4; - protected IDictionary memo; + protected readonly IDictionary memo; protected UnpickleStack stack; protected Stream input; - protected static IDictionary objectConstructors; + protected static readonly IDictionary objectConstructors; protected static readonly object NO_RETURN_VALUE = new object(); static Unpickler() { - objectConstructors = new Dictionary(); - objectConstructors["__builtin__.complex"] = new AnyClassConstructor(typeof(ComplexNumber)); - objectConstructors["builtins.complex"] = new AnyClassConstructor(typeof(ComplexNumber)); - objectConstructors["array.array"] = new ArrayConstructor(); - objectConstructors["array._array_reconstructor"] = new ArrayConstructor(); - objectConstructors["__builtin__.bytearray"] = new ByteArrayConstructor(); - objectConstructors["builtins.bytearray"] =new ByteArrayConstructor(); - objectConstructors["__builtin__.bytes"] = new ByteArrayConstructor(); - objectConstructors["__builtin__.set"] = new SetConstructor(); - objectConstructors["builtins.set"] = new SetConstructor(); - objectConstructors["datetime.datetime"] = new DateTimeConstructor(DateTimeConstructor.PythonType.DATETIME); - objectConstructors["datetime.time"] = new DateTimeConstructor(DateTimeConstructor.PythonType.TIME); - objectConstructors["datetime.date"] = new DateTimeConstructor(DateTimeConstructor.PythonType.DATE); - objectConstructors["datetime.timedelta"] = new DateTimeConstructor(DateTimeConstructor.PythonType.TIMEDELTA); - objectConstructors["decimal.Decimal"] = new DecimalConstructor(); - objectConstructors["_codecs.encode"] = new ByteArrayConstructor(); // we're lucky, the bytearray constructor is also able to mimic codecs.encode() + objectConstructors = new Dictionary + { + ["__builtin__.complex"] = new AnyClassConstructor(typeof(ComplexNumber)), + ["builtins.complex"] = new AnyClassConstructor(typeof(ComplexNumber)), + ["array.array"] = new ArrayConstructor(), + ["array._array_reconstructor"] = new ArrayConstructor(), + ["__builtin__.bytearray"] = new ByteArrayConstructor(), + ["builtins.bytearray"] = new ByteArrayConstructor(), + ["__builtin__.bytes"] = new ByteArrayConstructor(), + ["__builtin__.set"] = new SetConstructor(), + ["builtins.set"] = new SetConstructor(), + ["datetime.datetime"] = new DateTimeConstructor(DateTimeConstructor.PythonType.DateTime), + ["datetime.time"] = new DateTimeConstructor(DateTimeConstructor.PythonType.Time), + ["datetime.date"] = new DateTimeConstructor(DateTimeConstructor.PythonType.Date), + ["datetime.timedelta"] = new DateTimeConstructor(DateTimeConstructor.PythonType.TimeDelta), + ["decimal.Decimal"] = new DecimalConstructor(), + ["_codecs.encode"] = new ByteArrayConstructor() + }; + // we're lucky, the bytearray constructor is also able to mimic codecs.encode() } /** @@ -90,9 +97,9 @@ public object loads(byte[] pickledata) { * Close the unpickler and frees the resources such as the unpickle stack and memo table. */ public void close() { - if(stack!=null) stack.clear(); - if(memo!=null) memo.Clear(); - if(input!=null) input.Close(); + stack?.clear(); + memo?.Clear(); + input?.Close(); } /** @@ -305,17 +312,17 @@ protected object dispatch(short key) { return NO_RETURN_VALUE; } - void load_build() { + private void load_build() { object args=stack.pop(); object target=stack.peek(); - object[] arguments=new object[] {args}; - Type[] argumentTypes=new Type[] {args.GetType()}; + object[] arguments={args}; + Type[] argumentTypes={args.GetType()}; // call the __setstate__ method with the given arguments try { MethodInfo setStateMethod=target.GetType().GetMethod("__setstate__", argumentTypes); if(setStateMethod==null) { - throw new PickleException(string.Format("no __setstate__() found in type {0} with argument type {1}", target.GetType(), args.GetType())); + throw new PickleException($"no __setstate__() found in type {target.GetType()} with argument type {args.GetType()}"); } setStateMethod.Invoke(target, arguments); } catch(Exception e) { @@ -323,25 +330,25 @@ void load_build() { } } - void load_proto() { + private void load_proto() { byte proto = PickleUtils.readbyte(input); if (proto > HIGHEST_PROTOCOL) throw new PickleException("unsupported pickle protocol: " + proto); } - void load_none() { + private void load_none() { stack.add(null); } - void load_false() { + private void load_false() { stack.add(false); } - void load_true() { + private void load_true() { stack.add(true); } - void load_int() { + private void load_int() { string data = PickleUtils.readline(input, true); object val; if (data==Opcodes.FALSE.Substring(1)) @@ -360,21 +367,21 @@ void load_int() { stack.add(val); } - void load_binint() { + private void load_binint() { int integer = PickleUtils.bytes_to_integer(PickleUtils.readbytes(input, 4)); stack.add(integer); } - void load_binint1() { + private void load_binint1() { stack.add((int)PickleUtils.readbyte(input)); } - void load_binint2() { + private void load_binint2() { int integer = PickleUtils.bytes_to_integer(PickleUtils.readbytes(input, 2)); stack.add(integer); } - void load_long() { + private void load_long() { string val = PickleUtils.readline(input); if (val.EndsWith("L")) { val = val.Substring(0, val.Length - 1); @@ -387,30 +394,30 @@ void load_long() { } } - void load_long1() { + private void load_long1() { byte n = PickleUtils.readbyte(input); - byte[] data = PickleUtils.readbytes(input, n); + var data = PickleUtils.readbytes(input, n); stack.add(PickleUtils.decode_long(data)); } - void load_long4() { + private void load_long4() { int n = PickleUtils.bytes_to_integer(PickleUtils.readbytes(input, 4)); - byte[] data = PickleUtils.readbytes(input, n); + var data = PickleUtils.readbytes(input, n); stack.add(PickleUtils.decode_long(data)); } - void load_float() { + private void load_float() { string val = PickleUtils.readline(input, true); double d=double.Parse(val, NumberStyles.Float|NumberStyles.AllowDecimalPoint|NumberStyles.AllowLeadingSign, NumberFormatInfo.InvariantInfo); stack.add(d); } - void load_binfloat() { + private void load_binfloat() { double val = PickleUtils.bytes_bigendian_to_double(PickleUtils.readbytes(input, 8),0); stack.add(val); } - void load_string() { + private void load_string() { string rep = PickleUtils.readline(input); bool quotesOk = false; foreach (string q in new [] { "\"", "'" }) // double or single quote @@ -431,100 +438,100 @@ void load_string() { stack.add(PickleUtils.decode_escaped(rep)); } - void load_binstring() { + private void load_binstring() { int len = PickleUtils.bytes_to_integer(PickleUtils.readbytes(input, 4)); - byte[] data = PickleUtils.readbytes(input, len); + var data = PickleUtils.readbytes(input, len); stack.add(PickleUtils.rawStringFromBytes(data)); } - void load_binbytes() { + private void load_binbytes() { int len = PickleUtils.bytes_to_integer(PickleUtils.readbytes(input, 4)); stack.add(PickleUtils.readbytes(input, len)); } - void load_binbytes8() { + private void load_binbytes8() { long len = PickleUtils.bytes_to_long(PickleUtils.readbytes(input, 8),0); stack.add(PickleUtils.readbytes(input, len)); } - void load_unicode() { + private void load_unicode() { string str=PickleUtils.decode_unicode_escaped(PickleUtils.readline(input)); stack.add(str); } - void load_binunicode() { + private void load_binunicode() { int len = PickleUtils.bytes_to_integer(PickleUtils.readbytes(input, 4)); - byte[] data = PickleUtils.readbytes(input, len); + var data = PickleUtils.readbytes(input, len); stack.add(Encoding.UTF8.GetString(data)); } - void load_binunicode8() { + private void load_binunicode8() { long len = PickleUtils.bytes_to_long(PickleUtils.readbytes(input, 8),0); - byte[] data = PickleUtils.readbytes(input, len); + var data = PickleUtils.readbytes(input, len); stack.add(Encoding.UTF8.GetString(data)); } - void load_short_binunicode() { + private void load_short_binunicode() { int len = PickleUtils.readbyte(input); - byte[] data = PickleUtils.readbytes(input, len); + var data = PickleUtils.readbytes(input, len); stack.add(Encoding.UTF8.GetString(data)); } - void load_short_binstring() { + private void load_short_binstring() { byte len = PickleUtils.readbyte(input); - byte[] data = PickleUtils.readbytes(input, len); + var data = PickleUtils.readbytes(input, len); stack.add(PickleUtils.rawStringFromBytes(data)); } - void load_short_binbytes() { + private void load_short_binbytes() { byte len = PickleUtils.readbyte(input); stack.add(PickleUtils.readbytes(input, len)); } - void load_tuple() { + private void load_tuple() { ArrayList top=stack.pop_all_since_marker(); stack.add(top.ToArray()); } - void load_empty_tuple() { + private void load_empty_tuple() { stack.add(new object[0]); } - void load_tuple1() { + private void load_tuple1() { stack.add(new [] { stack.pop() }); } - void load_tuple2() { + private void load_tuple2() { object o2 = stack.pop(); object o1 = stack.pop(); stack.add(new [] { o1, o2 }); } - void load_tuple3() { + private void load_tuple3() { object o3 = stack.pop(); object o2 = stack.pop(); object o1 = stack.pop(); stack.add(new [] { o1, o2, o3 }); } - void load_empty_list() { + private void load_empty_list() { stack.add(new ArrayList(5)); } - void load_empty_dictionary() { + private void load_empty_dictionary() { stack.add(new Hashtable(5)); } - void load_empty_set() { + private void load_empty_set() { stack.add(new HashSet()); } - void load_list() { + private void load_list() { ArrayList top = stack.pop_all_since_marker(); stack.add(top); // simply add the top items as a list to the stack again } - void load_dict() { + private void load_dict() { ArrayList top = stack.pop_all_since_marker(); Hashtable map=new Hashtable(top.Count); for (int i = 0; i < top.Count; i += 2) { @@ -534,16 +541,16 @@ void load_dict() { } stack.add(map); } - - void load_frozenset() { + + private void load_frozenset() { ArrayList top = stack.pop_all_since_marker(); var set = new HashSet(); foreach(var element in top) set.Add(element); stack.add(set); } - - void load_additems() { + + private void load_additems() { ArrayList top = stack.pop_all_since_marker(); var set = (HashSet) stack.pop(); foreach(object item in top) @@ -551,54 +558,61 @@ void load_additems() { stack.add(set); } - void load_global() { + private void load_global() { string module = PickleUtils.readline(input); string name = PickleUtils.readline(input); load_global_sub(module, name); } - - void load_stack_global() { + + private void load_stack_global() { string name = (string) stack.pop(); string module = (string) stack.pop(); load_global_sub(module, name); } - - void load_global_sub(string module, string name) { + + private void load_global_sub(string module, string name) { IObjectConstructor constructor; string key=module+"."+name; if(objectConstructors.ContainsKey(key)) { constructor = objectConstructors[module + "." + name]; - } else { - // check if it is an exception - if(module=="exceptions") { - // python 2.x - constructor=new ExceptionConstructor(typeof(PythonException), module, name); - } else if(module=="builtins" || module=="__builtin__") { - if(name.EndsWith("Error") || name.EndsWith("Warning") || name.EndsWith("Exception") - || name=="GeneratorExit" || name=="KeyboardInterrupt" - || name=="StopIteration" || name=="SystemExit") - { - // it's a python 3.x exception + } else + { + switch (module) + { + // check if it is an exception + case "exceptions": + // python 2.x constructor=new ExceptionConstructor(typeof(PythonException), module, name); - } - else - { - // return a dictionary with the class's properties + break; + case "builtins": + case "__builtin__": + if(name.EndsWith("Error") || name.EndsWith("Warning") || name.EndsWith("Exception") + || name=="GeneratorExit" || name=="KeyboardInterrupt" + || name=="StopIteration" || name=="SystemExit") + { + // it's a python 3.x exception + constructor=new ExceptionConstructor(typeof(PythonException), module, name); + } + else + { + // return a dictionary with the class's properties + constructor=new ClassDictConstructor(module, name); + } + + break; + default: constructor=new ClassDictConstructor(module, name); - } - } else { - // return a dictionary with the class's properties - constructor=new ClassDictConstructor(module, name); + break; } } stack.add(constructor); } - void load_pop() { + private void load_pop() { stack.pop(); } - void load_pop_mark() { + private void load_pop_mark() { object o; do { o = stack.pop(); @@ -606,68 +620,68 @@ void load_pop_mark() { stack.trim(); } - void load_dup() { + private void load_dup() { stack.add(stack.peek()); } - void load_get() { + private void load_get() { int i = int.Parse(PickleUtils.readline(input)); if(!memo.ContainsKey(i)) throw new PickleException("invalid memo key"); stack.add(memo[i]); } - void load_binget() { + private void load_binget() { byte i = PickleUtils.readbyte(input); if(!memo.ContainsKey(i)) throw new PickleException("invalid memo key"); stack.add(memo[i]); } - void load_long_binget() { + private void load_long_binget() { int i = PickleUtils.bytes_to_integer(PickleUtils.readbytes(input, 4)); if(!memo.ContainsKey(i)) throw new PickleException("invalid memo key"); stack.add(memo[i]); } - void load_put() { + private void load_put() { int i = int.Parse(PickleUtils.readline(input)); memo[i]=stack.peek(); } - void load_binput() { + private void load_binput() { byte i = PickleUtils.readbyte(input); memo[i]=stack.peek(); } - void load_memoize() { + private void load_memoize() { memo[memo.Count]=stack.peek(); } - void load_long_binput() { + private void load_long_binput() { int i = PickleUtils.bytes_to_integer(PickleUtils.readbytes(input, 4)); memo[i]=stack.peek(); } - void load_append() { + private void load_append() { object value = stack.pop(); ArrayList list = (ArrayList) stack.peek(); list.Add(value); } - void load_appends() { + private void load_appends() { ArrayList top = stack.pop_all_since_marker(); ArrayList list = (ArrayList) stack.peek(); list.AddRange(top); list.TrimToSize(); } - void load_setitem() { + private void load_setitem() { object value = stack.pop(); object key = stack.pop(); Hashtable dict=(Hashtable)stack.peek(); dict[key]=value; } - void load_setitems() { + private void load_setitems() { var newitems=new List>(); object value = stack.pop(); while (value != stack.MARKER) { @@ -682,48 +696,48 @@ void load_setitems() { } } - void load_mark() { + private void load_mark() { stack.add_mark(); } - void load_reduce() { - object[] args = (object[]) stack.pop(); + private void load_reduce() { + var args = (object[]) stack.pop(); IObjectConstructor constructor = (IObjectConstructor) stack.pop(); stack.add(constructor.construct(args)); } - void load_newobj() { + private void load_newobj() { load_reduce(); // we just do the same as class(*args) instead of class.__new__(class,*args) } - - void load_newobj_ex() { + + private void load_newobj_ex() { Hashtable kwargs = (Hashtable) stack.pop(); - object[] args = (object[]) stack.pop(); + var args = (object[]) stack.pop(); IObjectConstructor constructor = (IObjectConstructor) stack.pop(); if(kwargs.Count==0) stack.add(constructor.construct(args)); else throw new PickleException("newobj_ex with keyword arguments not supported"); } - - void load_frame() { + + private void load_frame() { // for now we simply skip the frame opcode and its length PickleUtils.readbytes(input, 8); } - - void load_persid() { + + private void load_persid() { // the persistent id is taken from the argument string pid = PickleUtils.readline(input); stack.add(persistentLoad(pid)); } - - void load_binpersid() { + + private void load_binpersid() { // the persistent id is taken from the stack string pid = stack.pop().ToString(); stack.add(persistentLoad(pid)); } - - void load_obj() { + + private void load_obj() { ArrayList args = stack.pop_all_since_marker(); IObjectConstructor constructor = (IObjectConstructor)args[0]; args = args.GetRange(1, args.Count-1); @@ -731,7 +745,7 @@ void load_obj() { stack.add(obj); } - void load_inst() { + private void load_inst() { string module = PickleUtils.readline(input); string classname = PickleUtils.readline(input); ArrayList args = stack.pop_all_since_marker(); @@ -747,14 +761,14 @@ void load_inst() { stack.add(obj); } - protected virtual Object persistentLoad(string pid) + protected virtual object persistentLoad(string pid) { throw new PickleException("A load persistent id instruction was encountered, but no persistentLoad function was specified. (implement it in custom Unpickler subclass)"); } public void Dispose() { - this.close(); + close(); } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Config.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Config.cs index e91458d..1e2f4ee 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Config.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Config.cs @@ -1,5 +1,8 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ +// ReSharper disable InconsistentNaming +// ReSharper disable ConvertToConstant.Global +// ReSharper disable FieldCanBeMadeReadOnly.Global namespace Razorvine.Pyro { @@ -11,7 +14,7 @@ public static class Config { public enum SerializerType { pickle, serpent - }; + } public static string MSG_TRACE_DIR=null; public static int NS_PORT = 9090; diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/DummyPyroSerializer.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/DummyPyroSerializer.cs index 2010f34..c764226 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/DummyPyroSerializer.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/DummyPyroSerializer.cs @@ -12,6 +12,8 @@ public class DummyPyroSerializer /// /// for the unpickler to restore state /// + // ReSharper disable once UnusedMember.Global + // ReSharper disable once UnusedParameter.Global public void __setstate__(Hashtable values) { } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameBuiltin.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameBuiltin.cs index 5db73ba..7607b8a 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameBuiltin.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameBuiltin.cs @@ -2,6 +2,7 @@ using System; using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Dynamic; namespace Razorvine.Pyro @@ -10,17 +11,20 @@ namespace Razorvine.Pyro /// /// Flame-Wrapper for a builtin function. /// +[SuppressMessage("ReSharper", "InconsistentNaming")] +[SuppressMessage("ReSharper", "UnusedMember.Global")] +[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public class FlameBuiltin : DynamicObject, IDisposable { - private PyroProxy flameserver; - private string builtin; + private PyroProxy _flameserver; + private string _builtin; public byte[] pyroHmacKey { get { - return flameserver.pyroHmacKey; + return _flameserver.pyroHmacKey; } set { - flameserver.pyroHmacKey = value; + _flameserver.pyroHmacKey = value; } } @@ -28,12 +32,12 @@ public byte[] pyroHmacKey { /// for the unpickler to restore state /// public void __setstate__(Hashtable values) { - flameserver=(PyroProxy) values["flameserver"]; - builtin=(string) values["builtin"]; + _flameserver=(PyroProxy) values["flameserver"]; + _builtin=(string) values["builtin"]; } - public Object call(params object[] arguments) { - return flameserver.call("invokeBuiltin", builtin, arguments, new Hashtable(0)); + public object call(params object[] arguments) { + return _flameserver.call("invokeBuiltin", _builtin, arguments, new Hashtable(0)); } /// @@ -42,13 +46,13 @@ public Object call(params object[] arguments) { /// public override bool TryInvoke(InvokeBinder binder, object[] args, out object result) { - result = flameserver.call("invokeBuiltin", builtin, args, new Hashtable(0)); + result = _flameserver.call("invokeBuiltin", _builtin, args, new Hashtable(0)); return true; } - public void close() { - if(flameserver!=null) - flameserver.close(); + public void close() + { + _flameserver?.close(); } public void Dispose() diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameModule.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameModule.cs index a716836..4d42cf8 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameModule.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameModule.cs @@ -2,6 +2,7 @@ using System; using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Dynamic; namespace Razorvine.Pyro @@ -10,16 +11,19 @@ namespace Razorvine.Pyro /// /// Flame-Wrapper for a remote module. /// +[SuppressMessage("ReSharper", "InconsistentNaming")] +[SuppressMessage("ReSharper", "UnusedMember.Global")] +[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public class FlameModule : DynamicObject, IDisposable { - private PyroProxy flameserver; - private string module; + private PyroProxy _flameserver; + private string _module; public byte[] pyroHmacKey { get { - return flameserver.pyroHmacKey; + return _flameserver.pyroHmacKey; } set { - flameserver.pyroHmacKey = value; + _flameserver.pyroHmacKey = value; } } @@ -27,8 +31,8 @@ public byte[] pyroHmacKey { /// for the unpickler to restore state /// public void __setstate__(Hashtable values) { - flameserver=(PyroProxy) values["flameserver"]; - module=(string) values["module"]; + _flameserver=(PyroProxy) values["flameserver"]; + _module=(string) values["module"]; } /// @@ -41,13 +45,13 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o return true; } - public Object call(string attribute, params object[] arguments) { - return flameserver.call("invokeModule", module+"."+attribute, arguments, new Hashtable(0)); + public object call(string attribute, params object[] arguments) { + return _flameserver.call("invokeModule", _module+"."+attribute, arguments, new Hashtable(0)); } - public void close() { - if(flameserver!=null) - flameserver.close(); + public void close() + { + _flameserver?.close(); } public void Dispose() diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameRemoteConsole.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameRemoteConsole.cs index 7603985..e29549c 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameRemoteConsole.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/FlameRemoteConsole.cs @@ -2,6 +2,7 @@ using System; using System.Collections; +using System.Diagnostics.CodeAnalysis; namespace Razorvine.Pyro { @@ -9,28 +10,29 @@ namespace Razorvine.Pyro /// /// Flame remote interactive console client. /// +[SuppressMessage("ReSharper", "InconsistentNaming")] +[SuppressMessage("ReSharper", "UnusedMember.Global")] +[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] +[SuppressMessage("ReSharper", "InvertIf")] public class FlameRemoteConsole : IDisposable { - private PyroProxy remoteconsole; + private PyroProxy _remoteconsole; /// /// for the unpickler to restore state /// public void __setstate__(Hashtable values) { - remoteconsole=(PyroProxy)values["remoteconsole"]; + _remoteconsole=(PyroProxy)values["remoteconsole"]; } public void interact() { - string banner=(String)remoteconsole.call("get_banner"); + string banner=(string)_remoteconsole.call("get_banner"); Console.WriteLine(banner); - string ps1=">>> "; - string ps2="... "; + const string ps1 = ">>> "; + const string ps2 = "... "; bool more=false; while(true) { - if(more) - Console.Write(ps2); - else - Console.Write(ps1); + Console.Write(more ? ps2 : ps1); Console.Out.Flush(); string line=Console.ReadLine(); if(line==null) { @@ -38,7 +40,7 @@ public void interact() { Console.WriteLine(""); break; } - object[] result=(object[])remoteconsole.call("push_and_get_output", line); + var result=(object[])_remoteconsole.call("push_and_get_output", line); if(result[0]!=null) { Console.Write(result[0]); } @@ -48,10 +50,10 @@ public void interact() { } public void close() { - if(remoteconsole!=null) { - remoteconsole.call("terminate"); - remoteconsole.close(); - remoteconsole = null; + if(_remoteconsole!=null) { + _remoteconsole.call("terminate"); + _remoteconsole.close(); + _remoteconsole = null; } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/IOUtil.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/IOUtil.cs index 6ad5d86..6573ee2 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/IOUtil.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/IOUtil.cs @@ -1,6 +1,7 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System.IO; +// ReSharper disable InconsistentNaming namespace Razorvine.Pyro { @@ -8,7 +9,7 @@ namespace Razorvine.Pyro /// /// Lowlevel I/O utilities. /// -class IOUtil +internal static class IOUtil { /** * send a message to the outputstream. @@ -22,7 +23,7 @@ public static void send(Stream outs, byte[] message) { * Makes sure the complete message is received, raises IOException otherwise. */ public static byte[] recv(Stream ins, int size) { - byte [] bytes = new byte [size]; + var bytes = new byte [size]; int numRead = ins.Read(bytes, 0, size); if(numRead<=0) { throw new IOException("premature end of data"); diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Message.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Message.cs index 8aaf2de..4c47f0d 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Message.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Message.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; @@ -13,6 +14,9 @@ namespace Razorvine.Pyro /// /// Pyro wire protocol message. /// +[SuppressMessage("ReSharper", "InconsistentNaming")] +[SuppressMessage("ReSharper", "UnusedMember.Global")] +[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public class Message { private const int CHECKSUM_MAGIC = 0x34E9; @@ -40,8 +44,8 @@ public class Message public byte[] data; public int data_size; public ushort annotations_size; - public ushort serializer_id; - public ushort seq; + public readonly ushort serializer_id; + public readonly ushort seq; public IDictionary annotations; /// @@ -49,7 +53,7 @@ public class Message /// public Message(ushort msgType, ushort serializer_id, ushort flags, ushort seq) { - this.type = msgType; + type = msgType; this.flags = flags; this.seq = seq; this.serializer_id = serializer_id; @@ -61,8 +65,8 @@ public Message(ushort msgType, ushort serializer_id, ushort flags, ushort seq) public Message(ushort msgType, byte[] databytes, ushort serializer_id, ushort flags, ushort seq, IDictionary annotations, byte[] hmac) :this(msgType, serializer_id, flags, seq) { - this.data = databytes; - this.data_size = databytes.Length; + data = databytes; + data_size = databytes.Length; this.annotations = annotations; if(null==annotations) this.annotations = new Dictionary(0); @@ -70,7 +74,7 @@ public Message(ushort msgType, byte[] databytes, ushort serializer_id, ushort fl if(hmac!=null) this.annotations["HMAC"] = this.hmac(hmac); - this.annotations_size = (ushort) this.annotations.Sum(a=>a.Value.Length+6); + annotations_size = (ushort) this.annotations.Sum(a=>a.Value.Length+6); } /// @@ -79,13 +83,13 @@ public Message(ushort msgType, byte[] databytes, ushort serializer_id, ushort fl public byte[] hmac(byte[] key) { using(HMACSHA1 hmac=new HMACSHA1(key)) { - hmac.TransformBlock(this.data, 0, this.data.Length, this.data, 0); - foreach(var e in this.annotations.OrderBy(a=>a.Key)) + hmac.TransformBlock(data, 0, data.Length, data, 0); + foreach(var e in annotations.OrderBy(a=>a.Key)) { if(e.Key!="HMAC") hmac.TransformBlock(e.Value, 0, e.Value.Length, e.Value, 0); } - hmac.TransformFinalBlock(this.data, 0, 0); + hmac.TransformFinalBlock(data, 0, 0); return hmac.Hash; } } @@ -95,9 +99,9 @@ public byte[] hmac(byte[] key) /// public byte[] to_bytes() { - byte[] header_bytes = get_header_bytes(); - byte[] annotations_bytes = get_annotations_bytes(); - byte[] result = new byte[header_bytes.Length + annotations_bytes.Length + data.Length]; + var header_bytes = get_header_bytes(); + var annotations_bytes = get_annotations_bytes(); + var result = new byte[header_bytes.Length + annotations_bytes.Length + data.Length]; Array.Copy(header_bytes, result, header_bytes.Length); Array.Copy(annotations_bytes, 0, result, header_bytes.Length, annotations_bytes.Length); Array.Copy(data, 0, result, header_bytes.Length+annotations_bytes.Length, data.Length); @@ -107,7 +111,7 @@ public byte[] to_bytes() public byte[] get_header_bytes() { int checksum = (type+Config.PROTOCOL_VERSION+data_size+annotations_size+serializer_id+flags+seq+CHECKSUM_MAGIC)&0xffff; - byte[] header = new byte[HEADER_SIZE]; + var header = new byte[HEADER_SIZE]; /* header format: '!4sHHHHiHHHH' (24 bytes) 4 id ('PYRO') @@ -168,7 +172,7 @@ public byte[] get_annotations_bytes() if(ann.Key.Length!=4) throw new ArgumentException("annotation key must be length 4"); result = result.Concat(Encoding.ASCII.GetBytes(ann.Key)); - byte[] size_bytes = new byte[] { (byte)((ann.Value.Length>>8)&0xff), (byte)(ann.Value.Length&0xff) }; + byte[] size_bytes = { (byte)((ann.Value.Length>>8)&0xff), (byte)(ann.Value.Length&0xff) }; result = result.Concat(size_bytes); result = result.Concat(ann.Value); } @@ -201,10 +205,12 @@ public static Message from_header(byte[] header) int checksum = (header[22]<<8)|header[23]; if(checksum!=((msg_type+version+data_size+annotations_size+flags+serializer_id+seq+CHECKSUM_MAGIC)&0xffff)) throw new PyroException("header checksum mismatch"); - - var msg = new Message((ushort)msg_type, (ushort)serializer_id, (ushort)flags, (ushort)seq); - msg.data_size = data_size; - msg.annotations_size = (ushort)annotations_size; + + var msg = new Message((ushort) msg_type, (ushort) serializer_id, (ushort) flags, (ushort) seq) + { + data_size = data_size, + annotations_size = (ushort) annotations_size + }; return msg; } @@ -229,12 +235,13 @@ public static Message from_header(byte[] header) /// Also reads annotation chunks and the actual payload data. /// Validates a HMAC chunk if present. /// + // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global public static Message recv(Stream connection, ushort[] requiredMsgTypes, byte[] hmac) { - byte[] header_data = IOUtil.recv(connection, HEADER_SIZE); + var header_data = IOUtil.recv(connection, HEADER_SIZE); var msg = from_header(header_data); if(requiredMsgTypes!=null && !requiredMsgTypes.Contains(msg.type)) - throw new PyroException(string.Format("invalid msg type {0} received", msg.type)); + throw new PyroException($"invalid msg type {msg.type} received"); byte[] annotations_data = null; msg.annotations = new Dictionary(); @@ -247,7 +254,7 @@ public static Message recv(Stream connection, ushort[] requiredMsgTypes, byte[] { string anno = Encoding.ASCII.GetString(annotations_data, i, 4); int length = (annotations_data[i+4]<<8) | annotations_data[i+5]; - byte[] annotations_bytes = new byte[length]; + var annotations_bytes = new byte[length]; Array.Copy(annotations_data, i+6, annotations_bytes, 0, length); msg.annotations[anno] = annotations_bytes; i += 6+length; @@ -275,26 +282,26 @@ public static Message recv(Stream connection, ushort[] requiredMsgTypes, byte[] } public static void TraceMessageRecv(int sequenceNr, byte[] headerdata, byte[] annotations, byte[] data) { - string filename=Path.Combine(Config.MSG_TRACE_DIR, string.Format("{0:D5}-b-recv-header.dat", sequenceNr)); + string filename=Path.Combine(Config.MSG_TRACE_DIR, $"{sequenceNr:D5}-b-recv-header.dat"); using(FileStream fos=new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { fos.Write(headerdata, 0, headerdata.Length); if(annotations!=null) fos.Write(annotations, 0, annotations.Length); } - filename=Path.Combine(Config.MSG_TRACE_DIR, string.Format("{0:D5}-b-recv-message.dat", sequenceNr)); + filename=Path.Combine(Config.MSG_TRACE_DIR, $"{sequenceNr:D5}-b-recv-message.dat"); using(FileStream fos=new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { fos.Write(data, 0, data.Length); } } public static void TraceMessageSend(int sequenceNr, byte[] headerdata, byte[] annotations, byte[] data) { - string filename=Path.Combine(Config.MSG_TRACE_DIR, string.Format("{0:D5}-a-send-header.dat", sequenceNr)); + string filename=Path.Combine(Config.MSG_TRACE_DIR, $"{sequenceNr:D5}-a-send-header.dat"); using(FileStream fos=new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { fos.Write(headerdata, 0, headerdata.Length); if(annotations!=null) fos.Write(annotations, 0, annotations.Length); } - filename=Path.Combine(Config.MSG_TRACE_DIR, string.Format("{0:D5}-a-send-message.dat", sequenceNr)); + filename=Path.Combine(Config.MSG_TRACE_DIR, $"{sequenceNr:D5}-a-send-message.dat"); using(FileStream fos=new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { fos.Write(data, 0, data.Length); } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/NameServerProxy.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/NameServerProxy.cs index 4004302..bb404bc 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/NameServerProxy.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/NameServerProxy.cs @@ -3,6 +3,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Sockets; using System.Text; @@ -15,6 +16,7 @@ namespace Razorvine.Pyro /// A wrapper proxy for the Pyro Name Server, /// to simplify the access to its remote methods. /// +[SuppressMessage("ReSharper", "InconsistentNaming")] public class NameServerProxy : PyroProxy { public NameServerProxy(PyroURI uri) : this(uri.host, uri.port, uri.objectid) { @@ -24,38 +26,38 @@ public NameServerProxy(string hostname, int port, string objectid = "Pyro.NameSe } public void ping() { - this.call("ping"); + call("ping"); } public PyroURI lookup(string name) { - return (PyroURI) this.call("lookup", name); + return (PyroURI) call("lookup", name); } public Tuple> lookup(string name, bool return_metadata) { - object[] result = (object[])this.call("lookup", name, return_metadata); + var result = (object[])call("lookup", name, return_metadata); PyroURI uri = (PyroURI) result[0]; var metastrings = GetStringSet(result[1]); return new Tuple>(uri, metastrings); } public int remove(string name, string prefix, string regex) { - return (int) this.call("remove", name, prefix, regex); + return (int) call("remove", name, prefix, regex); } public void register(string name, PyroURI uri, bool safe) { - this.call("register", name, uri, safe); + call("register", name, uri, safe); } public void register(string name, PyroURI uri, bool safe, IEnumerable metadata) { - this.call("register", name, uri, safe, metadata); + call("register", name, uri, safe, metadata); } public void set_metadata(string name, ISet metadata) { - this.call("set_metadata", name, metadata); + call("set_metadata", name, metadata); } public IDictionary list(string prefix, string regex) { - IDictionary hash = (IDictionary) this.call("list", prefix, regex); + IDictionary hash = (IDictionary) call("list", prefix, regex); IDictionary typed=new Dictionary(hash.Count); foreach(object name in hash.Keys) { typed[(string)name]=(string)hash[name]; @@ -64,7 +66,7 @@ public IDictionary list(string prefix, string regex) { } public IDictionary list(string prefix, string regex, IEnumerable metadata_all, IEnumerable metadata_any) { - IDictionary hash = (IDictionary) this.call("list", prefix, regex, metadata_all, metadata_any); + IDictionary hash = (IDictionary) call("list", prefix, regex, metadata_all, metadata_any); IDictionary typed=new Dictionary(hash.Count); foreach(object name in hash.Keys) { typed[(string)name]=(string)hash[name]; @@ -73,10 +75,10 @@ public IDictionary list(string prefix, string regex, IEnumerable< } public IDictionary>> list_with_meta(string prefix, string regex) { - IDictionary hash = (IDictionary) this.call("list", prefix, regex, null, null, true); + IDictionary hash = (IDictionary) call("list", prefix, regex, null, null, true); IDictionary>> typed=new Dictionary>>(hash.Count); foreach(object name in hash.Keys) { - object[] o = (object[]) hash[name]; + var o = (object[]) hash[name]; string uri = (string) o[0]; var metastrings = GetStringSet(o[1]); typed[(string)name] = new Tuple>(uri, metastrings); @@ -85,10 +87,10 @@ public IDictionary>> list_with_meta(string pr } public IDictionary>> list_with_meta(string prefix, string regex, IEnumerable metadata_all, IEnumerable metadata_any) { - IDictionary hash = (IDictionary) this.call("list", prefix, regex, metadata_all, metadata_any, true); + IDictionary hash = (IDictionary) call("list", prefix, regex, metadata_all, metadata_any, true); IDictionary>> typed=new Dictionary>>(hash.Count); foreach(object name in hash.Keys) { - object[] o = (object[]) hash[name]; + var o = (object[]) hash[name]; string uri = (string) o[0]; var metastrings = GetStringSet(o[1]); typed[(string)name] = new Tuple>(uri, metastrings); @@ -111,7 +113,7 @@ public static NameServerProxy locateNS(string host, int port=0, byte[] hmacKey=n using(UdpClient udpclient=new UdpClient()) { udpclient.Client.ReceiveTimeout = 2000; udpclient.EnableBroadcast=true; - byte[] buf=Encoding.ASCII.GetBytes("GET_NSURI"); + var buf=Encoding.ASCII.GetBytes("GET_NSURI"); udpclient.Send(buf, buf.Length, ipendpoint); IPEndPoint source=null; try { diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/ProxyClassConstructor.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/ProxyClassConstructor.cs index 12f89eb..884c3ab 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/ProxyClassConstructor.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/ProxyClassConstructor.cs @@ -1,6 +1,5 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ -using System; using Razorvine.Pickle; namespace Razorvine.Pyro @@ -10,22 +9,25 @@ namespace Razorvine.Pyro /// public class ProxyClassConstructor : IObjectConstructor { - public object construct(object[] args) { + public object construct(object[] args) + { if(args.Length==0) { // no-arg constructor return new PyroProxy(); - } else if(args.Length==1 && args[0] is PyroURI) { + } + + if(args.Length==1 && args[0] is PyroURI) { // constructor with PyroURI arg return new PyroProxy((PyroURI)args[0]); - } else if(args.Length==3) { - // constructor with hostname,port,objectid args - String hostname=(String)args[0]; - int port=(int)args[1]; - String objectId=(String)args[2]; - return new PyroProxy(hostname, port, objectId); - } else { - throw new PickleException("invalid args for PyroProxy unpickling"); } + + if (args.Length != 3) throw new PickleException("invalid args for PyroProxy unpickling"); + // constructor with hostname,port,objectid args + string hostname=(string)args[0]; + int port=(int)args[1]; + string objectId=(string)args[2]; + return new PyroProxy(hostname, port, objectId); + } } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroException.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroException.cs index 5435014..a2054d3 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroException.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroException.cs @@ -4,6 +4,8 @@ using System.Collections; using System.Runtime.Serialization; using System.Text; +// ReSharper disable InconsistentNaming +// ReSharper disable UnusedMember.Global namespace Razorvine.Pyro { @@ -13,8 +15,8 @@ namespace Razorvine.Pyro [Serializable] public class PyroException : Exception { - public String _pyroTraceback {get;set;} - public String PythonExceptionType {get;set;} + public string _pyroTraceback {get; set;} + public string PythonExceptionType {get; set;} public PyroException() { @@ -41,9 +43,9 @@ public void __setstate__(Hashtable values) { return; object tb=values["_pyroTraceback"]; // if the traceback is a list of strings, create one string from it - if(tb is ICollection) { + var tbcoll = tb as ICollection; + if(tbcoll != null) { StringBuilder sb=new StringBuilder(); - ICollection tbcoll=(ICollection)tb; foreach(object line in tbcoll) { sb.Append(line); } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroExceptionPickler.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroExceptionPickler.cs index f05f36e..eeed63b 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroExceptionPickler.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroExceptionPickler.cs @@ -5,6 +5,7 @@ using System.Text; using Razorvine.Pickle; +// ReSharper disable InvertIf namespace Razorvine.Pyro { @@ -17,17 +18,17 @@ public class PyroExceptionPickler : IObjectPickler { public void pickle(object o, Stream outs, Pickler currentPickler) { PyroException error = (PyroException) o; outs.WriteByte(Opcodes.GLOBAL); - byte[] output=Encoding.Default.GetBytes("Pyro4.errors\nPyroError\n"); + var output=Encoding.Default.GetBytes("Pyro4.errors\nPyroError\n"); outs.Write(output,0,output.Length); - object[] args = new object[] { error.Message }; + object[] args = { error.Message }; currentPickler.save(args); outs.WriteByte(Opcodes.REDUCE); if(!string.IsNullOrEmpty(error._pyroTraceback)) { // add _pyroTraceback attribute to the output - Hashtable tb = new Hashtable(); - tb["_pyroTraceback"] = new []{ error._pyroTraceback }; // transform single string back into list + Hashtable tb = new Hashtable {["_pyroTraceback"] = new[] {error._pyroTraceback}}; + // transform single string back into list currentPickler.save(tb); outs.WriteByte(Opcodes.BUILD); } @@ -52,21 +53,17 @@ public static IDictionary ToSerpentDict(object obj) public static object FromSerpentDict(IDictionary dict) { - object[] args = (object[]) dict["args"]; + var args = (object[]) dict["args"]; string pythonExceptionType = (string) dict["__class__"]; PyroException ex; - if(args.Length==0) { - if(string.IsNullOrEmpty(pythonExceptionType)) - ex = new PyroException(); - else - ex = new PyroException("["+pythonExceptionType+"]"); + if(args.Length==0) + { + ex = string.IsNullOrEmpty(pythonExceptionType) ? new PyroException() : new PyroException("["+pythonExceptionType+"]"); } - else { - if(string.IsNullOrEmpty(pythonExceptionType)) - ex = new PyroException((string)args[0]); - else - ex = new PyroException(string.Format("[{0}] {1}", pythonExceptionType, args[0])); + else + { + ex = string.IsNullOrEmpty(pythonExceptionType) ? new PyroException((string)args[0]) : new PyroException($"[{pythonExceptionType}] {args[0]}"); } ex.PythonExceptionType = pythonExceptionType; @@ -79,9 +76,9 @@ public static object FromSerpentDict(IDictionary dict) if("_pyroTraceback"==key) { // if the traceback is a list of strings, create one string from it - if(entry.Value is ICollection) { + var tbcoll = entry.Value as ICollection; + if(tbcoll != null) { StringBuilder sb=new StringBuilder(); - ICollection tbcoll=(ICollection)entry.Value; foreach(object line in tbcoll) { sb.Append(line); } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroProxy.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroProxy.cs index 2c97239..eb98164 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroProxy.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroProxy.cs @@ -3,6 +3,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.IO; using System.IO.Compression; @@ -11,6 +12,7 @@ using System.Reflection; using System.Text; using Razorvine.Pickle; +// ReSharper disable InvertIf namespace Razorvine.Pyro { @@ -21,11 +23,14 @@ namespace Razorvine.Pyro /// If you declare it as a 'dynamic' variable, you can just invoke the remote methods on it directly, and access remote attributes directly. /// [Serializable] +[SuppressMessage("ReSharper", "InconsistentNaming")] +[SuppressMessage("ReSharper", "MemberCanBeProtected.Global")] +[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public class PyroProxy : DynamicObject, IDisposable { - public string hostname {get;set;} - public int port {get;set;} - public string objectid {get;set;} + public string hostname {get;private set;} + public int port {get;private set;} + public string objectid {get;private set;} public byte[] pyroHmacKey; // per-proxy hmac key, used to be HMAC_KEY config item public Guid? correlation_id; // per-proxy correlation id (need to set/update this yourself) public object pyroHandshake = "hello"; // data object that should be sent in the initial connection handshake message. Can be any serializable object. @@ -63,7 +68,7 @@ public PyroProxy(string hostname, int port, string objectid) { /// Release resources when descructed /// ~PyroProxy() { - this.close(); + close(); } public void Dispose() { @@ -88,7 +93,7 @@ protected void connect() { // not checking _pyroOneway because that feature already existed and people are already modifying it on the proxy // log.debug("reusing existing metadata") } else { - GetMetadata(this.objectid); + GetMetadata(objectid); } } } @@ -99,7 +104,7 @@ protected void connect() { /// protected void GetMetadata(string objectId) { // get metadata from server (methods, attrs, oneway, ...) and remember them in some attributes of the proxy - objectId = objectId ?? this.objectid; + objectId = objectId ?? objectid; if(sock==null) { connect(); if(pyroMethods.Any() || pyroAttrs.Any()) @@ -107,7 +112,7 @@ protected void GetMetadata(string objectId) { } // invoke the get_metadata method on the daemon - object result = this.internal_call("get_metadata", Config.DAEMON_NAME, 0, false, objectId); + object result = internal_call("get_metadata", Config.DAEMON_NAME, 0, false, objectId); if(result==null) return; _processMetadata((IDictionary)result); @@ -121,20 +126,20 @@ private void _processMetadata(IDictionary result) { // the collections in the result can be either an object[] or a HashSet or List, // depending on the serializer and Pyro version that is used - object[] methods_array = result["methods"] as object[]; - object[] attrs_array = result["attrs"] as object[]; - object[] oneway_array = result["oneway"] as object[]; + var methods_array = result["methods"] as object[]; + var attrs_array = result["attrs"] as object[]; + var oneway_array = result["oneway"] as object[]; - this.pyroMethods = methods_array != null ? new HashSet(methods_array.Select(o => o as string)) : GetStringSet(result["methods"]); - this.pyroAttrs = attrs_array != null ? new HashSet(attrs_array.Select(o => o as string)) : GetStringSet(result["attrs"]); - this.pyroOneway = oneway_array != null ? new HashSet(oneway_array.Select(o => o as string)) : GetStringSet(result["attrs"]); + pyroMethods = methods_array != null ? new HashSet(methods_array.Select(o => o as string)) : GetStringSet(result["methods"]); + pyroAttrs = attrs_array != null ? new HashSet(attrs_array.Select(o => o as string)) : GetStringSet(result["attrs"]); + pyroOneway = oneway_array != null ? new HashSet(oneway_array.Select(o => o as string)) : GetStringSet(result["attrs"]); if(!pyroMethods.Any() && !pyroAttrs.Any()) { throw new PyroException("remote object doesn't expose any methods or attributes"); } } - protected HashSet GetStringSet(object strings) + protected static HashSet GetStringSet(object strings) { var result1 = strings as HashSet; if(result1!=null) @@ -191,6 +196,7 @@ public object call(string method, params object[] arguments) { /// the name of the method you want to call /// zero or more arguments for the remote method [Obsolete("Pyro now figures out automatically what methods are oneway by getting metadata from the server. Just use call().")] + [SuppressMessage("ReSharper", "UnusedMember.Global")] public void call_oneway(string method, params object[] arguments) { internal_call(method, null, Message.FLAGS_ONEWAY, true, arguments); } @@ -200,7 +206,7 @@ public void call_oneway(string method, params object[] arguments) { /// /// the attribute name public object getattr(string attr) { - return this.internal_call("__getattr__", null, 0, false, new object[]{attr}); + return internal_call("__getattr__", null, 0, false, attr); } @@ -210,7 +216,7 @@ public object getattr(string attr) { /// the attribute name /// the new value for the attribute public void setattr(string attr, object value) { - this.internal_call("__setattr__", null, 0, false, new object[] {attr, value}); + internal_call("__setattr__", null, 0, false, attr, value); } /// @@ -230,8 +236,9 @@ public virtual IDictionary annotations() /// /// Internal call method to actually perform the Pyro method call and process the result. /// + // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private object internal_call(string method, string actual_objectId, ushort flags, bool checkMethodName, params object[] parameters) { - actual_objectId = actual_objectId ?? this.objectid; + actual_objectId = actual_objectId ?? objectid; lock(this) { connect(); unchecked { @@ -245,17 +252,17 @@ private object internal_call(string method, string actual_objectId, ushort flags flags |= Message.FLAGS_ONEWAY; } if(checkMethodName && Config.METADATA && !pyroMethods.Contains(method)) { - throw new PyroException(string.Format("remote object '{0}' has no exposed attribute or method '{1}'", actual_objectId, method)); + throw new PyroException($"remote object '{actual_objectId}' has no exposed attribute or method '{method}'"); } if (parameters == null) parameters = new object[] {}; PyroSerializer ser = PyroSerializer.GetFor(Config.SERIALIZER); - byte[] pickle = ser.serializeCall(actual_objectId, method, parameters, new Dictionary(0)); - var msg = new Message(Message.MSG_INVOKE, pickle, ser.serializer_id, flags, sequenceNr, this.annotations(), pyroHmacKey); + var pickle = ser.serializeCall(actual_objectId, method, parameters, new Dictionary(0)); + var msg = new Message(Message.MSG_INVOKE, pickle, ser.serializer_id, flags, sequenceNr, annotations(), pyroHmacKey); Message resultmsg; - lock (this.sock) { + lock (sock) { IOUtil.send(sock_stream, msg.to_bytes()); if(Config.MSG_TRACE_DIR!=null) { Message.TraceMessageSend(sequenceNr, msg.get_header_bytes(), msg.get_annotations_bytes(), msg.data); @@ -286,27 +293,21 @@ private object internal_call(string method, string actual_objectId, ushort flags if ((resultmsg.flags & Message.FLAGS_EXCEPTION) != 0) { Exception rx = (Exception) ser.deserializeData(resultmsg.data); - if (rx is PyroException) { - throw (PyroException) rx; - } else { - PyroException px; - - // if the source was a PythonException, copy its message and python exception type - PythonException pyx = rx as PythonException; - if(pyx==null) { - px = new PyroException(null, rx); - } else { - px = new PyroException(rx.Message, rx); - px.PythonExceptionType = pyx.PythonExceptionType; - } + var exception = rx as PyroException; + if (exception != null) { + throw exception; + } + + // if the source was a PythonException, copy its message and python exception type + PythonException pyx = rx as PythonException; + var px = pyx==null ? new PyroException(null, rx) : new PyroException(rx.Message, rx) {PythonExceptionType = pyx.PythonExceptionType}; - PropertyInfo remotetbProperty=rx.GetType().GetProperty("_pyroTraceback"); - if(remotetbProperty!=null) { - string remotetb=(string)remotetbProperty.GetValue(rx,null); - px._pyroTraceback=remotetb; - } - throw px; + PropertyInfo remotetbProperty=rx.GetType().GetProperty("_pyroTraceback"); + if(remotetbProperty!=null) { + string remotetb=(string)remotetbProperty.GetValue(rx,null); + px._pyroTraceback=remotetb; } + throw px; } return ser.deserializeData(resultmsg.data); @@ -316,14 +317,14 @@ private object internal_call(string method, string actual_objectId, ushort flags /// /// Decompress the data bytes in the given message (in place). /// - private void _decompressMessageData(Message msg) { + private static void _decompressMessageData(Message msg) { if((msg.flags & Message.FLAGS_COMPRESSED) == 0) { throw new ArgumentException("message data is not compressed"); } using(MemoryStream compressed=new MemoryStream(msg.data, 2, msg.data.Length-2, false)) { using(DeflateStream decompresser=new DeflateStream(compressed, CompressionMode.Decompress)) { MemoryStream bos = new MemoryStream(msg.data.Length); - byte[] buffer = new byte[4096]; + var buffer = new byte[4096]; int numRead; while ((numRead = decompresser.Read(buffer, 0, buffer.Length)) != 0) { bos.Write(buffer, 0, numRead); @@ -339,12 +340,12 @@ private void _decompressMessageData(Message msg) { /// If you re-use the proxy, it will automatically reconnect. /// public void close() { - if (this.sock != null) { - if(this.sock_stream!=null) this.sock_stream.Close(); - this.sock.Client.Close(); - this.sock.Close(); - this.sock=null; - this.sock_stream=null; + if (sock != null) { + sock_stream?.Close(); + sock.Client.Close(); + sock.Close(); + sock=null; + sock_stream=null; } } @@ -353,11 +354,10 @@ public void close() { /// protected void _handshake() { var ser = PyroSerializer.GetFor(Config.SERIALIZER); - var handshakedata = new Dictionary(); - handshakedata["handshake"] = pyroHandshake; + var handshakedata = new Dictionary {["handshake"] = pyroHandshake}; if(Config.METADATA) handshakedata["object"] = objectid; - byte[] data = ser.serializeData(handshakedata); + var data = ser.serializeData(handshakedata); ushort flags = Config.METADATA? Message.FLAGS_META_ON_CONNECT : (ushort)0; var msg = new Message(Message.MSG_CONNECT, data, ser.serializer_id, flags, sequenceNr, annotations(), pyroHmacKey); IOUtil.send(sock_stream, msg.to_bytes()); @@ -381,24 +381,28 @@ protected void _handshake() { handshake_response = ""; } } - if(msg.type==Message.MSG_CONNECTOK) { - if((msg.flags & Message.FLAGS_META_ON_CONNECT) != 0) { - var response_dict = (IDictionary)handshake_response; - _processMetadata((IDictionary)response_dict["meta"]); - handshake_response = response_dict["handshake"]; - try { - validateHandshake(handshake_response); - } catch (Exception) { - close(); - throw; + switch (msg.type) + { + case Message.MSG_CONNECTOK: + if((msg.flags & Message.FLAGS_META_ON_CONNECT) != 0) { + var response_dict = (IDictionary)handshake_response; + _processMetadata((IDictionary)response_dict["meta"]); + handshake_response = response_dict["handshake"]; + try { + validateHandshake(handshake_response); + } catch (Exception) { + close(); + throw; + } } - } - } else if (msg.type==Message.MSG_CONNECTFAIL) { - close(); - throw new PyroException("connection rejected, reason: "+handshake_response); - } else { - close(); - throw new PyroException(string.Format("connect: invalid msg type {0} received", msg.type)); + + break; + case Message.MSG_CONNECTFAIL: + close(); + throw new PyroException("connection rejected, reason: "+handshake_response); + default: + close(); + throw new PyroException($"connect: invalid msg type {msg.type} received"); } } @@ -426,37 +430,39 @@ public virtual void responseAnnotations(IDictionary annotations, /// called by the Unpickler to restore state. /// /// args(8 or 9): pyroUri, pyroOneway(hashset), pyroMethods(set), pyroAttrs(set), pyroTimeout, pyroHmacKey, pyroHandshake, pyroMaxRetries, [pyroSerializer] + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + [SuppressMessage("ReSharper", "UnusedMember.Global")] public void __setstate__(object[] args) { if(args.Length != 8 && args.Length !=9) { throw new PyroException("invalid pickled proxy, using wrong pyro version?"); } PyroURI uri=(PyroURI)args[0]; - this.hostname=uri.host; - this.port=uri.port; - this.objectid=uri.objectid; - this.sock=null; - this.sock_stream=null; - this.correlation_id=null; + hostname=uri.host; + port=uri.port; + objectid=uri.objectid; + sock=null; + sock_stream=null; + correlation_id=null; - this.pyroOneway.Clear(); + pyroOneway.Clear(); foreach(object o in (HashSet) args[1]) - this.pyroOneway.Add(o as string); - this.pyroMethods.Clear(); + pyroOneway.Add(o as string); + pyroMethods.Clear(); foreach(object o in (HashSet) args[2]) - this.pyroMethods.Add(o as string); - this.pyroAttrs.Clear(); + pyroMethods.Add(o as string); + pyroAttrs.Clear(); foreach(object o in (HashSet) args[3]) - this.pyroAttrs.Add(o as string); + pyroAttrs.Add(o as string); - this.pyroHmacKey = (byte[])args[5]; - this.pyroHandshake = args[6]; + pyroHmacKey = (byte[])args[5]; + pyroHandshake = args[6]; // XXX maxretries (args[7]) is not yet supported/used in pyrolite // XXX custom serializer (args[8]) is not yet supported in pyrolite } public class StreamResultIterator: IEnumerable, IDisposable { - private string streamId; + private readonly string streamId; private PyroProxy proxy; public StreamResultIterator(string streamId, PyroProxy proxy) { @@ -477,20 +483,20 @@ public StreamResultIterator(string streamId, PyroProxy proxy) public IEnumerator GetEnumerator() { - if(this.proxy==null) + if(proxy==null) yield break; while(true) { - if(this.proxy.sock ==null) { + if(proxy.sock ==null) { throw new PyroException("the proxy for this stream result has been closed"); } object value; try { - value = this.proxy.internal_call("get_next_stream_item", Config.DAEMON_NAME, 0, false, this.streamId); + value = proxy.internal_call("get_next_stream_item", Config.DAEMON_NAME, 0, false, streamId); } catch (PyroException x) { if(stopIterationExceptions.Contains(x.PythonExceptionType)) { // iterator ended normally. no need to call close_stream, server will have closed the stream on its side already. - this.proxy = null; + proxy = null; yield break; } Dispose(); @@ -502,10 +508,10 @@ public IEnumerator GetEnumerator() public void Dispose() { - if(this.proxy!=null && this.proxy.sock!=null) { - this.proxy.internal_call("close_stream", Config.DAEMON_NAME, Message.FLAGS_ONEWAY, false, this.streamId); + if(proxy?.sock != null) { + proxy.internal_call("close_stream", Config.DAEMON_NAME, Message.FLAGS_ONEWAY, false, streamId); } - this.proxy = null; + proxy = null; } } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroProxyPickler.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroProxyPickler.cs index 1125d0b..13143f4 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroProxyPickler.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroProxyPickler.cs @@ -3,6 +3,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; @@ -15,18 +16,19 @@ namespace Razorvine.Pyro /// /// Pickler extension to be able to pickle PyroProxy objects. /// +[SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] public class PyroProxyPickler : IObjectPickler { public void pickle(object o, Stream outs, Pickler currentPickler) { PyroProxy proxy = (PyroProxy) o; outs.WriteByte(Opcodes.GLOBAL); - byte[] output=Encoding.Default.GetBytes("Pyro4.core\nProxy\n"); + var output=Encoding.Default.GetBytes("Pyro4.core\nProxy\n"); outs.Write(output,0,output.Length); outs.WriteByte(Opcodes.EMPTY_TUPLE); outs.WriteByte(Opcodes.NEWOBJ); // args(8): pyroUri, pyroOneway(hashset), pyroMethods(set), pyroAttrs(set), pyroTimeout, pyroHmacKey, pyroHandshake, pyroMaxRetries - object[] args = new object[] { + object[] args = { new PyroURI(proxy.objectid, proxy.hostname, proxy.port), proxy.pyroOneway, proxy.pyroMethods, @@ -47,7 +49,7 @@ public static IDictionary ToSerpentDict(object obj) // uri, oneway set, methods set, attrs set, timeout, hmac_key, handshake, maxretries (in this order) PyroProxy proxy = (PyroProxy)obj; var dict = new Hashtable(); - string uri = string.Format("PYRO:{0}@{1}:{2}", proxy.objectid, proxy.hostname, proxy.port); + string uri = $"PYRO:{proxy.objectid}@{proxy.hostname}:{proxy.port}"; string encodedHmac = proxy.pyroHmacKey!=null? "b64:"+Convert.ToBase64String(proxy.pyroHmacKey) : null; dict["state"] = new []{ uri, @@ -68,33 +70,33 @@ public static object FromSerpentDict(IDictionary dict) // note: the state array received in the dict conforms to the list produced by Pyro4's Proxy.__getstate_for_dict__ // that means, we must get an array of length 8: (the same as with ToSerpentDict above!) // uri, oneway set, methods set, attrs set, timeout, hmac_key, handshake, maxretries (in this order) - object[] state = (object[])dict["state"]; + var state = (object[])dict["state"]; PyroURI uri = new PyroURI((string)state[0]); var proxy = new PyroProxy(uri); // the following nasty piece of code is similar to _processMetaData from the PyroProxy // this is because the three collections can either be an array or a set - object[] oneway_array = state[1] as object[]; - object[] methods_array = state[2] as object[]; - object[] attrs_array = state[3] as object[]; - if(oneway_array!=null) - proxy.pyroOneway = new HashSet(oneway_array.Select(o=>o as string)); - else if((state[1] as HashSet) != null) - proxy.pyroOneway = state[1] as HashSet; + var onewayArray = state[1] as object[]; + var methodsArray = state[2] as object[]; + var attrsArray = state[3] as object[]; + if(onewayArray!=null) + proxy.pyroOneway = new HashSet(onewayArray.Select(o=>o as string)); + else if(state[1] is HashSet) + proxy.pyroOneway = (HashSet) state[1]; else proxy.pyroOneway = new HashSet ((state[1] as HashSet).Select(o=>o.ToString())); - if(methods_array!=null) - proxy.pyroMethods = new HashSet(methods_array.Select(o=>o as string)); - else if((state[2] as HashSet) != null) - proxy.pyroMethods = state[2] as HashSet; + if(methodsArray!=null) + proxy.pyroMethods = new HashSet(methodsArray.Select(o=>o as string)); + else if(state[2] is HashSet) + proxy.pyroMethods = (HashSet) state[2]; else proxy.pyroMethods = new HashSet((state[2] as HashSet).Select(o=>o.ToString())); - if(attrs_array!=null) - proxy.pyroAttrs = new HashSet(attrs_array.Select(o=>o as string)); - else if((state[3] as HashSet) != null) - proxy.pyroAttrs = state[3] as HashSet; + if(attrsArray!=null) + proxy.pyroAttrs = new HashSet(attrsArray.Select(o=>o as string)); + else if(state[3] is HashSet) + proxy.pyroAttrs = (HashSet) state[3]; else proxy.pyroAttrs = new HashSet((state[3] as HashSet).Select(o=>o.ToString())); diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroURI.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroURI.cs index 1d092b9..967a859 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroURI.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroURI.cs @@ -2,6 +2,8 @@ using System; using System.Text.RegularExpressions; +// ReSharper disable InconsistentNaming +// ReSharper disable UnusedMember.Global namespace Razorvine.Pyro { @@ -12,10 +14,10 @@ namespace Razorvine.Pyro [Serializable] public class PyroURI { - public string protocol {get;set;} - public string objectid {get;set;} - public string host {get;set;} - public int port {get;set;} + public string protocol {get; private set;} + public string objectid {get; private set;} + public string host {get; private set;} + public int port {get; private set;} public PyroURI() { @@ -35,7 +37,7 @@ public PyroURI(string uri) { if (m.Success) { protocol = m.Groups[1].Value; objectid = m.Groups[2].Value; - string[] loc = m.Groups[4].Value.Split(':'); + var loc = m.Groups[4].Value.Split(':'); host = loc[0]; port = int.Parse(loc[1]); } else { @@ -44,7 +46,7 @@ public PyroURI(string uri) { } public PyroURI(string objectid, string host, int port) { - this.protocol = "PYRO"; + protocol = "PYRO"; this.objectid = objectid; this.host = host; this.port = port; @@ -60,7 +62,7 @@ public override bool Equals(object obj) PyroURI other = obj as PyroURI; if (other == null) return false; - return other.ToString()==this.ToString(); + return other.ToString()==ToString(); } public override int GetHashCode() @@ -88,10 +90,10 @@ public override int GetHashCode() * called by the Unpickler to restore state */ public void __setstate__(object[] args) { - this.protocol = (string) args[0]; - this.objectid = (string) args[1]; - this.host = (string) args[3]; - this.port = (int) args[4]; + protocol = (string) args[0]; + objectid = (string) args[1]; + host = (string) args[3]; + port = (int) args[4]; } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroUriPickler.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroUriPickler.cs index cd78845..f5dd789 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroUriPickler.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroUriPickler.cs @@ -17,7 +17,7 @@ public class PyroUriPickler : IObjectPickler { public void pickle(object o, Stream outs, Pickler currentPickler) { PyroURI uri = (PyroURI) o; outs.WriteByte(Opcodes.GLOBAL); - byte[] output=Encoding.Default.GetBytes("Pyro4.core\nURI\n"); + var output=Encoding.Default.GetBytes("Pyro4.core\nURI\n"); outs.Write(output,0,output.Length); outs.WriteByte(Opcodes.EMPTY_TUPLE); outs.WriteByte(Opcodes.NEWOBJ); @@ -34,15 +34,17 @@ public void pickle(object o, Stream outs, Pickler currentPickler) { public static IDictionary ToSerpentDict(object obj) { PyroURI uri = (PyroURI)obj; - var dict = new Hashtable(); - dict["state"] = new object[]{uri.protocol, uri.objectid, null, uri.host, uri.port}; - dict["__class__"] = "Pyro4.core.URI"; + var dict = new Hashtable + { + ["state"] = new object[] {uri.protocol, uri.objectid, null, uri.host, uri.port}, + ["__class__"] = "Pyro4.core.URI" + }; return dict; } public static object FromSerpentDict(IDictionary dict) { - object[] state = (object[])dict["state"]; // protocol, objectid, socketname, hostname, port + var state = (object[])dict["state"]; // protocol, objectid, socketname, hostname, port return new PyroURI((string)state[1], (string)state[3], (int)state[4]); } } diff --git a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Serializers.cs b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Serializers.cs index cb05ab9..e024275 100644 --- a/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Serializers.cs +++ b/dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/Serializers.cs @@ -8,6 +8,8 @@ using Razorvine.Pickle; using Razorvine.Pickle.Objects; // ReSharper disable MemberCanBePrivate.Global +// ReSharper disable InconsistentNaming +// ReSharper disable MemberCanBeMadeStatic.Global namespace Razorvine.Pyro { @@ -41,16 +43,13 @@ public static PyroSerializer GetFor(Config.SerializerType type) // and it will become available once you copy that into the correct location. lock(typeof(SerpentSerializer)) { - if(serpentSerializer==null) - { - try { - serpentSerializer = new SerpentSerializer(); - return serpentSerializer; - } catch (TypeInitializationException x) { - throw new PyroException("serpent serializer unavailable", x); - } + if (serpentSerializer != null) return serpentSerializer; + try { + serpentSerializer = new SerpentSerializer(); + return serpentSerializer; + } catch (TypeInitializationException x) { + throw new PyroException("serpent serializer unavailable", x); } - return serpentSerializer; } } default: @@ -103,7 +102,7 @@ public override byte[] serializeCall(string objectId, string method, object[] va { using(var p=new Pickler()) { - object[] invokeparams = new object[] {objectId, method, vargs, kwargs}; + object[] invokeparams = {objectId, method, vargs, kwargs}; return p.dumps(invokeparams); } } @@ -162,6 +161,9 @@ static SerpentSerializer() // register a few custom class-to-dict converters MethodInfo registerMethod = serpentSerializerType.GetMethod("RegisterClass", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); + if (registerMethod == null) + throw new PyroException("serpent library doesn't provide expected RegisterClass method"); + Func converter = PyroUriPickler.ToSerpentDict; registerMethod.Invoke(null, new object[]{typeof(PyroURI), converter}); converter = PyroExceptionPickler.ToSerpentDict; @@ -199,7 +201,7 @@ public override byte[] serializeData(object obj) public override byte[] serializeCall(string objectId, string method, object[] vargs, IDictionary kwargs) { - object[] invokeparams = new object[] {objectId, method, vargs, kwargs}; + object[] invokeparams = {objectId, method, vargs, kwargs}; // call the "Serialize" method, using reflection var serializer = Activator.CreateInstance(serpentSerializerType, Config.SERPENT_INDENT, Config.SERPENT_SET_LITERALS, true); return (byte[]) serializeMethod.Invoke(serializer, new object[] {invokeparams}); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pickle/ArrayConstructorTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pickle/ArrayConstructorTests.cs index 57be441..189039e 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pickle/ArrayConstructorTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pickle/ArrayConstructorTests.cs @@ -15,7 +15,7 @@ namespace Pyrolite.Tests.Pickle public class ArrayConstructorTest { [Fact] - public void testInvalidMachineTypes() + public void TestInvalidMachineTypes() { ArrayConstructor ac=new ArrayConstructor(); try { @@ -55,20 +55,20 @@ public void testInvalidMachineTypes() } [Fact] - public void testChars() + public void TestChars() { ArrayConstructor ac=new ArrayConstructor(); - char EURO=(char)0x20ac; + const char eurochar = (char)0x20ac; // c/u - Assert.Equal(new []{'A',EURO}, (char[])ac.construct('c', 18, new byte[]{65,0,0xac,0x20})); - Assert.Equal(new []{'A',EURO}, (char[])ac.construct('u', 18, new byte[]{65,0,0xac,0x20})); - Assert.Equal(new []{'A',EURO}, (char[])ac.construct('c', 19, new byte[]{0,65,0x20,0xac})); - Assert.Equal(new []{'A',EURO}, (char[])ac.construct('u', 19, new byte[]{0,65,0x20,0xac})); - Assert.Equal(new []{'A',EURO}, (char[])ac.construct('c', 20, new byte[]{65,0,0,0,0xac,0x20,0,0})); - Assert.Equal(new []{'A',EURO}, (char[])ac.construct('u', 20, new byte[]{65,0,0,0,0xac,0x20,0,0})); - Assert.Equal(new []{'A',EURO}, (char[])ac.construct('c', 21, new byte[]{0,0,0,65,0,0,0x20,0xac})); - Assert.Equal(new []{'A',EURO}, (char[])ac.construct('u', 21, new byte[]{0,0,0,65,0,0,0x20,0xac})); + Assert.Equal(new []{'A',eurochar}, (char[])ac.construct('c', 18, new byte[]{65,0,0xac,0x20})); + Assert.Equal(new []{'A',eurochar}, (char[])ac.construct('u', 18, new byte[]{65,0,0xac,0x20})); + Assert.Equal(new []{'A',eurochar}, (char[])ac.construct('c', 19, new byte[]{0,65,0x20,0xac})); + Assert.Equal(new []{'A',eurochar}, (char[])ac.construct('u', 19, new byte[]{0,65,0x20,0xac})); + Assert.Equal(new []{'A',eurochar}, (char[])ac.construct('c', 20, new byte[]{65,0,0,0,0xac,0x20,0,0})); + Assert.Equal(new []{'A',eurochar}, (char[])ac.construct('u', 20, new byte[]{65,0,0,0,0xac,0x20,0,0})); + Assert.Equal(new []{'A',eurochar}, (char[])ac.construct('c', 21, new byte[]{0,0,0,65,0,0,0x20,0xac})); + Assert.Equal(new []{'A',eurochar}, (char[])ac.construct('u', 21, new byte[]{0,0,0,65,0,0,0x20,0xac})); try { ac.construct('u', 21, new byte[]{0,1,0,65}); // out of range codepoint Assert.True(false, "expected error"); @@ -82,7 +82,7 @@ public void testChars() } [Fact] - public void testInts() + public void TestInts() { ArrayConstructor ac=new ArrayConstructor(); @@ -152,7 +152,7 @@ public void testInts() } [Fact] - public void testFloats() + public void TestFloats() { // f/d ArrayConstructor ac=new ArrayConstructor(); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pickle/AssertUtils.cs b/dotnet/Razorvine.Pyrolite/Tests/Pickle/AssertUtils.cs index 142c982..7397282 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pickle/AssertUtils.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pickle/AssertUtils.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; +using System.Linq; using Xunit; // ReSharper disable CheckNamespace @@ -10,8 +11,7 @@ namespace Pyrolite.Tests.Pickle /// /// Some assertion things that don't appear to be in Nunit. /// - -static class AssertUtils +internal static class AssertUtils { public static void AssertEqual(IDictionary expected, object actual) { @@ -27,10 +27,10 @@ public static void AssertEqual(IDictionary expected, object actual) foreach(object key in expected.Keys) { object ev=expected[key]; object av=actualdict[key]; - if(ev is IDictionary) { - AssertEqual((IDictionary)ev, av); - } else - { + var dictionary = ev as IDictionary; + if(dictionary != null) { + AssertEqual(dictionary, av); + } else { Assert.Equal(ev, av); // dictionary values must be the same } } @@ -39,11 +39,8 @@ public static void AssertEqual(IDictionary expected, object actual) public static void AssertEqual(HashSet expected, object actual) { if(expected.Equals(actual)) return; - List expectedvalues=new List(expected); - List actualvalues=new List(); - foreach(object x in (IEnumerable)actual) { - actualvalues.Add((T)x); - } + var expectedvalues=new List(expected); + var actualvalues= ((IEnumerable) actual).Cast().ToList(); Assert.Equal(expectedvalues, actualvalues); // hashsets must be equal } } diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pickle/PickleUtilsTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pickle/PickleUtilsTests.cs index bd3677d..f5bb92a 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pickle/PickleUtilsTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pickle/PickleUtilsTests.cs @@ -1,6 +1,5 @@ /* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ -using System; using System.IO; using System.Text; using Xunit; @@ -16,15 +15,15 @@ namespace Pyrolite.Tests.Pickle /// public class PickleUtilsTest { - private readonly byte[] filedata; + private readonly byte[] _filedata; public PickleUtilsTest() { - filedata=Encoding.UTF8.GetBytes("str1\nstr2 \n str3 \nend"); + _filedata=Encoding.UTF8.GetBytes("str1\nstr2 \n str3 \nend"); } [Fact] - public void testReadline() { - Stream bis = new MemoryStream(filedata); + public void TestReadline() { + Stream bis = new MemoryStream(_filedata); Assert.Equal("str1", PickleUtils.readline(bis)); Assert.Equal("str2 ", PickleUtils.readline(bis)); Assert.Equal(" str3 ", PickleUtils.readline(bis)); @@ -38,8 +37,8 @@ public void testReadline() { } [Fact] - public void testReadlineWithLF() { - Stream bis=new MemoryStream(filedata); + public void TestReadlineWithLf() { + Stream bis=new MemoryStream(_filedata); Assert.Equal("str1\n", PickleUtils.readline(bis, true)); Assert.Equal("str2 \n", PickleUtils.readline(bis, true)); Assert.Equal(" str3 \n", PickleUtils.readline(bis, true)); @@ -53,8 +52,8 @@ public void testReadlineWithLF() { } [Fact] - public void testReadbytes() { - Stream bis=new MemoryStream(filedata); + public void TestReadbytes() { + Stream bis=new MemoryStream(_filedata); Assert.Equal(115, PickleUtils.readbyte(bis)); Assert.Equal(new byte[]{}, PickleUtils.readbytes(bis, 0)); @@ -69,9 +68,9 @@ public void testReadbytes() { } [Fact] - public void testReadbytes_into() { - Stream bis=new MemoryStream(filedata); - byte[] bytes = new byte[] {0,0,0,0,0,0,0,0,0,0}; + public void TestReadbytes_into() { + Stream bis=new MemoryStream(_filedata); + byte[] bytes = {0,0,0,0,0,0,0,0,0,0}; PickleUtils.readbytes_into(bis, bytes, 1, 4); Assert.Equal(new byte[] {0,115,116,114,49,0,0,0,0,0}, bytes); PickleUtils.readbytes_into(bis, bytes, 8, 1); @@ -79,7 +78,7 @@ public void testReadbytes_into() { } [Fact] - public void testBytes_to_integer() { + public void TestBytes_to_integer() { try { PickleUtils.bytes_to_integer(new byte[] {}); Assert.True(false, "expected PickleException"); @@ -105,7 +104,7 @@ public void testBytes_to_integer() { } [Fact] - public void testBytes_to_uint() { + public void TestBytes_to_uint() { try { PickleUtils.bytes_to_uint(new byte[] {},0); Assert.True(false, "expected PickleException"); @@ -121,7 +120,7 @@ public void testBytes_to_uint() { } [Fact] - public void testBytes_to_long() { + public void TestBytes_to_long() { try { PickleUtils.bytes_to_long(new byte[] {}, 0); Assert.True(false, "expected PickleException"); @@ -142,7 +141,7 @@ public void testBytes_to_long() { } [Fact] - public void testInteger_to_bytes() + public void TestInteger_to_bytes() { Assert.Equal(new byte[]{0,0,0,0}, PickleUtils.integer_to_bytes(0)); Assert.Equal(new byte[]{0x78, 0x56, 0x34, 0x12}, PickleUtils.integer_to_bytes(0x12345678)); @@ -154,7 +153,7 @@ public void testInteger_to_bytes() } [Fact] - public void testBytes_to_double() { + public void TestBytes_to_double() { try { PickleUtils.bytes_bigendian_to_double(new byte[] {} ,0); Assert.True(false, "expected PickleException"); @@ -183,7 +182,7 @@ public void testBytes_to_double() { } [Fact] - public void testBytes_to_float() { + public void TestBytes_to_float() { try { PickleUtils.bytes_bigendian_to_float(new byte[] {}, 0); Assert.True(false, "expected PickleException"); @@ -205,7 +204,7 @@ public void testBytes_to_float() { } [Fact] - public void testDouble_to_bytes() + public void TestDouble_to_bytes() { Assert.Equal(new byte[]{0,0,0,0,0,0,0,0}, PickleUtils.double_to_bytes_bigendian(0.0d)); Assert.Equal(new byte[]{0x3f,0xf0,0,0,0,0,0,0}, PickleUtils.double_to_bytes_bigendian(1.0d)); @@ -215,12 +214,12 @@ public void testDouble_to_bytes() Assert.Equal(new byte[]{0x7e,0x3d,0x7e,0xe8,0xbc,0xaf,0x28,0x3a}, PickleUtils.double_to_bytes_bigendian(1.23456789e300d)); // cannot test NaN because it's not always the same byte representation... // Assert.Equal(new byte[]{0xff,0xf8,0,0,0,0,0,0}, p.double_to_bytes(Double.NaN)); - Assert.Equal(new byte[]{0x7f,0xf0,0,0,0,0,0,0}, PickleUtils.double_to_bytes_bigendian(Double.PositiveInfinity)); - Assert.Equal(new byte[]{0xff,0xf0,0,0,0,0,0,0}, PickleUtils.double_to_bytes_bigendian(Double.NegativeInfinity)); + Assert.Equal(new byte[]{0x7f,0xf0,0,0,0,0,0,0}, PickleUtils.double_to_bytes_bigendian(double.PositiveInfinity)); + Assert.Equal(new byte[]{0xff,0xf0,0,0,0,0,0,0}, PickleUtils.double_to_bytes_bigendian(double.NegativeInfinity)); } [Fact] - public void testDecode_long() + public void TestDecode_long() { Assert.Equal(0L, PickleUtils.decode_long(new byte[0])); Assert.Equal(0L, PickleUtils.decode_long(new byte[]{0})); @@ -244,7 +243,7 @@ public void testDecode_long() } [Fact] - public void testDecode_escaped() + public void TestDecode_escaped() { Assert.Equal("abc", PickleUtils.decode_escaped("abc")); Assert.Equal("a\\c", PickleUtils.decode_escaped("a\\\\c")); @@ -256,7 +255,7 @@ public void testDecode_escaped() } [Fact] - public void testDecode_unicode_escaped() + public void TestDecode_unicode_escaped() { Assert.Equal("abc", PickleUtils.decode_unicode_escaped("abc")); Assert.Equal("a\\c", PickleUtils.decode_unicode_escaped("a\\\\c")); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pickle/PicklerTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pickle/PicklerTests.cs index a3d32cf..6c872d2 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pickle/PicklerTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pickle/PicklerTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.IO; using Xunit; @@ -28,11 +29,11 @@ namespace Pyrolite.Tests.Pickle /// public class PicklerTests { - byte[] B(string s) { + private static byte[] B(string s) { return B(PickleUtils.str2bytes(s)); } - byte[] B(byte[] bytes) { + private static byte[] B(byte[] bytes) { byte[] result=new byte[bytes.Length+3]; result[0]=Opcodes.PROTO; result[1]=2; @@ -41,17 +42,16 @@ byte[] B(byte[] bytes) { return result; } - string S(byte[] pickled) { + private static string S(byte[] pickled) { return PickleUtils.rawStringFromBytes(pickled); } private enum DayEnum { - SUNDAY, MONDAY, TUESDAY, WEDNESDAY, - THURSDAY, FRIDAY, SATURDAY - }; + Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday + } [Fact] - public void testSinglePrimitives() { + public void TestSinglePrimitives() { // protocol level 2 Pickler p=new Pickler(false); byte[] o=p.dumps(null); // none @@ -87,13 +87,13 @@ public void testSinglePrimitives() { o=p.dumps(1234.9876543210987654321m); Assert.Equal(B("cdecimal\nDecimal\nX\u0018\u0000\u0000\u00001234.9876543210987654321\u0085R"), o); - DayEnum day=DayEnum.WEDNESDAY; + const DayEnum day = DayEnum.Wednesday; o=p.dumps(day); // enum is returned as just a string representing the value - Assert.Equal(B("X\u0009\u0000\u0000\u0000WEDNESDAY"),o); + Assert.Equal(B("X\u0009\u0000\u0000\u0000Wednesday"),o); } [Fact] - public void testArrays() + public void TestArrays() { Pickler p = new Pickler(false); var o = p.dumps(new string[] {}); @@ -127,7 +127,7 @@ public void testArrays() public void TestRecursiveArray2() { Pickler p = new Pickler(false); - object[] a = new object[] { "hello", "placeholder" }; + object[] a = { "hello", "placeholder" }; a[1] = a; // make it recursive Assert.Throws(() => p.dumps(a)); // "recursive array not supported, use list" } @@ -136,13 +136,13 @@ public void TestRecursiveArray2() public void TestRecursiveArray6() { Pickler p = new Pickler(false); - object[] a = new object[] { "a","b","c","d","e","f" }; + object[] a = { "a","b","c","d","e","f" }; a[5] = a; // make it recursive Assert.Throws(() => p.dumps(a)); // "recursive array not supported, use list" } [Fact] - public void testDates() + public void TestDates() { Pickler p=new Pickler(false); Unpickler u=new Unpickler(); @@ -159,7 +159,7 @@ public void testDates() } [Fact] - public void testTimes() + public void TestTimes() { Pickler p=new Pickler(false); Unpickler u=new Unpickler(); @@ -172,7 +172,7 @@ public void testTimes() } [Fact] - public void testSets() + public void TestSets() { Pickler p=new Pickler(false); Unpickler up=new Unpickler(); @@ -189,7 +189,7 @@ public void testSets() } [Fact] - public void testMappings() + public void TestMappings() { Pickler p=new Pickler(false); Unpickler pu=new Unpickler(); @@ -210,7 +210,7 @@ public void testMappings() } [Fact] - public void testLists() + public void TestLists() { Pickler p=new Pickler(false); @@ -244,10 +244,10 @@ public void testLists() } [Fact] - public void testMemoizationSet() + public void TestMemoizationSet() { var set = new HashSet {"a"}; - object[] array = new object[] {set, set}; + object[] array = {set, set}; Pickler p = new Pickler(true); byte[] data = p.dumps(array); @@ -268,7 +268,7 @@ public void testMemoizationSet() } [Fact] - public void testMemoizationMap() + public void TestMemoizationMap() { var map = new Dictionary {{"key", "value"}}; object[] array = {map, map}; @@ -292,11 +292,11 @@ public void testMemoizationMap() } [Fact] - public void testMemoizationCollection() + public void TestMemoizationCollection() { ICollection list = new List(); list.Add("a"); - object[] array = new object[] {list, list}; + object[] array = {list, list}; Pickler p = new Pickler(true); byte[] data = p.dumps(array); @@ -317,12 +317,12 @@ public void testMemoizationCollection() } [Fact] - public void testMemoizationTimeStuff() + public void TestMemoizationTimeStuff() { TimeSpan delta = new TimeSpan(1,2,3); DateTime time = new DateTime(2014,11,20,1,2,3); - object[] array = new object[] {delta, delta, time, time}; + object[] array = {delta, delta, time, time}; Pickler p = new Pickler(true); byte[] data = p.dumps(array); @@ -345,11 +345,11 @@ public void testMemoizationTimeStuff() } [Fact] - public void testMemoizationDecimal() + public void TestMemoizationDecimal() { decimal bigd = 12345678901234567890.99887766m; - object[] array = new object[] {bigd, bigd}; + object[] array = {bigd, bigd}; Pickler p = new Pickler(true); byte[] data = p.dumps(array); @@ -367,10 +367,10 @@ public void testMemoizationDecimal() } [Fact] - public void testMemoizationString() + public void TestMemoizationString() { string str = "a"; - object[] array = new object[] {str, str}; + object[] array = {str, str}; Pickler p = new Pickler(true); byte[] data = p.dumps(array); @@ -390,9 +390,9 @@ public void testMemoizationString() } [Fact] - public void testMemoizationArray() + public void TestMemoizationArray() { - int[] arr = new int[] { 1, 2, 3}; + int[] arr = { 1, 2, 3}; object array = new object[] {arr, arr}; Pickler p = new Pickler(true); byte[] data = p.dumps(array); @@ -413,12 +413,11 @@ public void testMemoizationArray() } [Fact] - public void testMemoizationList() + public void TestMemoizationList() { Pickler p=new Pickler(); - - string reused = "reused"; - string another = "another"; + const string reused = "reused"; + const string another = "another"; IList list=new ArrayList(); IList sublist = new ArrayList(); sublist.Add(reused); @@ -450,7 +449,7 @@ public void testMemoizationList() } [Fact] - public void testMemoizationRecursiveNoMemo() + public void TestMemoizationRecursiveNoMemo() { Pickler p=new Pickler(false); @@ -463,7 +462,7 @@ public void testMemoizationRecursiveNoMemo() } [Fact] - public void testMemoizationRecursiveMemo() + public void TestMemoizationRecursiveMemo() { Pickler p=new Pickler(); @@ -504,9 +503,9 @@ public class Person { public int[] Values {get;} public Person(string name, bool deceased, int[] values) { - this.Name=name; - this.Deceased=deceased; - this.Values = values; + Name=name; + Deceased=deceased; + Values = values; } } @@ -520,7 +519,7 @@ public Relative(string name, bool deceased, int[] values) : base(name, deceased, [Fact] - public void testClass() + public void TestClass() { Pickler p=new Pickler(false); Unpickler pu=new Unpickler(); @@ -532,34 +531,38 @@ public void testClass() Assert.Equal("Pyrolite.Tests.Pickle.PicklerTests+Relative", map["__class__"]); Assert.Equal("Tupac", map["Name"]); Assert.Equal("unspecified", map["Relation"]); - Assert.True((Boolean) map["Deceased"]); + Assert.True((bool) map["Deceased"]); Assert.Equal(new [] {3,4,5}, map["Values"]); } - class NotABean { - public int x; + [SuppressMessage("ReSharper", "NotAccessedField.Global")] + public class NotABean { + public int Xantippe; } [Fact] - public void testFailure() + public void TestFailure() { - NotABean notabean = new NotABean {x = 42}; + NotABean notabean = new NotABean {Xantippe = 42}; Pickler p=new Pickler(false); Assert.Throws(() => p.dumps(notabean)); } - class CustomClass { - public int x=42; + [SuppressMessage("ReSharper", "ConvertToConstant.Global")] + public class CustomClass { + // ReSharper disable once ConvertToConstant.Local + public readonly int Xantippe=42; } - class CustomClassPickler : IObjectPickler { + + public class CustomClassPickler : IObjectPickler { public void pickle(object o, Stream outs, Pickler currentpickler) { CustomClass c=(CustomClass)o; - currentpickler.save("customclassint="+c.x); // write a string representation + currentpickler.save("customclassint="+c.Xantippe); // write a string representation } } [Fact] - public void testCustomPickler() + public void TestCustomPickler() { Pickler.registerCustomPickler(typeof(CustomClass), new CustomClassPickler()); CustomClass c=new CustomClass(); @@ -572,7 +575,7 @@ public void testCustomPickler() } [Fact] - public void testAnonType() + public void TestAnonType() { var x = new { Name="Harry", Country="UK", Age=34 }; Pickler p = new Pickler(); @@ -587,23 +590,23 @@ public void testAnonType() } - interface IBaseInterface {}; - interface ISubInterface : IBaseInterface {}; - class BaseClassWithInterface : IBaseInterface {}; - class SubClassWithInterface : BaseClassWithInterface, ISubInterface {}; - class BaseClass {}; - class SubClass : BaseClass {}; - abstract class AbstractBaseClass {}; - class ConcreteSubClass : AbstractBaseClass {}; - - class AnyClassPickler : IObjectPickler { + internal interface IBaseInterface {} + internal interface ISubInterface : IBaseInterface {} + internal class BaseClassWithInterface : IBaseInterface {} + internal class SubClassWithInterface : BaseClassWithInterface, ISubInterface {} + internal class BaseClass {} + internal class SubClass : BaseClass {} + internal abstract class AbstractBaseClass {} + internal class ConcreteSubClass : AbstractBaseClass {} + + internal class AnyClassPickler : IObjectPickler { public void pickle(object o, Stream outs, Pickler currentpickler) { currentpickler.save("[class="+o.GetType().FullName+"]"); } } [Fact] - public void testAbstractBaseClassHierarchyPickler() + public void TestAbstractBaseClassHierarchyPickler() { ConcreteSubClass c = new ConcreteSubClass(); Pickler p = new Pickler(false); @@ -621,7 +624,7 @@ public void testAbstractBaseClassHierarchyPickler() } [Fact] - public void testInterfaceHierarchyPickler() + public void TestInterfaceHierarchyPickler() { BaseClassWithInterface b = new BaseClassWithInterface(); SubClassWithInterface sub = new SubClassWithInterface(); @@ -648,7 +651,7 @@ public void testInterfaceHierarchyPickler() [Serializable] - class SerializableThing + public class SerializableThing { [NonSerialized] public string NotThisOne = "apple"; @@ -659,7 +662,7 @@ class SerializableThing } [DataContract(Name="CustomContractName", Namespace="http://namespace")] - class DataContractThing + public class DataContractThing { public string NotThisOne = "apple"; @@ -710,7 +713,7 @@ public void TestDatacontractAttr() /// public class MiscellaneousTests { [Fact] - public void testPythonExceptionType() + public void TestPythonExceptionType() { var ex=new PythonException("hello"); var type = ex.GetType(); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleComplexTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleComplexTests.cs index 58c1fec..ce5fba4 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleComplexTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleComplexTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Security.Cryptography; @@ -21,11 +22,11 @@ namespace Pyrolite.Tests.Pickle /// public class UnpickleComplexTests { - object U(string strdata) + private static object U(string strdata) { return U(PickleUtils.str2bytes(strdata)); } - object U(byte[] data) + private static object U(byte[] data) { using(Unpickler u=new Unpickler()) { @@ -34,29 +35,29 @@ object U(byte[] data) } [Fact] - public void testPickleUnpickleURI() { + public void TestPickleUnpickleUri() { PyroURI uri=new PyroURI("PYRO:test@localhost:9999"); PyroSerializer ser = new PickleSerializer(); - byte[] pickled_uri=ser.serializeData(uri); - PyroURI uri2=(PyroURI) ser.deserializeData(pickled_uri); + var pickledUri=ser.serializeData(uri); + PyroURI uri2=(PyroURI) ser.deserializeData(pickledUri); Assert.Equal(uri,uri2); uri=new PyroURI(); - pickled_uri=ser.serializeData(uri); - uri2=(PyroURI) ser.deserializeData(pickled_uri); + pickledUri=ser.serializeData(uri); + uri2=(PyroURI) ser.deserializeData(pickledUri); Assert.Equal(uri,uri2); } [Fact] - public void testPickleUnpickleProxy() { + public void TestPickleUnpickleProxy() { PyroProxy proxy = new PyroProxy("hostname", 9999, "objectid") { pyroHmacKey = Encoding.UTF8.GetBytes("secret"), pyroHandshake = "apples" }; PyroSerializer ser = new PickleSerializer(); - byte[] pickled_proxy=ser.serializeData(proxy); - PyroProxy result = (PyroProxy) ser.deserializeData(pickled_proxy); + var pickledProxy=ser.serializeData(proxy); + PyroProxy result = (PyroProxy) ser.deserializeData(pickledProxy); Assert.Equal(proxy.hostname, result.hostname); Assert.Equal(proxy.objectid, result.objectid); Assert.Equal(proxy.port, result.port); @@ -65,32 +66,32 @@ public void testPickleUnpickleProxy() { } [Fact] - public void testUnpickleRealProxy2() { - byte[] pickled_proxy=File.ReadAllBytes("pickled_nameserver_proxy_p2.dat"); - unpickleRealProxy(pickled_proxy); + public void TestUnpickleRealProxy2() { + var pickledProxy=File.ReadAllBytes("pickled_nameserver_proxy_p2.dat"); + UnpickleRealProxy(pickledProxy); } [Fact] - public void testUnpickleRealProxy2old() { - byte[] pickled_proxy=File.ReadAllBytes("pickled_nameserver_proxy_p2old.dat"); - unpickleRealProxy(pickled_proxy); + public void TestUnpickleRealProxy2Old() { + var pickledProxy=File.ReadAllBytes("pickled_nameserver_proxy_p2old.dat"); + UnpickleRealProxy(pickledProxy); } [Fact] - public void testUnpickleRealProxy3() { - byte[] pickled_proxy=File.ReadAllBytes("pickled_nameserver_proxy_p3.dat"); - unpickleRealProxy(pickled_proxy); + public void TestUnpickleRealProxy3() { + var pickledProxy=File.ReadAllBytes("pickled_nameserver_proxy_p3.dat"); + UnpickleRealProxy(pickledProxy); } [Fact] - public void testUnpickleRealProxy4() { - byte[] pickled_proxy=File.ReadAllBytes("pickled_nameserver_proxy_p4.dat"); - unpickleRealProxy(pickled_proxy); + public void TestUnpickleRealProxy4() { + var pickledProxy=File.ReadAllBytes("pickled_nameserver_proxy_p4.dat"); + UnpickleRealProxy(pickledProxy); } [Fact] - public void testUnpickleProto0Bytes() { - byte[] pickle = File.ReadAllBytes("pickled_bytes_level0.dat"); + public void TestUnpickleProto0Bytes() { + var pickle = File.ReadAllBytes("pickled_bytes_level0.dat"); PickleSerializer ser = new PickleSerializer(); string x = (string)ser.deserializeData(pickle); @@ -98,14 +99,14 @@ public void testUnpickleProto0Bytes() { // validate that the bytes in the string are what we expect (based on md5 hash) var m = SHA1.Create(); - byte[] hashb = m.ComputeHash(Encoding.UTF8.GetBytes(x)); + var hashb = m.ComputeHash(Encoding.UTF8.GetBytes(x)); string digest = BitConverter.ToString(hashb); Assert.Equal("22-f4-5b-87-63-83-c9-1b-1c-b2-0a-fe-51-ee-3b-30-f5-a8-5d-4c", digest.ToLowerInvariant()); } - private void unpickleRealProxy(byte[] pickled_proxy) { + private static void UnpickleRealProxy(byte[] pickledProxy) { PyroSerializer ser = new PickleSerializer(); - PyroProxy proxy=(PyroProxy)ser.deserializeData(pickled_proxy); + PyroProxy proxy=(PyroProxy)ser.deserializeData(pickledProxy); Assert.Equal("Pyro.NameServer",proxy.objectid); Assert.Equal("localhost",proxy.hostname); Assert.Equal(9090,proxy.port); @@ -128,11 +129,10 @@ private void unpickleRealProxy(byte[] pickled_proxy) { } [Fact] - public void testUnpickleMemo() { + public void TestUnpickleMemo() { // the pickle is of the following list: [65, 'hello', 'hello', {'recurse': [...]}, 'hello'] // i.e. the 4th element is a dict referring back to the list itself and the 'hello' strings are reused - byte[] pickle = new byte[] - {128, 2, 93, 113, 0, 40, 75, 65, 85, 5, 104, 101, 108, 108, 111, 113, 1, 104, 1, 125, 113, 2, + byte[] pickle = {128, 2, 93, 113, 0, 40, 75, 65, 85, 5, 104, 101, 108, 108, 111, 113, 1, 104, 1, 125, 113, 2, 85, 7, 114, 101, 99, 117, 114, 115, 101, 113, 3, 104, 0, 115, 104, 1, 101, 46}; ArrayList a = (ArrayList) U(pickle); Assert.Equal(5, a.Count); @@ -146,99 +146,103 @@ public void testUnpickleMemo() { [Fact] - public void testUnpickleUnsupportedClass() { + public void TestUnpickleUnsupportedClass() { // an unsupported class is mapped to a dictionary containing the class's attributes, and a __class__ attribute with the name of the class - byte[] pickled = new byte[] {128, 2, 99, 95, 95, 109, 97, 105, 110, 95, 95, 10, 67, 117, 115, 116, 111, 109, 67, 108, 97, 115, 115, 10, 113, 0, 41, 129, 113, 1, 125, 113, 2, 40, 85, 3, 97, 103, 101, 113, 3, 75, 34, 85, 6, 118, 97, 108, 117, 101, 115, 113, 4, 93, 113, 5, 40, 75, 1, 75, 2, 75, 3, 101, 85, 4, 110, 97, 109, 101, 113, 6, 85, 5, 72, 97, 114, 114, 121, 113, 7, 117, 98, 46}; - IDictionary o = (IDictionary ) U(pickled); + byte[] pickled = {128, 2, 99, 95, 95, 109, 97, 105, 110, 95, 95, 10, 67, 117, 115, 116, 111, 109, 67, 108, 97, 115, 115, 10, 113, 0, 41, 129, 113, 1, 125, 113, 2, 40, 85, 3, 97, 103, 101, 113, 3, 75, 34, 85, 6, 118, 97, 108, 117, 101, 115, 113, 4, 93, 113, 5, 40, 75, 1, 75, 2, 75, 3, 101, 85, 4, 110, 97, 109, 101, 113, 6, 85, 5, 72, 97, 114, 114, 121, 113, 7, 117, 98, 46}; + var o = (IDictionary ) U(pickled); Assert.Equal(4, o.Count); Assert.Equal("Harry", o["name"]); Assert.Equal(34, o["age"]); - Assert.Equal(new ArrayList() {1,2,3}, o["values"]); + Assert.Equal(new ArrayList {1,2,3}, o["values"]); Assert.Equal("__main__.CustomClass", o["__class__"]); } - class CustomClazz { - public string name; - public int age; - public ArrayList values; + [SuppressMessage("ReSharper", "SuggestBaseTypeForParameter")] + [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] + public class CustomClazz { + public string Name; + public int Age; + public ArrayList Values; public CustomClazz() { } public CustomClazz(string name, int age, ArrayList values) { - this.name=name; - this.age=age; - this.values=values; + Name=name; + Age=age; + Values=values; } /** * called by the Unpickler to restore state. */ // ReSharper disable once UnusedMember.Local + // ReSharper disable once UnusedMember.Global public void __setstate__(Hashtable args) { - this.name = (string) args["name"]; - this.age = (int) args["age"]; - this.values = (ArrayList) args["values"]; + Name = (string) args["name"]; + Age = (int) args["age"]; + Values = (ArrayList) args["values"]; } } - class CustomClazzConstructor: IObjectConstructor { + + private class CustomClazzConstructor: IObjectConstructor { public object construct(object[] args) { - if(args.Length==0) - { - return new CustomClazz(); // default constructor - } - else if(args.Length==3) + switch (args.Length) { - string name = (string)args[0]; - int age = (int) args[1]; - ArrayList values = (ArrayList) args[2]; - return new CustomClazz(name, age, values); + case 0: + return new CustomClazz(); // default constructor + case 3: + string name = (string)args[0]; + int age = (int) args[1]; + ArrayList values = (ArrayList) args[2]; + return new CustomClazz(name, age, values); + default: + throw new PickleException("expected 0 or 3 constructor arguments"); } - else throw new PickleException("expected 0 or 3 constructor arguments"); } } [Fact] - public void testUnpickleCustomClassAsClassDict() { - byte[] pickled = new byte[] {128, 2, 99, 95, 95, 109, 97, 105, 110, 95, 95, 10, 67, 117, 115, 115, 115, 115, 115, 115, 97, 122, 122, 10, 113, 0, 41, 129, 113, 1, 125, 113, 2, 40, 85, 3, 97, 103, 101, 113, 3, 75, 34, 85, 6, 118, 97, 108, 117, 101, 115, 113, 4, 93, 113, 5, 40, 75, 1, 75, 2, 75, 3, 101, 85, 4, 110, 97, 109, 101, 113, 6, 85, 5, 72, 97, 114, 114, 121, 113, 7, 117, 98, 46}; + public void TestUnpickleCustomClassAsClassDict() { + byte[] pickled = {128, 2, 99, 95, 95, 109, 97, 105, 110, 95, 95, 10, 67, 117, 115, 115, 115, 115, 115, 115, 97, 122, 122, 10, 113, 0, 41, 129, 113, 1, 125, 113, 2, 40, 85, 3, 97, 103, 101, 113, 3, 75, 34, 85, 6, 118, 97, 108, 117, 101, 115, 113, 4, 93, 113, 5, 40, 75, 1, 75, 2, 75, 3, 101, 85, 4, 110, 97, 109, 101, 113, 6, 85, 5, 72, 97, 114, 114, 121, 113, 7, 117, 98, 46}; ClassDict cd = (ClassDict) U(pickled); Assert.Equal("__main__.Cussssssazz", cd["__class__"]); Assert.Equal("Harry" , cd["name"]); Assert.Equal(34 , cd["age"]); - Assert.Equal(new ArrayList() {1,2,3}, cd["values"]); + Assert.Equal(new ArrayList {1,2,3}, cd["values"]); } [Fact] - public void testClassDictConstructorSetsClass() { + public void TestClassDictConstructorSetsClass() { ClassDict cd = new ClassDict("module", "myclass"); Assert.Equal("module.myclass", cd["__class__"]); ClassDictConstructor cdc = new ClassDictConstructor("module", "myclass"); - cd = (ClassDict) cdc.construct(new Object[]{}); + cd = (ClassDict) cdc.construct(new object[]{}); Assert.Equal("module.myclass", cd["__class__"]); Assert.Equal("module.myclass", cd.ClassName); } [Fact] - public void testUnpickleCustomClass() { - byte[] pickled = new byte[] {128, 2, 99, 95, 95, 109, 97, 105, 110, 95, 95, 10, 67, 117, 115, 116, 111, 109, 67, 108, 97, 122, 122, 10, 113, 0, 41, 129, 113, 1, 125, 113, 2, 40, 85, 3, 97, 103, 101, 113, 3, 75, 34, 85, 6, 118, 97, 108, 117, 101, 115, 113, 4, 93, 113, 5, 40, 75, 1, 75, 2, 75, 3, 101, 85, 4, 110, 97, 109, 101, 113, 6, 85, 5, 72, 97, 114, 114, 121, 113, 7, 117, 98, 46}; + public void TestUnpickleCustomClass() { + byte[] pickled = {128, 2, 99, 95, 95, 109, 97, 105, 110, 95, 95, 10, 67, 117, 115, 116, 111, 109, 67, 108, 97, 122, 122, 10, 113, 0, 41, 129, 113, 1, 125, 113, 2, 40, 85, 3, 97, 103, 101, 113, 3, 75, 34, 85, 6, 118, 97, 108, 117, 101, 115, 113, 4, 93, 113, 5, 40, 75, 1, 75, 2, 75, 3, 101, 85, 4, 110, 97, 109, 101, 113, 6, 85, 5, 72, 97, 114, 114, 121, 113, 7, 117, 98, 46}; Unpickler.registerConstructor("__main__","CustomClazz", new CustomClazzConstructor()); CustomClazz o = (CustomClazz) U(pickled); - Assert.Equal("Harry" ,o.name); - Assert.Equal(34 ,o.age); - Assert.Equal(new ArrayList() {1,2,3}, o.values); + Assert.Equal("Harry" ,o.Name); + Assert.Equal(34 ,o.Age); + Assert.Equal(new ArrayList {1,2,3}, o.Values); } [Fact] - public void testUnpickleException() { + public void TestUnpickleException() { // python 2.x PythonException x = (PythonException) U("cexceptions\nZeroDivisionError\np0\n(S'hello'\np1\ntp2\nRp3\n."); Assert.Equal("[exceptions.ZeroDivisionError] hello", x.Message); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleOpcodesTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleOpcodesTests.cs index 6d85764..eb899bd 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleOpcodesTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleOpcodesTests.cs @@ -3,10 +3,12 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Text; using Razorvine.Pickle; using Razorvine.Pickle.Objects; using Xunit; +// ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable UnusedMember.Local @@ -19,9 +21,9 @@ namespace Pyrolite.Tests.Pickle /// public class UnpickleOpcodesTests: IDisposable { - readonly Unpickler u; - static readonly string STRING256; - static readonly string STRING255; + private readonly Unpickler u; + private static readonly string STRING256; + private static readonly string STRING255; static UnpickleOpcodesTests() { StringBuilder sb=new StringBuilder(); @@ -32,7 +34,7 @@ static UnpickleOpcodesTests() { STRING255=STRING256.Substring(1); } - object U(string strdata) { + private object U(string strdata) { return u.loads(PickleUtils.str2bytes(strdata)); } @@ -45,8 +47,8 @@ public void Dispose() { } [Fact] - public void testStr2Bytes() { - byte[] bytes=PickleUtils.str2bytes(STRING256); + public void TestStr2Bytes() { + var bytes=PickleUtils.str2bytes(STRING256); for(int i=0; i<256; ++i) { int b=bytes[i]; if(b<0) b+=256; @@ -55,44 +57,44 @@ public void testStr2Bytes() { } [Fact] - public void testNotExisting() { + public void TestNotExisting() { Assert.Throws(()=>U("%.")); // non existing opcode '%' should crash } [Fact] - public void testMARK() { + public void TestMARK() { // MARK = b'(' # push special markobject on stack Assert.Null(U("(((N.")); } [Fact] - public void testSTOP() { + public void TestSTOP() { //STOP = b'.' # every pickle ends with STOP Assert.Throws(()=>U("..")); // a stop without any data on the stack will throw an array exception } [Fact] - public void testPOP() { + public void TestPOP() { //POP = b'0' # discard topmost stack item Assert.Null(U("}N.")); Assert.Equal(new Hashtable(), U("}N0.")); } [Fact] - public void testPOPMARK() { + public void TestPOPMARK() { //POP_MARK = b'1' # discard stack top through topmost markobject Assert.Equal(2, U("I1\n(I2\n(I3\nI4\n1.")); } [Fact] - public void testDUP() { + public void TestDUP() { //DUP = b'2' # duplicate top stack item object[] tuple={ 42,42}; Assert.Equal(tuple, (object[]) U("(I42\n2t.")); } [Fact] - public void testFLOAT() { + public void TestFLOAT() { //FLOAT = b'F' # push float object; decimal string argument Assert.Equal(0.0d, U("F0\n.")); Assert.Equal(0.0d, U("F0.0\n.")); @@ -110,7 +112,7 @@ public void testFLOAT() { } [Fact] - public void testINT() { + public void TestINT() { //INT = b'I' # push integer or bool; decimal string argument Assert.Equal(0, U("I0\n.")); Assert.Equal(0, U("I-0\n.")); @@ -134,7 +136,7 @@ public void testINT() { } [Fact] - public void testBININT() { + public void TestBININT() { //BININT = b'J' # push four-byte signed int (little endian) Assert.Equal(0, U("J\u0000\u0000\u0000\u0000.")); Assert.Equal(1, U("J\u0001\u0000\u0000\u0000.")); @@ -144,7 +146,7 @@ public void testBININT() { } [Fact] - public void testBININT1() { + public void TestBININT1() { //BININT1 = b'K' # push 1-byte unsigned int Assert.Equal(0, U("K\u0000.")); Assert.Equal(128, U("K\u0080.")); @@ -152,7 +154,7 @@ public void testBININT1() { } [Fact] - public void testLONG() { + public void TestLONG() { //LONG = b'L' # push long; decimal string argument Assert.Equal(0L, U("L0\n.")); Assert.Equal(0L, U("L-0\n.")); @@ -177,7 +179,7 @@ public void testLONG() { } [Fact] - public void testBININT2() { + public void TestBININT2() { //BININT2 = b'M' # push 2-byte unsigned int (little endian) Assert.Equal(0, U("M\u0000\u0000.")); Assert.Equal(255, U("M\u00ff\u0000.")); @@ -186,26 +188,26 @@ public void testBININT2() { } [Fact] - public void testNONE() { + public void TestNONE() { //NONE = b'N' # push None Assert.Null(U("N.")); } [Fact] - public void testPERSIDfail() { + public void TestPERSIDfail() { //PERSID = b'P' # push persistent object; id is taken from string arg Assert.Throws(() => U("Pbla\n.")); } [Fact] - public void testBINPERSIDfail() { + public void TestBINPERSIDfail() { //BINPERSID = b'Q' # push persistent object; id is taken from stack Assert.Throws(() => U("I42\nQ.")); } - class PersistentIdUnpickler : Unpickler + private class PersistentIdUnpickler : Unpickler { - protected override Object persistentLoad(string pid) + protected override object persistentLoad(string pid) { if(pid=="9999") return "PersistentObject"; @@ -214,9 +216,9 @@ protected override Object persistentLoad(string pid) } [Fact] - public void testPERSID() { + public void TestPERSID() { //PERSID = b'P' # push persistent object; id is taken from string arg - byte[] pickle = PickleUtils.str2bytes("(lp0\nI42\naP9999\na."); + var pickle = PickleUtils.str2bytes("(lp0\nI42\naP9999\na."); Unpickler unpickler = new PersistentIdUnpickler(); IList result = (IList)unpickler.loads(pickle); Assert.Equal(2, result.Count); @@ -225,9 +227,9 @@ public void testPERSID() { } [Fact] - public void testBINPERSID() { + public void TestBINPERSID() { //BINPERSID = b'Q' # push persistent object; id is taken from stack - byte[] pickle = PickleUtils.str2bytes("\u0080\u0004\u0095\u000f\u0000\u0000\u0000\u0000\u0000\u0000\u0000]\u0094(K*\u008c\u00049999\u0094Qe."); + var pickle = PickleUtils.str2bytes("\u0080\u0004\u0095\u000f\u0000\u0000\u0000\u0000\u0000\u0000\u0000]\u0094(K*\u008c\u00049999\u0094Qe."); Unpickler unpickler = new PersistentIdUnpickler(); IList result = (IList)unpickler.loads(pickle); Assert.Equal(2, result.Count); @@ -236,16 +238,17 @@ public void testBINPERSID() { } [Fact] - public void testREDUCE_and_GLOBAL() { + public void TestREDUCE_and_GLOBAL() + { //GLOBAL = b'c' # push self.find_class(modname, name); 2 string args //REDUCE = b'R' # apply callable to argtuple, both on stack //"cdecimal\nDecimal\n(V123.456\ntR." - decimal dec=123.456m; + const decimal dec = 123.456m; Assert.Equal(dec, (decimal)U("cdecimal\nDecimal\n(V123.456\ntR.")); } [Fact] - public void testSTRING() { + public void TestSTRING() { //STRING = b'S' # push string; NL-terminated string argument Assert.Equal("", U("S''\n.")); Assert.Equal("", U("S\"\"\n.")); @@ -272,7 +275,7 @@ public void testSTRING() { } [Fact] - public void testBINSTRING() { + public void TestBINSTRING() { //BINSTRING = b'T' # push string; counted binary string argument Assert.Equal("", U("T\u0000\u0000\u0000\u0000.")); Assert.Equal("a", U("T\u0001\u0000\u0000\u0000a.")); @@ -282,7 +285,7 @@ public void testBINSTRING() { } [Fact] - public void testSHORT_BINSTRING() { + public void TestSHORT_BINSTRING() { //SHORT_BINSTRING= b'U' # push string; counted binary string argument < 256 bytes Assert.Equal("", U("U\u0000.")); Assert.Equal("a", U("U\u0001a.")); @@ -291,7 +294,7 @@ public void testSHORT_BINSTRING() { } [Fact] - public void testUNICODE() { + public void TestUNICODE() { //UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument Assert.Equal("", U("V\n.")); Assert.Equal("abc", U("Vabc\n.")); @@ -301,7 +304,7 @@ public void testUNICODE() { } [Fact] - public void testBINUNICODE() { + public void TestBINUNICODE() { //BINUNICODE = b'X' # push Unicode string; counted UTF-8 string argument Assert.Equal("", U("X\u0000\u0000\u0000\u0000.")); Assert.Equal("abc", U("X\u0003\u0000\u0000\u0000abc.")); @@ -309,7 +312,7 @@ public void testBINUNICODE() { } [Fact] - public void testBINUNICODE8() { + public void TestBINUNICODE8() { //BINUNICODE8 = 0x8d; // push very long string Assert.Equal("", U("\u008d\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000.")); Assert.Equal("abc", U("\u008d\u0003\u0000\u0000\u0000\u0000\u0000\u0000\u0000abc.")); @@ -317,7 +320,7 @@ public void testBINUNICODE8() { } [Fact] - public void testSHORTBINUNICODE() { + public void TestSHORTBINUNICODE() { //SHORT_BINUNICODE = 0x8c; // push short string; UTF-8 length < 256 bytes Assert.Equal("", U("\u008c\u0000.")); Assert.Equal("abc", U("\u008c\u0003abc.")); @@ -332,13 +335,14 @@ public void testSHORTBINUNICODE() { } [Fact] - public void testAPPEND() { + public void TestAPPEND() { //APPEND = b'a' # append stack top to list below it ArrayList list = new ArrayList {42, 43}; Assert.Equal(list, U("]I42\naI43\na.")); } + [SuppressMessage("ReSharper", "SuggestBaseTypeForParameter")] private class ThingyWithSetstate { public string a; public ThingyWithSetstate(string param) { @@ -348,7 +352,8 @@ public void __setstate__(Hashtable values) { a=(string)values["a"]; } } - class ThingyConstructor : IObjectConstructor { + + private class ThingyConstructor : IObjectConstructor { public object construct(object[] args) { return new ThingyWithSetstate((string)args[0]); @@ -356,7 +361,7 @@ public object construct(object[] args) { } [Fact] - public void testBUILD() { + public void TestBUILD() { //BUILD = b'b' # call __setstate__ or __dict__.update() Unpickler.registerConstructor("unittest", "Thingy", new ThingyConstructor()); // create a thing with initial value for the field 'a', @@ -366,7 +371,7 @@ public void testBUILD() { } [Fact] - public void testDICT() { + public void TestDICT() { //DICT = b'd' # build a dict from stack items var dict = new Hashtable { @@ -377,27 +382,27 @@ public void testDICT() { } [Fact] - public void testEMPTY_DICT() { + public void TestEMPTY_DICT() { //EMPTY_DICT = b'}' # push empty dict Assert.Equal(new Hashtable(), U("}.")); } [Fact] - public void testAPPENDS() { + public void TestAPPENDS() { //APPENDS = b'e' # extend list on stack by topmost stack slice ArrayList list = new ArrayList {42, 43}; Assert.Equal(list, U("](I42\nI43\ne.")); } [Fact] - public void testGET_and_PUT() { + public void TestGET_and_PUT() { //GET = b'g' # push item from memo on stack; index is string arg //PUT = b'p' # store stack top in memo; index is string arg // a list with three times the same string in it. // the string is stored ('p') and retrieved from the memo ('g'). var list=new List(); - string str="abc"; + const string str = "abc"; list.Add(str); list.Add(str); list.Add(str); @@ -412,13 +417,13 @@ public void testGET_and_PUT() { } [Fact] - public void testBINGET_and_BINPUT() { + public void TestBINGET_and_BINPUT() { //BINGET = b'h' # push item from memo on stack; index is 1-byte arg //BINPUT = b'q' # store stack top in memo; index is 1-byte arg // a list with three times the same string in it. // the string is stored ('p') and retrieved from the memo ('g'). var list=new List(); - string str="abc"; + const string str = "abc"; list.Add(str); list.Add(str); list.Add(str); @@ -433,7 +438,7 @@ public void testBINGET_and_BINPUT() { } [Fact] - public void testINST() { + public void TestINST() { //INST = b'i' # build & push class instance ClassDict result = (ClassDict) U("(i__main__\nThing\n(dS'value'\nI32\nsb."); Assert.Equal("__main__.Thing", result.ClassName); @@ -441,13 +446,13 @@ public void testINST() { } [Fact] - public void testLONG_BINGET_and_LONG_BINPUT() { + public void TestLONG_BINGET_and_LONG_BINPUT() { //LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg //LONG_BINPUT = b'r' # store stack top in memo; index is 4-byte arg // a list with three times the same string in it. // the string is stored ('p') and retrieved from the memo ('g'). var list=new List(); - string str="abc"; + const string str = "abc"; list.Add(str); list.Add(str); list.Add(str); @@ -463,20 +468,20 @@ public void testLONG_BINGET_and_LONG_BINPUT() { } [Fact] - public void testLIST() { + public void TestLIST() { //LIST = b'l' # build list from topmost stack items var list = new List {1, 2}; Assert.Equal(list, U("(I1\nI2\nl.")); } [Fact] - public void testEMPTY_LIST() { + public void TestEMPTY_LIST() { //EMPTY_LIST = b']' # push empty list Assert.Equal(new ArrayList(), U("].")); } [Fact] - public void testOBJ() { + public void TestOBJ() { //OBJ = b'o' # build & push class instance ClassDict result = (ClassDict) U("\u0080\u0002(c__main__\nThing\no}U\u0005valueK sb."); Assert.Equal("__main__.Thing", result.ClassName); @@ -484,7 +489,7 @@ public void testOBJ() { } [Fact] - public void testSETITEM() { + public void TestSETITEM() { //SETITEM = b's' # add key+value pair to dict var dict = new Hashtable { @@ -495,27 +500,27 @@ public void testSETITEM() { } [Fact] - public void testTUPLE() { + public void TestTUPLE() { //TUPLE = b't' # build tuple from topmost stack items object[] tuple={1,2}; Assert.Equal(tuple, (object[]) U("(I1\nI2\nt.")); } [Fact] - public void testEMPTY_TUPLE() { + public void TestEMPTY_TUPLE() { //EMPTY_TUPLE = b')' # push empty tuple Assert.Equal(new object[0], (object[]) U(").")); } [Fact] - public void testEMPTY_SET() { + public void TestEMPTY_SET() { //EMPTY_SET = 0x8f; // push empty set on the stack var value = new HashSet(); Assert.Equal(value, u.loads(new byte[]{ 0x8f, Opcodes.STOP})); } [Fact] - public void testFROZENSET() { + public void TestFROZENSET() { //FROZENSET = 0x91; // build frozenset from topmost stack items var value = new HashSet(); Assert.Equal(value, u.loads(new[]{ Opcodes.MARK, Opcodes.FROZENSET, Opcodes.STOP})); @@ -525,7 +530,7 @@ public void testFROZENSET() { } [Fact] - public void testADDITEMS() { + public void TestADDITEMS() { //ADDITEMS = 0x90; // modify set by adding topmost stack items var value = new HashSet(); Assert.Equal(value, u.loads(new []{ Opcodes.EMPTY_SET, Opcodes.MARK, Opcodes.ADDITEMS, Opcodes.STOP})); @@ -535,7 +540,7 @@ public void testADDITEMS() { } [Fact] - public void testSETITEMS() { + public void TestSETITEMS() { //SETITEMS = b'u' # modify dict by adding topmost key+value pairs var dict = new Hashtable { @@ -552,30 +557,30 @@ public void testSETITEMS() { } [Fact] - public void testBINFLOAT() { + public void TestBINFLOAT() { //BINFLOAT = b'G' # push float; arg is 8-byte float encoding Assert.Equal(2.345e123, u.loads(new byte[]{Opcodes.BINFLOAT, 0x59,0x8c,0x60,0xfb,0x80,0xae,0x2f,0xbb, Opcodes.STOP})); Assert.Equal(1.172419264827552e+123, u.loads(new byte[]{Opcodes.BINFLOAT, 0x59,0x7c,0x60,0x7b,0x70,0x7e,0x2f,0x7b, Opcodes.STOP})); - Assert.Equal(Double.PositiveInfinity, u.loads(new byte[]{Opcodes.BINFLOAT, 0x7f,0xf0,0,0,0,0,0,0, Opcodes.STOP})); - Assert.Equal(Double.NegativeInfinity, u.loads(new byte[]{Opcodes.BINFLOAT, 0xff,0xf0,0,0,0,0,0,0, Opcodes.STOP})); - Assert.Equal(Double.NaN, u.loads(new byte[]{Opcodes.BINFLOAT, 0xff,0xf8,0,0,0,0,0,0, Opcodes.STOP})); + Assert.Equal(double.PositiveInfinity, u.loads(new byte[]{Opcodes.BINFLOAT, 0x7f,0xf0,0,0,0,0,0,0, Opcodes.STOP})); + Assert.Equal(double.NegativeInfinity, u.loads(new byte[]{Opcodes.BINFLOAT, 0xff,0xf0,0,0,0,0,0,0, Opcodes.STOP})); + Assert.Equal(double.NaN, u.loads(new byte[]{Opcodes.BINFLOAT, 0xff,0xf8,0,0,0,0,0,0, Opcodes.STOP})); } [Fact] - public void testTRUE() { + public void TestTRUE() { //TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py Assert.True((bool) U("I01\n.")); } [Fact] - public void testFALSE() { + public void TestFALSE() { //FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py Assert.False((bool) U("I00\n.")); } [Fact] - public void testPROTO() { + public void TestPROTO() { //PROTO = b'\x80' # identify pickle protocol U("\u0080\u0000N."); U("\u0080\u0001N."); @@ -591,18 +596,19 @@ public void testPROTO() { } [Fact] - public void testNEWOBJ() { + public void TestNEWOBJ() + { //NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple //GLOBAL = b'c' # push self.find_class(modname, name); 2 string args //"cdecimal\nDecimal\n(V123.456\nt\x81." - decimal dec=123.456m; + const decimal dec = 123.456m; Assert.Equal(dec, (decimal)U("cdecimal\nDecimal\n(V123.456\nt\u0081.")); } [Fact] - public void testNEWOBJ_EX() { + public void TestNEWOBJ_EX() { //NEWOBJ_EX = 0x92; // like NEWOBJ but work with keyword only arguments - decimal dec=123.456m; + const decimal dec = 123.456m; Assert.Equal(dec, (decimal)U("cdecimal\nDecimal\n(V123.456\nt}\u0092.")); try { @@ -615,58 +621,58 @@ public void testNEWOBJ_EX() { [Fact] - public void testEXT1() { + public void TestEXT1() { //EXT1 = b'\x82' # push object from extension registry; 1-byte index Assert.Throws(()=>U("\u0082\u0001.")); // not implemented } [Fact] - public void testEXT2() { + public void TestEXT2() { //EXT2 = b'\x83' # ditto, but 2-byte index Assert.Throws(()=>U("\u0083\u0001\u0002.")); // not implemented } [Fact] - public void testEXT4() { + public void TestEXT4() { //EXT4 = b'\x84' # ditto, but 4-byte index Assert.Throws(()=>U("\u0084\u0001\u0002\u0003\u0004.")); // not implemented } [Fact] - public void testTUPLE1() { + public void TestTUPLE1() { //TUPLE1 = b'\x85' # build 1-tuple from stack top object[] tuple={ 42 }; Assert.Equal(tuple, (object[]) U("I41\nI42\n\u0085.")); } [Fact] - public void testTUPLE2() { + public void TestTUPLE2() { //TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items object[] tuple={ 42, 43 }; Assert.Equal(tuple, (object[]) U("I41\nI42\nI43\n\u0086.")); } [Fact] - public void testTUPLE3() { + public void TestTUPLE3() { //TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items object[] tuple={ 42, 43, 44 }; Assert.Equal(tuple, (object[]) U("I41\nI42\nI43\nI44\n\u0087.")); } [Fact] - public void testNEWTRUE() { + public void TestNEWTRUE() { //NEWTRUE = b'\x88' # push True Assert.True((bool) U("\u0088.")); } [Fact] - public void testNEWFALSE() { + public void TestNEWFALSE() { //NEWFALSE = b'\x89' # push False Assert.False((bool) U("\u0089.")); } [Fact] - public void testLONG1() { + public void TestLONG1() { //LONG1 = b'\x8a' # push long from < 256 bytes Assert.Equal(0L, U("\u008a\u0000.")); Assert.Equal(0L, U("\u008a\u0001\u0000.")); @@ -693,7 +699,7 @@ public void testLONG1() { } [Fact] - public void testLONG4() { + public void TestLONG4() { //LONG4 = b'\x8b' # push really big long Assert.Equal(0L, u.loads(new byte[] {Opcodes.LONG4, 0x00, 0x00, 0x00, 0x00, Opcodes.STOP})); Assert.Equal(0L, u.loads(new byte[] {Opcodes.LONG4, 0x01, 0x00, 0x00, 0x00, 0x00, Opcodes.STOP})); @@ -720,7 +726,7 @@ public void testLONG4() { } [Fact] - public void testBINBYTES() { + public void TestBINBYTES() { //BINBYTES = b'B' # push bytes; counted binary string argument var bytes = new byte[]{}; Assert.Equal(bytes, (byte[]) U("B\u0000\u0000\u0000\u0000.")); @@ -737,7 +743,7 @@ public void testBINBYTES() { [Fact] - public void testBINBYTES8() { + public void TestBINBYTES8() { //BINBYTES8 = 0x8e; // push very long bytes string var bytes = new byte[]{}; Assert.Equal(bytes, (byte[]) U("\u008e\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000.")); @@ -753,7 +759,7 @@ public void testBINBYTES8() { } [Fact] - public void testSHORT_BINBYTES() { + public void TestSHORT_BINBYTES() { //SHORT_BINBYTES = b'C' # push bytes; counted binary string argument < 256 bytes var bytes = new byte[]{}; Assert.Equal(bytes, (byte[]) U("C\u0000.")); @@ -769,7 +775,7 @@ public void testSHORT_BINBYTES() { } [Fact] - public void testMEMOIZE() { + public void TestMEMOIZE() { // MEMOIZE = 0x94; // store top of the stack in memo var value = new object[] {1,2,2}; var result = (object[]) U("K\u0001\u0094K\u0002\u0094h\u0000h\u0001h\u0001\u0087."); @@ -777,7 +783,7 @@ public void testMEMOIZE() { } [Fact] - public void testFRAME() { + public void TestFRAME() { // FRAME = 0x95; // indicate the beginning of a new frame var result = u.loads(new byte[] { Opcodes.FRAME, 6,0,0,0,0,0,0,0, Opcodes.BININT1, 42, Opcodes.BININT1, 43, Opcodes.BININT1, 44, @@ -787,7 +793,7 @@ public void testFRAME() { } [Fact] - public void testGLOBAL() { + public void TestGLOBAL() { //GLOBAL = (byte)'c'; // push self.find_class(modname, name); 2 string args var result = U("cdatetime\ntime\n."); Assert.IsType(result); @@ -796,7 +802,7 @@ public void testGLOBAL() { } [Fact] - public void testSTACK_GLOBAL() { + public void TestSTACK_GLOBAL() { //STACK_GLOBAL = 0x93; // same as GLOBAL but using names on the stacks var result = U("\u008c\u0008datetime\u008c\u0004time\u0093."); Assert.IsType(result); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleStackTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleStackTests.cs index e9161b7..1ead3e3 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleStackTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpickleStackTests.cs @@ -14,7 +14,7 @@ namespace Pyrolite.Tests.Pickle public class UnpickleStackTest { [Fact] - public void testPopSinceMarker() { + public void TestPopSinceMarker() { UnpickleStack s=new UnpickleStack(); s.add("a"); s.add("b"); @@ -32,7 +32,7 @@ public void testPopSinceMarker() { } [Fact] - public void testAddPop() { + public void TestAddPop() { UnpickleStack s=new UnpickleStack(); Assert.Equal(0, s.size()); s.add("x"); @@ -47,7 +47,7 @@ public void testAddPop() { } [Fact] - public void testClear() { + public void TestClear() { UnpickleStack s=new UnpickleStack(); s.add("x"); s.add("y"); @@ -57,7 +57,7 @@ public void testClear() { } [Fact] - public void testTrim() { + public void TestTrim() { UnpickleStack s=new UnpickleStack(); s.add("a"); s.add("b"); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpicklerTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpicklerTests.cs index a261ec3..0e4c3c3 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpicklerTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pickle/UnpicklerTests.cs @@ -18,11 +18,12 @@ namespace Pyrolite.Tests.Pickle /// public class UnpicklerTests { - object U(string strdata) + private static object U(string strdata) { return U(PickleUtils.str2bytes(strdata)); } - object U(byte[] data) + + private static object U(byte[] data) { Unpickler u=new Unpickler(); object o=u.loads(data); @@ -32,12 +33,12 @@ object U(byte[] data) [Fact] - public void testSinglePrimitives() { + public void TestSinglePrimitives() { // protocol level 1 Assert.Null(U("N.")); // none Assert.Equal(123.456d, U("F123.456\n.")); // float - Assert.True((Boolean)U("I01\n.")); // true boolean - Assert.False((Boolean)U("I00\n.")); // false boolean + Assert.True((bool)U("I01\n.")); // true boolean + Assert.False((bool)U("I00\n.")); // false boolean Assert.Equal(new byte[]{97,98,99},(byte[]) U("c__builtin__\nbytes\np0\n((lp1\nL97L\naL98L\naL99L\natp2\nRp3\n.")); // python3 bytes Assert.Equal(new byte[]{97,98,99},(byte[]) U("c__builtin__\nbytes\n(](KaKbKcetR.")); // python3 bytes Assert.Equal(new byte[]{97,98,99,100,101,102}, (byte[]) U("C\u0006abcdef.")); // python3 bytes @@ -66,8 +67,8 @@ public void testSinglePrimitives() { Assert.Equal(new object[0], (object[]) U(").")); Assert.Equal(1234.5678d, U("G@\u0093JEm\\\u00fa\u00ad.")); // 8-byte binary coded float // protocol level2 - Assert.True((Boolean)U("\u0088.")); // True - Assert.False((Boolean)U("\u0089.")); // False + Assert.True((bool)U("\u0088.")); // True + Assert.False((bool)U("\u0089.")); // False //Assert.Equal(12345678987654321L, U("\u008a\u0007\u00b1\u00f4\u0091\u0062\u0054\u00dc\u002b.")); //Assert.Equal(12345678987654321L, U("\u008b\u0007\u0000\u0000\u0000\u00b1\u00f4\u0091\u0062\u0054\u00dc\u002b.")); // Protocol 3 (Python 3.x) @@ -76,8 +77,8 @@ public void testSinglePrimitives() { } [Fact] - public void testZeroToTwoFiveSix() { - byte[] bytes=new byte[256]; + public void TestZeroToTwoFiveSix() { + var bytes=new byte[256]; for(int b=0; b<256; ++b) { bytes[b]=(byte)b; } @@ -92,11 +93,11 @@ public void testZeroToTwoFiveSix() { MemoryStream bos=new MemoryStream(434); bos.WriteByte(Opcodes.PROTO); bos.WriteByte(2); - byte[] data=Encoding.Default.GetBytes("c__builtin__\nbytearray\n"); + var data=Encoding.Default.GetBytes("c__builtin__\nbytearray\n"); bos.Write(data,0,data.Length); bos.WriteByte(Opcodes.BINUNICODE); bos.Write(new byte[] {0x80,0x01,0x00,0x00},0,4); - byte[] utf8=Encoding.UTF8.GetBytes(str); + var utf8=Encoding.UTF8.GetBytes(str); bos.Write(utf8,0,utf8.Length); bos.WriteByte(Opcodes.BINUNICODE); bos.Write(new byte[] {7,0,0,0},0,4); @@ -106,8 +107,8 @@ public void testZeroToTwoFiveSix() { bos.WriteByte(Opcodes.REDUCE); bos.WriteByte(Opcodes.STOP); - byte[] bytesresult=bos.ToArray(); - byte[] output=p.dumps(bytes); + var bytesresult=bos.ToArray(); + var output=p.dumps(bytes); Assert.Equal(bytesresult, output); Assert.Equal(bytes, (byte[])u.loads(output)); @@ -126,7 +127,7 @@ public void testZeroToTwoFiveSix() { } [Fact] - public void testUnicodeStrings() + public void TestUnicodeStrings() { Assert.Equal("\u00ff", U("S'\\xff'\n.")); Assert.Equal("\u20ac", U("V\\u20ac\n.")); @@ -139,7 +140,7 @@ public void testUnicodeStrings() } [Fact] - public void testTuples() + public void TestTuples() { Assert.Equal(new object[0], (object[])U(").")); // () Assert.Equal(new object[]{97}, (object[])U("Ka\u0085.")); // (97,) @@ -149,7 +150,7 @@ public void testTuples() } [Fact] - public void testLists() + public void TestLists() { IList list=new List(0); @@ -163,7 +164,7 @@ public void testLists() } [Fact] - public void testDicts() + public void TestDicts() { Hashtable map=new Hashtable(); Hashtable map2=new Hashtable(); @@ -224,7 +225,7 @@ public void testDicts() } [Fact] - public void testComplex() + public void TestComplex() { ComplexNumber c=new ComplexNumber(2.0, 4.0); Assert.Equal(c, U("c__builtin__\ncomplex\np0\n(F2.0\nF4.0\ntp1\nRp2\n.")); @@ -232,14 +233,14 @@ public void testComplex() } [Fact] - public void testDecimal() + public void TestDecimal() { Assert.Equal(12345.6789m, U("cdecimal\nDecimal\np0\n(S'12345.6789'\np1\ntp2\nRp3\n.")); Assert.Equal(12345.6789m, U("\u0080\u0002cdecimal\nDecimal\nU\n12345.6789\u0085R.")); } [Fact] - public void testDateTime() + public void TestDateTime() { DateTime dt; TimeSpan ts; @@ -275,7 +276,7 @@ public void testDateTime() } [Fact] - public void testDateTimePython3() + public void TestDateTimePython3() { DateTime dt; TimeSpan ts; @@ -294,11 +295,11 @@ public void testDateTimePython3() } [Fact] - public void testDateTimeStringEscaping() + public void TestDateTimeStringEscaping() { DateTime dt=new DateTime(2011, 10, 10, 9, 13, 10, 10); Pickler p = new Pickler(); - byte[] pickle = p.dumps(dt); + var pickle = p.dumps(dt); Unpickler u = new Unpickler(); DateTime dt2 = (DateTime) u.loads(pickle); Assert.Equal(dt, dt2); @@ -313,15 +314,15 @@ public void testDateTimeStringEscaping() } [Fact] - public void testCodecBytes() + public void TestCodecBytes() { // this is a protocol 2 pickle that contains the way python3 encodes bytes - byte[] data = (byte[]) U("\u0080\u0002c_codecs\nencode\nX\u0004\u0000\u0000\u0000testX\u0006\u0000\u0000\u0000latin1\u0086R."); + var data = (byte[]) U("\u0080\u0002c_codecs\nencode\nX\u0004\u0000\u0000\u0000testX\u0006\u0000\u0000\u0000latin1\u0086R."); Assert.Equal(Encoding.ASCII.GetBytes("test"), data); } [Fact] - public void testBytesAndByteArray() + public void TestBytesAndByteArray() { byte[] bytes={1,2,127,128,255}; Assert.Equal(bytes, (byte[])U("\u0080\u0003C\u0005\u0001\u0002\u007f\u0080\u00ffq\u0000.")); @@ -378,7 +379,7 @@ public void testBytesAndByteArray() Assert.Equal(bytes, (byte[])U(p2)); // the following is a python3 pickle of a small bytearray. It constructs a bytearray using [SHORT_]BINBYTES instead of a list. - byte[] p3 = new byte[] { + byte[] p3 = { 0x80, 0x04, 0x95, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x08, 0x62, 0x75, 0x69, 0x6c, 0x74, 0x69, 0x6e, 0x73, 0x8c, 0x09, 0x62, 0x79, 0x74, 0x65, 0x61, 0x72, 0x72, 0x61, 0x79, 0x93, 0x43, 0x08, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x85, 0x52, 0x2e @@ -387,11 +388,11 @@ public void testBytesAndByteArray() } [Fact] - public void testArray() + public void TestArray() { // c=char -->char char[] testc={'a','b','c'}; - char[] arrayc=(char[]) U("carray\narray\np0\n(S'c'\np1\n(lp2\nS'a'\np3\naS'b'\np4\nag1\natp5\nRp6\n."); + var arrayc=(char[]) U("carray\narray\np0\n(S'c'\np1\n(lp2\nS'a'\np3\naS'b'\np4\nag1\natp5\nRp6\n."); Assert.Equal(testc,arrayc); testc=new []{'x','y','z'}; arrayc=(char[])U("carray\narray\nU\u0001c](U\u0001xU\u0001yU\u0001ze\u0086R."); @@ -404,72 +405,72 @@ public void testArray() // b=signed char -->sbyte sbyte[] testsb={1,2,-1,-2}; - sbyte[] arraysb=(sbyte[]) U("carray\narray\np0\n(S'b'\np1\n(lp2\nI1\naI2\naI-1\naI-2\natp3\nRp4\n."); + var arraysb=(sbyte[]) U("carray\narray\np0\n(S'b'\np1\n(lp2\nI1\naI2\naI-1\naI-2\natp3\nRp4\n."); Assert.Equal(testsb,arraysb); // B=unsigned char -->byte byte[] testb={1,2,128,255}; - byte[] arrayb=(byte[]) U("carray\narray\np0\n(S'B'\np1\n(lp2\nI1\naI2\naI128\naI255\natp3\nRp4\n."); + var arrayb=(byte[]) U("carray\narray\np0\n(S'B'\np1\n(lp2\nI1\naI2\naI128\naI255\natp3\nRp4\n."); Assert.Equal(testb,arrayb); // h=signed short -->short short[] tests={1,2,128,255,32700,-32700}; - short[] arrays=(short[]) U("carray\narray\np0\n(S'h'\np1\n(lp2\nI1\naI2\naI128\naI255\naI32700\naI-32700\natp3\nRp4\n."); + var arrays=(short[]) U("carray\narray\np0\n(S'h'\np1\n(lp2\nI1\naI2\naI128\naI255\naI32700\naI-32700\natp3\nRp4\n."); Assert.Equal(tests,arrays); // H=unsigned short -->ushort ushort[] testus={1,2,40000,65535}; - ushort[] arrayus=(ushort[]) U("carray\narray\np0\n(S'H'\np1\n(lp2\nI1\naI2\naI40000\naI65535\natp3\nRp4\n."); + var arrayus=(ushort[]) U("carray\narray\np0\n(S'H'\np1\n(lp2\nI1\naI2\naI40000\naI65535\natp3\nRp4\n."); Assert.Equal(testus,arrayus); // i=signed integer -->int int[] testi={1,2,999999999,-999999999}; - int[] arrayi=(int[]) U("carray\narray\np0\n(S'i'\np1\n(lp2\nI1\naI2\naI999999999\naI-999999999\natp3\nRp4\n."); + var arrayi=(int[]) U("carray\narray\np0\n(S'i'\np1\n(lp2\nI1\naI2\naI999999999\naI-999999999\natp3\nRp4\n."); Assert.Equal(testi,arrayi); // I=unsigned integer -->uint - uint[] testui=new uint[]{1,2,999999999}; - uint[] arrayui=(uint[]) U("carray\narray\np0\n(S'I'\np1\n(lp2\nL1L\naL2L\naL999999999L\natp3\nRp4\n."); + uint[] testui={1,2,999999999}; + var arrayui=(uint[]) U("carray\narray\np0\n(S'I'\np1\n(lp2\nL1L\naL2L\naL999999999L\natp3\nRp4\n."); Assert.Equal(testui,arrayui); // l=signed long -->long - long[] testl=new long[]{1,2,999999999999,-999999999999}; - long[] arrayl=(long[]) U("carray\narray\np0\n(S'l'\np1\n(lp2\nI1\naI2\naI999999999999\naI-999999999999\natp3\nRp4\n."); + long[] testl={1,2,999999999999,-999999999999}; + var arrayl=(long[]) U("carray\narray\np0\n(S'l'\np1\n(lp2\nI1\naI2\naI999999999999\naI-999999999999\natp3\nRp4\n."); Assert.Equal(testl,arrayl); // L=unsigned long -->ulong - ulong[] testul=new ulong[]{1,2,999999999999}; - ulong[] arrayul=(ulong[]) U("carray\narray\np0\n(S'L'\np1\n(lp2\nL1L\naL2L\naL999999999999L\natp3\nRp4\n."); + ulong[] testul={1,2,999999999999}; + var arrayul=(ulong[]) U("carray\narray\np0\n(S'L'\np1\n(lp2\nL1L\naL2L\naL999999999999L\natp3\nRp4\n."); Assert.Equal(testul,arrayul); // f=float 4 - float[] testf=new float[]{-4.4f, 4.4f}; - float[] arrayf=(float[]) U("carray\narray\np0\n(S'f'\np1\n(lp2\nF-4.400000095367432\naF4.400000095367432\natp3\nRp4\n."); + float[] testf={-4.4f, 4.4f}; + var arrayf=(float[]) U("carray\narray\np0\n(S'f'\np1\n(lp2\nF-4.400000095367432\naF4.400000095367432\natp3\nRp4\n."); Assert.Equal(testf,arrayf); // d=float 8 - double[] testd=new double[]{-4.4d, 4.4d}; - double[] arrayd=(double[]) U("carray\narray\np0\n(S'd'\np1\n(lp2\nF-4.4\naF4.4\natp3\nRp4\n."); + double[] testd={-4.4d, 4.4d}; + var arrayd=(double[]) U("carray\narray\np0\n(S'd'\np1\n(lp2\nF-4.4\naF4.4\natp3\nRp4\n."); Assert.Equal(testd,arrayd); } [Fact] - public void testArrayPython3() { + public void TestArrayPython3() { // python 3 array reconstructor - short[] testi=new short[]{1,2,3}; - short[] arrayi=(short[])U("\u0080\u0003carray\n_array_reconstructor\nq\u0000(carray\narray\nq\u0001X\u0001\u0000\u0000\u0000hq\u0002K\u0004C\u0006\u0001\u0000\u0002\u0000\u0003\u0000q\u0003tq\u0004Rq\u0005."); + short[] testi={1,2,3}; + var arrayi=(short[])U("\u0080\u0003carray\n_array_reconstructor\nq\u0000(carray\narray\nq\u0001X\u0001\u0000\u0000\u0000hq\u0002K\u0004C\u0006\u0001\u0000\u0002\u0000\u0003\u0000q\u0003tq\u0004Rq\u0005."); Assert.Equal(testi, arrayi); } [Fact] - public void testArrayPython26NotSupported() { + public void TestArrayPython26NotSupported() { // python 2.6 array reconstructor not yet supported Assert.Throws(() => U("carray\narray\n(S'h'\nS'\\x01\\x00\\x02\\x00\\x03\\x00'\ntR.")); } [Fact] - public void testSet() + public void TestSet() { var set = new HashSet {1, 2, "abc"}; @@ -477,7 +478,7 @@ public void testSet() } [Fact] - public void testMemoing() + public void TestMemoing() { ArrayList list = new ArrayList {"irmen", "irmen", "irmen"}; @@ -487,7 +488,7 @@ public void testMemoing() ArrayList b = new ArrayList {222}; ArrayList c = new ArrayList {333}; - object[] array=new object[] {a,b,c,a,b,c}; + object[] array={a,b,c,a,b,c}; Assert.Equal(array, (object[]) U("((lp0\nI111\na(lp1\nI222\na(lp2\nI333\nag0\ng1\ng2\ntp3\n.")); list.Clear(); @@ -503,16 +504,16 @@ public void testMemoing() } [Fact] - public void testBinint2WithObject() + public void TestBinint2WithObject() { Unpickler u=new Unpickler(); - byte[] data=PickleUtils.str2bytes("\u0080\u0002cIgnore.Ignore\nIgnore\n)\u0081M\u0082#."); + var data=PickleUtils.str2bytes("\u0080\u0002cIgnore.Ignore\nIgnore\n)\u0081M\u0082#."); int result=(int) u.loads(data); Assert.Equal(9090,result); } [Fact(Skip = "performancetest")] - public void testUnpicklingPerformance() + public void TestUnpicklingPerformance() { Pickler pickler = new Pickler(); @@ -521,7 +522,7 @@ public void testUnpicklingPerformance() myList.Add(i.ToString()); } - byte[] bytes = pickler.dumps(myList); + var bytes = pickler.dumps(myList); Unpickler unpickler = new Unpickler(); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pyro/MessageTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pyro/MessageTests.cs index a6dc4e9..029aef7 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pyro/MessageTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pyro/MessageTests.cs @@ -5,6 +5,7 @@ using System.Text; using System.Linq; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Xunit; using Razorvine.Pyro; // ReSharper disable CheckNamespace @@ -13,31 +14,31 @@ namespace Pyrolite.Tests.Pyro { public class MessageTestsHmac { - readonly ushort serializer_id = new PickleSerializer().serializer_id; + private readonly ushort _serializerId = new PickleSerializer().serializer_id; [Fact] - public void testMessage() + public void TestMessage() { - byte[] hmac = Encoding.UTF8.GetBytes("secret"); + var hmac = Encoding.UTF8.GetBytes("secret"); - var unused = new Message(99, new byte[0], this.serializer_id, 0, 0, null, hmac); // doesn't check msg type here + var unused = new Message(99, new byte[0], _serializerId, 0, 0, null, hmac); // doesn't check msg type here Assert.Throws(()=>Message.from_header(Encoding.ASCII.GetBytes("FOOBAR"))); - var msg = new Message(Message.MSG_CONNECT, Encoding.ASCII.GetBytes("hello"), this.serializer_id, 0, 0, null, hmac); + var msg = new Message(Message.MSG_CONNECT, Encoding.ASCII.GetBytes("hello"), _serializerId, 0, 0, null, hmac); Assert.Equal(Message.MSG_CONNECT, msg.type); Assert.Equal(5, msg.data_size); Assert.Equal(new []{(byte)'h',(byte)'e',(byte)'l',(byte)'l',(byte)'o'}, msg.data); Assert.Equal(4+2+20, msg.annotations_size); - byte[] mac = msg.hmac(hmac); + var mac = msg.hmac(hmac); var expected = new Dictionary {["HMAC"] = mac}; Assert.Equal(expected, msg.annotations); - byte[] hdr = msg.to_bytes().Take(Message.HEADER_SIZE).ToArray(); + var hdr = msg.to_bytes().Take(Message.HEADER_SIZE).ToArray(); msg = Message.from_header(hdr); Assert.Equal(Message.MSG_CONNECT, msg.type); Assert.Equal(4+2+20, msg.annotations_size); Assert.Equal(5, msg.data_size); - hdr = new Message(Message.MSG_RESULT, new byte[0], this.serializer_id, 0, 0, null, hmac).to_bytes().Take(Message.HEADER_SIZE).ToArray(); + hdr = new Message(Message.MSG_RESULT, new byte[0], _serializerId, 0, 0, null, hmac).to_bytes().Take(Message.HEADER_SIZE).ToArray(); msg = Message.from_header(hdr); Assert.Equal(Message.MSG_RESULT, msg.type); Assert.Equal(4+2+20, msg.annotations_size); @@ -51,22 +52,22 @@ public void testMessage() Assert.Equal(12345, msg.serializer_id); Assert.Equal(30003, msg.seq); - byte[] data = new Message(255, new byte[0], this.serializer_id, 0, 255, null, hmac).to_bytes(); + var data = new Message(255, new byte[0], _serializerId, 0, 255, null, hmac).to_bytes(); Assert.Equal(50, data.Length); - data = new Message(1, new byte[0], this.serializer_id, 0, 255, null, hmac).to_bytes(); + data = new Message(1, new byte[0], _serializerId, 0, 255, null, hmac).to_bytes(); Assert.Equal(50, data.Length); - data = new Message(1, new byte[0], this.serializer_id, 253, 254, null, hmac).to_bytes(); + data = new Message(1, new byte[0], _serializerId, 253, 254, null, hmac).to_bytes(); Assert.Equal(50, data.Length); // compression is a job of the code supplying the data, so the messagefactory should leave it untouched data = new byte[1000]; - byte[] msg_bytes1 = new Message(Message.MSG_INVOKE, data, this.serializer_id, 0, 0, null, hmac).to_bytes(); - byte[] msg_bytes2 = new Message(Message.MSG_INVOKE, data, this.serializer_id, Message.FLAGS_COMPRESSED, 0, null, hmac).to_bytes(); - Assert.Equal(msg_bytes1.Length, msg_bytes2.Length); + var msgBytes1 = new Message(Message.MSG_INVOKE, data, _serializerId, 0, 0, null, hmac).to_bytes(); + var msgBytes2 = new Message(Message.MSG_INVOKE, data, _serializerId, Message.FLAGS_COMPRESSED, 0, null, hmac).to_bytes(); + Assert.Equal(msgBytes1.Length, msgBytes2.Length); } [Fact] - public void testMessageHeaderDatasize() + public void TestMessageHeaderDatasize() { var msg = new Message(Message.MSG_RESULT, Encoding.ASCII.GetBytes("hello"), 12345, 60006, 30003, null, null) @@ -74,7 +75,7 @@ public void testMessageHeaderDatasize() data_size = 0x12345678 }; // hack it to a large value to see if it comes back ok - byte[] hdr = msg.to_bytes().Take(Message.HEADER_SIZE).ToArray(); + var hdr = msg.to_bytes().Take(Message.HEADER_SIZE).ToArray(); msg = Message.from_header(hdr); Assert.Equal(Message.MSG_RESULT, msg.type); Assert.Equal(60006, msg.flags); @@ -84,9 +85,9 @@ public void testMessageHeaderDatasize() } [Fact] - public void testAnnotations() + public void TestAnnotations() { - byte[] hmac=Encoding.UTF8.GetBytes("secret"); + var hmac=Encoding.UTF8.GetBytes("secret"); var annotations = new Dictionary { @@ -96,17 +97,17 @@ public void testAnnotations() ["TES4"] = new byte[] {40, 50, 60, 70, 80} }; - var msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, this.serializer_id, 0, 0, annotations, hmac); - byte[] data = msg.to_bytes(); - int annotations_size = 4+2+20 + (4+2+5)*4; - Assert.Equal(Message.HEADER_SIZE + 5 + annotations_size, data.Length); - Assert.Equal(annotations_size, msg.annotations_size); + var msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, _serializerId, 0, 0, annotations, hmac); + var data = msg.to_bytes(); + const int annotationsSize = 4+2+20 + (4+2+5)*4; + Assert.Equal(Message.HEADER_SIZE + 5 + annotationsSize, data.Length); + Assert.Equal(annotationsSize, msg.annotations_size); Assert.Equal(5, msg.annotations.Count); Assert.Equal(new byte[]{10,20,30,40,50}, msg.annotations["TES1"]); Assert.Equal(new byte[]{20,30,40,50,60}, msg.annotations["TES2"]); Assert.Equal(new byte[]{30,40,50,60,70}, msg.annotations["TES3"]); Assert.Equal(new byte[]{40,50,60,70,80}, msg.annotations["TES4"]); - byte[] mac = msg.hmac(hmac); + var mac = msg.hmac(hmac); Assert.Equal(mac, msg.annotations["HMAC"]); annotations = new Dictionary @@ -116,20 +117,20 @@ public void testAnnotations() ["TES2"] = new byte[] {20, 30, 40, 50, 60}, ["TES1"] = new byte[] {10, 20, 30, 40, 50} }; - var msg2 = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, this.serializer_id, 0, 0, annotations, hmac); + var msg2 = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, _serializerId, 0, 0, annotations, hmac); Assert.Equal(msg.hmac(hmac), msg2.hmac(hmac)); annotations = new Dictionary {["TES4"] = new byte[] {40, 50, 60, 70, 80}}; - var msg3 = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, this.serializer_id, 0, 0, annotations, hmac); + var msg3 = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, _serializerId, 0, 0, annotations, hmac); Assert.NotEqual(msg.hmac(hmac), msg3.hmac(hmac)); } [Fact] - public void testAnnotationsIdLength4() + public void TestAnnotationsIdLength4() { try { var anno = new Dictionary {["TOOLONG"] = new byte[] {10, 20, 30}}; - var msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, this.serializer_id, 0, 0, anno, null); + var msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, _serializerId, 0, 0, anno, null); msg.to_bytes(); Assert.True(false, "should fail, too long"); } catch(ArgumentException) { @@ -137,7 +138,7 @@ public void testAnnotationsIdLength4() } try { var anno = new Dictionary {["QQ"] = new byte[] {10, 20, 30}}; - var msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, this.serializer_id, 0, 0, anno, null); + var msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, _serializerId, 0, 0, anno, null); msg.to_bytes(); Assert.True(false, "should fail, too short"); } catch (ArgumentException) { @@ -146,10 +147,10 @@ public void testAnnotationsIdLength4() } [Fact] - public void testRecvAnnotations() + public void TestRecvAnnotations() { var annotations = new Dictionary {["TEST"] = new byte[] {10, 20, 30, 40, 50}}; - var msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, this.serializer_id, 0, 0, annotations, Encoding.UTF8.GetBytes("secret")); + var msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, _serializerId, 0, 0, annotations, Encoding.UTF8.GetBytes("secret")); var ms = new MemoryStream(msg.to_bytes()); msg = Message.recv(ms, null, Encoding.UTF8.GetBytes("secret")); @@ -160,7 +161,8 @@ public void testRecvAnnotations() Assert.True(msg.annotations.ContainsKey("HMAC")); } - class CustomAnnProxy : PyroProxy + [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] + public class CustomAnnProxy : PyroProxy { public CustomAnnProxy(PyroURI uri) : base(uri) {} @@ -173,7 +175,7 @@ public override IDictionary annotations() } [Fact] - public void testProxyAnnotations() + public void TestProxyAnnotations() { var p = new CustomAnnProxy(new PyroURI("PYRO:dummy@localhost:50000")) { @@ -187,36 +189,36 @@ public void testProxyAnnotations() } [Fact] - public void testProtocolVersionKaputt() + public void TestProtocolVersionKaputt() { - byte[] msg = new Message(Message.MSG_RESULT, new byte[0], this.serializer_id, 0, 1, null, null).to_bytes().Take(Message.HEADER_SIZE).ToArray(); + var msg = new Message(Message.MSG_RESULT, new byte[0], _serializerId, 0, 1, null, null).to_bytes().Take(Message.HEADER_SIZE).ToArray(); msg[4] = 99; // screw up protocol version in message header msg[5] = 111; // screw up protocol version in message header Assert.Throws(() => Message.from_header(msg)); // "invalid protocol version: 25455" } [Fact] - public void testProtocolVersionsNotSupported1() + public void TestProtocolVersionsNotSupported1() { - byte[] msg = new Message(Message.MSG_RESULT, new byte[0], this.serializer_id, 0, 1, null, null).to_bytes().Take(Message.HEADER_SIZE).ToArray(); + var msg = new Message(Message.MSG_RESULT, new byte[0], _serializerId, 0, 1, null, null).to_bytes().Take(Message.HEADER_SIZE).ToArray(); msg[4] = 0; msg[5] = 47; Assert.Throws(() => Message.from_header(msg)); // "invalid protocol version: 47" } [Fact] - public void testProtocolVersionsNotSupported2() + public void TestProtocolVersionsNotSupported2() { - byte[] msg = new Message(Message.MSG_RESULT, new byte[0], this.serializer_id, 0, 1, null, null).to_bytes().Take(Message.HEADER_SIZE).ToArray(); + var msg = new Message(Message.MSG_RESULT, new byte[0], _serializerId, 0, 1, null, null).to_bytes().Take(Message.HEADER_SIZE).ToArray(); msg[4] = 0; msg[5] = 49; Assert.Throws(() => Message.from_header(msg)); //"invalid protocol version: 49" } [Fact] - public void testHmac() + public void TestHmac() { - byte[] data = new Message(Message.MSG_RESULT, new byte[]{1,2,3,4,5}, 42, 0, 1, null, Encoding.UTF8.GetBytes("secret")).to_bytes(); + var data = new Message(Message.MSG_RESULT, new byte[]{1,2,3,4,5}, 42, 0, 1, null, Encoding.UTF8.GetBytes("secret")).to_bytes(); Stream c = new MemoryStream(data); // test checking of different hmacs @@ -244,10 +246,10 @@ public void testHmac() } [Fact] - public void testChecksum() + public void TestChecksum() { var msg = new Message(Message.MSG_RESULT, new byte[]{1,2,3,4}, 42, 0, 1, null, null); - byte[] data = msg.to_bytes(); + var data = msg.to_bytes(); // corrupt the checksum bytes data[Message.HEADER_SIZE-2] = 0; data[Message.HEADER_SIZE-1] = 0; @@ -263,7 +265,7 @@ public void testChecksum() } [Fact] - public void testProxyCorrelationId() + public void TestProxyCorrelationId() { PyroProxy p = new PyroProxy(new PyroURI("PYRO:foo@localhost:55555")) {correlation_id = null}; var ann = p.annotations(); @@ -282,10 +284,10 @@ public void testProxyCorrelationId() public class MessageTestsNoHmac { [Fact] - public void testRecvNoAnnotations() + public void TestRecvNoAnnotations() { var msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, 42, 0, 0, null, null); - byte[] data = msg.to_bytes(); + var data = msg.to_bytes(); var ms = new MemoryStream(data); msg = Message.recv(ms, null, null); Assert.Equal(-1, ms.ReadByte()); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pyro/SerializePyroTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pyro/SerializePyroTests.cs index 1e26adc..92b404e 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pyro/SerializePyroTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pyro/SerializePyroTests.cs @@ -22,7 +22,7 @@ public void PyroClassesSerpent() { var ser = new SerpentSerializer(); var uri = new PyroURI("PYRO:something@localhost:4444"); - byte[] s = ser.serializeData(uri); + var s = ser.serializeData(uri); object x = ser.deserializeData(s); Assert.Equal(uri, x); @@ -86,7 +86,7 @@ public void PyroProxySerpent() [Fact] public void UnserpentProxy() { - byte[] data = Encoding.UTF8.GetBytes("# serpent utf-8 python3.2\n" + + var data = Encoding.UTF8.GetBytes("# serpent utf-8 python3.2\n" + "{'state':('PYRO:Pyro.NameServer@localhost:9090',(),('count','lookup','register','ping','list','remove'),(),0.0,'b64:c2VjcmV0','hello',0),'__class__':'Pyro4.core.Proxy'}"); SerpentSerializer ser = new SerpentSerializer(); @@ -109,7 +109,7 @@ public void PyroClassesPickle() { var pickler = new PickleSerializer(); var uri = new PyroURI("PYRO:something@localhost:4444"); - byte[] s = pickler.serializeData(uri); + var s = pickler.serializeData(uri); object x = pickler.deserializeData(s); Assert.Equal(uri, x); @@ -144,10 +144,10 @@ public void PyroClassesPickle() [Fact] public void TestBytes() { - byte[] bytes = new byte[] { 97, 98, 99, 100, 101, 102 }; // abcdef + byte[] bytes = { 97, 98, 99, 100, 101, 102 }; // abcdef var dict = new Dictionary {{"data", "YWJjZGVm"}, {"encoding", "base64"}}; - byte[] bytes2 = SerpentSerializer.ToBytes(dict); + var bytes2 = SerpentSerializer.ToBytes(dict); Assert.Equal(bytes, bytes2); var hashtable = new Hashtable {{"data", "YWJjZGVm"}, {"encoding", "base64"}}; @@ -170,7 +170,7 @@ public void TestBytes() public class MiscellaneousTests { [Fact] - public void testPyroExceptionType() + public void TestPyroExceptionType() { var ex=new PyroException("hello"); var type = ex.GetType(); @@ -181,7 +181,7 @@ public void testPyroExceptionType() } [Fact] - public void testSerpentDictType() + public void TestSerpentDictType() { Hashtable ht = new Hashtable {["key"] = "value"}; var ser = new SerpentSerializer(); diff --git a/dotnet/Razorvine.Pyrolite/Tests/Pyro/SerpentSerializerTests.cs b/dotnet/Razorvine.Pyrolite/Tests/Pyro/SerpentSerializerTests.cs index 73fec8d..f51f2bf 100644 --- a/dotnet/Razorvine.Pyrolite/Tests/Pyro/SerpentSerializerTests.cs +++ b/dotnet/Razorvine.Pyrolite/Tests/Pyro/SerpentSerializerTests.cs @@ -29,12 +29,12 @@ public void TestSerializeData() list.Add(42); var ser = PyroSerializer.GetFor(Config.SerializerType.serpent); - byte[] data = ser.serializeData(list); + var data = ser.serializeData(list); string str = Encoding.UTF8.GetString(data); Assert.Equal("# serpent utf-8 python2.6\n['hello',42]", str); - List list_obj = (List)ser.deserializeData(data); - Assert.Equal(list, list_obj); + var listObj = (List)ser.deserializeData(data); + Assert.Equal(list, listObj); ISet s = new HashSet(); s.Add("element1"); @@ -43,8 +43,8 @@ public void TestSerializeData() str = Encoding.UTF8.GetString(data); Assert.Equal("# serpent utf-8 python2.6\n('element1','element2')", str); - object[] array_obj = (object[]) ser.deserializeData(data); - Assert.Equal(s, array_obj); + var arrayObj = (object[]) ser.deserializeData(data); + Assert.Equal(s, arrayObj); } [Fact] @@ -56,18 +56,19 @@ public void TestSerializeCall() var ser = PyroSerializer.GetFor(Config.SerializerType.serpent); IDictionary kwargs = new Dictionary(); kwargs["arg"] = 42; - object[] vargs = new object[] {"hello"}; + object[] vargs = {"hello"}; - byte[] data = ser.serializeCall("objectid", "method", vargs, kwargs); + var data = ser.serializeCall("objectid", "method", vargs, kwargs); string s = Encoding.UTF8.GetString(data); Assert.Equal("# serpent utf-8 python2.6\n('objectid','method',('hello',),{'arg':42})", s); - object[] call = (object[])ser.deserializeData(data); - object[] expected = new object[] { + var call = (object[])ser.deserializeData(data); + object[] expected = { "objectid", "method", new object[] {"hello"}, - new Dictionary() { + new Dictionary + { {"arg", 42} } }; @@ -87,11 +88,11 @@ public void TestSerializeData() s.Add("element1"); s.Add("element2"); var ser = PyroSerializer.GetFor(Config.SerializerType.serpent); - byte[] data = ser.serializeData(s); + var data = ser.serializeData(s); string str = Encoding.UTF8.GetString(data); Assert.Equal("# serpent utf-8 python3.2\n{'element1','element2'}", str); - HashSet s2 = (HashSet) ser.deserializeData(data); + var s2 = (HashSet) ser.deserializeData(data); Assert.Equal(s, s2); } @@ -101,16 +102,16 @@ public void TestSerpentBytes() Config.SERPENT_INDENT=false; Config.SERPENT_SET_LITERALS=true; - byte[] bytes = Encoding.ASCII.GetBytes("hello"); + var bytes = Encoding.ASCII.GetBytes("hello"); SerpentSerializer ser = new SerpentSerializer(); - byte[] data = ser.serializeData(bytes); + var data = ser.serializeData(bytes); string str = Encoding.ASCII.GetString(data); Assert.Contains("base64", str); Parser p = new Parser(); - Object data2 = p.Parse(data).GetData(); - byte[] bytes2 = SerpentSerializer.ToBytes(data2); + object data2 = p.Parse(data).GetData(); + var bytes2 = SerpentSerializer.ToBytes(data2); Assert.Equal(Encoding.ASCII.GetBytes("hello"), bytes2); } }