package jocket.futex;

import java.nio.MappedByteBuffer;

import jocket.wait.WaitStrategy;

public class Futex implements WaitStrategy {

  private static boolean libAvailable;

  private final long futAddr;

  private final long seqAddr;

  public Futex(MappedByteBuffer b, int futexPos, int seqPos) {
    this.futAddr = computeAddress(b, futexPos);
    this.seqAddr = computeAddress(b, seqPos);
  }

  @Override
  public void pause(int seq) {
    pause(futAddr, seqAddr, seq);
  }

  private static native void pause(long futAddr2, long seqAddr2, int seq);

  @Override
  public void reset() {
  }

  private static long computeAddress(MappedByteBuffer b, int pos) {
    try {
      int addressSize = 1;// UnsafeUtil.unsafe().addressSize();
      return getAddress(b) + pos / addressSize;
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public void signal(int seq) {
    signal0(futAddr);
  }

  public void await() {
    await0(futAddr);
  }

  private static native long getAddress(MappedByteBuffer b);

  private static native void signal0(long addr);

  private static native void await0(long addr);

  public static native void x86pause();

  public static native long rdtsc();

  static {
    try {
      LibLoader.loadLibrary("JocketFutex");
      libAvailable = true;
    }
    catch (Throwable e) {
      libAvailable = false;
      System.err.println("WARN: JNI futex lib is NOT available: " + e);
      e.printStackTrace();
    }
  }

  public static boolean isAvailable() {
    return libAvailable;
  }
}

@@ -233,16 +233,84 @@
 qAddr;%0A%0A
+  private final MappedByteBuffer buf;%0A%0A  private final int seqPos;%0A%0A
   public
@@ -360,24 +360,68 @@
 t seqPos) %7B%0A
+    this.buf = b;%0A    this.seqPos = seqPos;%0A
     this.fut
@@ -538,22 +538,34 @@
 id pause
-(int s
+While(int currentS
 eq) %7B%0A  
@@ -590,17 +590,24 @@
 eqAddr, 
-s
+currentS
 eq);%0A  %7D
@@ -655,17 +655,16 @@
  futAddr
-2
 , long s
@@ -673,9 +673,8 @@
 Addr
-2
 , in
@@ -805,72 +805,8 @@
 y %7B%0A
-      int addressSize = 1;// UnsafeUtil.unsafe().addressSize();%0A
     
@@ -837,22 +837,8 @@
  pos
- / addressSize
 ;%0A  
@@ -907,32 +907,328 @@
 (e);%0A    %7D%0A  %7D%0A%0A
+  // TEST%0A  public int getInt(int pos) %7B%0A    return getInt0(computeAddress(buf, pos));%0A  %7D%0A%0A  public void setInt(int pos, int value) %7B%0A    setInt0(computeAddress(buf, pos), value);%0A  %7D%0A%0A  private static native int getInt0(long addr);%0A%0A  private static native void setInt0(long addr, int value);%0A%0A
   public void si

Debug futex