Bucket.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package oram;
  2. import java.io.Serializable;
  3. import java.util.Random;
  4. import exceptions.LengthNotMatchException;
  5. public class Bucket implements Serializable {
  6. /**
  7. *
  8. */
  9. private static final long serialVersionUID = 1L;
  10. private int numBytes;
  11. private Tuple[] tuples;
  12. public Bucket(int numTuples, int[] tupleParams, Random rand) {
  13. if (tupleParams.length != 4)
  14. throw new LengthNotMatchException(tupleParams.length + " != 4");
  15. tuples = new Tuple[numTuples];
  16. for (int i = 0; i < numTuples; i++)
  17. tuples[i] = new Tuple(tupleParams[0], tupleParams[1], tupleParams[2], tupleParams[3], rand);
  18. numBytes = numTuples * tuples[0].getNumBytes();
  19. }
  20. public Bucket(Tuple[] tuples) {
  21. this.tuples = tuples;
  22. numBytes = tuples.length * tuples[0].getNumBytes();
  23. }
  24. // deep copy
  25. public Bucket(Bucket b) {
  26. numBytes = b.getNumBytes();
  27. tuples = new Tuple[b.getNumTuples()];
  28. for (int i = 0; i < tuples.length; i++)
  29. tuples[i] = new Tuple(b.getTuple(i));
  30. }
  31. public int getNumBytes() {
  32. return numBytes;
  33. }
  34. public int getNumTuples() {
  35. return tuples.length;
  36. }
  37. public Tuple getTuple(int i) {
  38. return tuples[i];
  39. }
  40. public void setTuple(int i, Tuple tuple) {
  41. if (!tuples[i].sameLength(tuple))
  42. throw new LengthNotMatchException(tuples[i].getNumBytes() + " != " + tuple.getNumBytes());
  43. tuples[i] = tuple;
  44. }
  45. public Bucket xor(Bucket b) {
  46. if (!this.sameLength(b))
  47. throw new LengthNotMatchException(numBytes + " != " + b.getNumBytes());
  48. Tuple[] newTuples = new Tuple[tuples.length];
  49. for (int i = 0; i < tuples.length; i++)
  50. newTuples[i] = tuples[i].xor(b.getTuple(i));
  51. return new Bucket(newTuples);
  52. }
  53. public void setXor(Bucket b) {
  54. if (!this.sameLength(b))
  55. throw new LengthNotMatchException(numBytes + " != " + b.getNumBytes());
  56. for (int i = 0; i < tuples.length; i++)
  57. tuples[i].setXor(b.getTuple(i));
  58. }
  59. public boolean sameLength(Bucket b) {
  60. return numBytes == b.getNumBytes();
  61. }
  62. public byte[] toByteArray() {
  63. int tupleBytes = tuples[0].getNumBytes();
  64. byte[] bucket = new byte[numBytes];
  65. for (int i = 0; i < tuples.length; i++) {
  66. byte[] tuple = tuples[i].toByteArray();
  67. System.arraycopy(tuple, 0, bucket, i * tupleBytes, tupleBytes);
  68. }
  69. return bucket;
  70. }
  71. @Override
  72. public String toString() {
  73. String str = "Bucket:";
  74. for (int i = 0; i < tuples.length; i++)
  75. str += ("\n " + tuples[i]);
  76. return str;
  77. }
  78. }