diff src/luan/lib/PickleServer.java @ 146:0517a4a7fcc5

add Io.reverse_pickle git-svn-id: https://luan-java.googlecode.com/svn/trunk@147 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Sun, 15 Jun 2014 13:35:33 +0000
parents 90f38a5d0e0a
children cc3a0578edac
line wrap: on
line diff
--- a/src/luan/lib/PickleServer.java	Sun Jun 15 10:02:16 2014 +0000
+++ b/src/luan/lib/PickleServer.java	Sun Jun 15 13:35:33 2014 +0000
@@ -8,15 +8,23 @@
 import java.util.ArrayList;
 import luan.Luan;
 import luan.LuanState;
+import luan.LuanTable;
+import luan.LuanFunction;
+import luan.LuanJavaFunction;
 import luan.LuanException;
 
 
-final class PickleServer {
+public final class PickleServer {
 
 	private final PickleCon con;
+	private boolean isRunning;
 
 	PickleServer(LuanState luan,DataInputStream in,DataOutputStream out) {
-		con = new PickleCon(luan,in,out);
+		this(new PickleCon(luan,in,out));
+	}
+
+	PickleServer(PickleCon con) {
+		this.con = con;
 	}
 
 	void next() throws IOException {
@@ -44,20 +52,54 @@
 	}
 
 	public void run() {
+		LuanTable ioModule = con.ioModule;
+		Object old_reverse_pickle = ioModule.get("reverse_pickle");
+		Object old_close_pickle = ioModule.get("unreverse_pickle");
 		try {
-			while( true ) {
-				next();
+			try {
+				ioModule.put("reverse_pickle", new LuanJavaFunction(
+					PickleServer.class.getMethod( "reverse_pickle" ), this
+				) );
+				ioModule.put("unreverse_pickle", new LuanJavaFunction(
+					PickleServer.class.getMethod( "unreverse_pickle" ), this
+				) );
+			} catch(NoSuchMethodException e) {
+				throw new RuntimeException(e);
 			}
-		} catch(EOFException e) {
-			// done
-		} catch(IOException e) {
-			e.printStackTrace();
-		}
-		try {
-			con.close();
-		} catch(IOException e) {
-			throw new RuntimeException(e);
+			isRunning = true;
+			try {
+				while( isRunning ) {
+					next();
+				}
+			} catch(EOFException e) {
+				// done
+			} catch(IOException e) {
+				e.printStackTrace();
+			}
+			if( isRunning ) {
+				try {
+					con.close();
+				} catch(IOException e) {
+					throw new RuntimeException(e);
+				}
+			}
+		} finally {
+			ioModule.put("reverse_pickle",old_reverse_pickle);
+			ioModule.put("unreverse_pickle",old_close_pickle);
 		}
 	}
 
+	public LuanTable reverse_pickle() throws IOException {
+		try {
+			con.write( "return Io._reversed_pickle()\n" );
+		} catch(LuanException e) {
+			throw new RuntimeException(e);
+		}
+		return new PickleClient(con).table();
+	}
+
+	public void unreverse_pickle() {
+		isRunning = false;
+	}
+
 }