checkpoint
[sbp.git] / src / edu / berkeley / sbp / bind / Bindable.java
index 7c620c9..ccaa51d 100644 (file)
@@ -29,25 +29,43 @@ public abstract class Bindable implements ToJava {
         return null;
     }
 
-    public Binding createBinding() {
-        return new Binding() {
-                public Object invoke(Object[] o) {
-                    return impose(o);
-                }
-            };
-    }
-    public Binding createBinding(final int[] map) {
-        return new Binding() {
-                public Object invoke(Object[] o) {
-                    int max = 0;
-                    for(int i=0; i<map.length; i++) max = Math.max(map[i], max);
-                    Object[] o2 = new Object[max+1];
-                    for(int i=0; i<o.length; i++) o2[map[i]] = o[i];
-                    return impose(o2);
+    public Binding createBinding() { return new SimpleBinding(); }
+    public Binding createBinding(final int[] map) { return new SimpleBinding(map); }
+    public Binding createBinding(final int[] map, Object prepend) { return new SimpleBinding(map, prepend); }
+
+    public class SimpleBinding implements Binding, ToJava {
+        private int[] map = null;
+        private Object prepend = null;
+        public SimpleBinding() { }
+        public SimpleBinding(int[] map) { this.map = map; }
+        public SimpleBinding(int[] map, Object prepend) { this.map = map; this.prepend = prepend; }
+
+        public Object invoke(Object[] o) {
+            if (map==null) return impose(o);
+            int max = 0;
+            for(int i=0; i<map.length; i++) max = Math.max(map[i], max);
+            Object[] o2 = new Object[max+1];
+            for(int i=0; i<o.length; i++) o2[map[i]+(prepend==null?0:1)] = o[i];
+            if (prepend != null) o2[0] = prepend;
+            return impose(o2);
+        }
+
+        public void toJava(StringBuffer sb) {
+            Bindable.this.toJava(sb);
+            sb.append(".createBinding(");
+            if (map != null) {
+                sb.append("new int[] {");
+                for(int i=0; i<map.length; i++) {
+                    sb.append(i);
+                    if (i<map.length-1) sb.append(",");
                 }
-            };
+                sb.append("}");
+            }
+            sb.append(")");
+        }
     }
 
+
     private static class BindableMethod extends Bindable {
         private final Method _method;
         public String toString() { return "BindableMethod["+_method+"]"; }