ByteArrays.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * @author Ranides Atterwim <ranides@gmail.com>
  3. * @copyright Ranides Atterwim
  4. * @license WTFPL
  5. * @url http://ranides.net/projects/assira
  6. */
  7. package net.ranides.assira.collection;
  8. /**
  9. *
  10. * @author ranides
  11. */
  12. public class ByteArrays {
  13. public static byte[] make(int size, byte value) {
  14. byte[] content = new byte[size];
  15. if(value!=0) { for(int i=0; i<size; i++) { content[i] = value; } }
  16. return content;
  17. }
  18. public static byte shift(byte[] values) {
  19. if(values == null || values.length==0) { throw new EmptyCollectionException(); }
  20. byte value = values[0];
  21. for(int i=1,n=values.length; i<n; i++) { values[i-1] = values[i]; }
  22. return value;
  23. }
  24. public static byte unshift(byte[] values) {
  25. if(values == null || values.length==0) { throw new EmptyCollectionException(); }
  26. byte value = values[values.length-1];
  27. for(int i=values.length-1; i>0; i--) { values[i] = values[i-1]; }
  28. return value;
  29. }
  30. public static byte[] concat(byte[] first, byte[] second) {
  31. byte[] result = new byte[ first.length + second.length ];
  32. System.arraycopy(first, 0, result, 0, first.length);
  33. System.arraycopy(second, 0, result, first.length, second.length);
  34. return result;
  35. }
  36. /**
  37. * Porównuje zawartość tablic, i zwraca {@code true}, jeśli są równe.
  38. * @param array1
  39. * @param array2
  40. * @return
  41. */
  42. public static boolean isEqual(byte[] array1, byte[] array2) { // @test
  43. if (array1==array2) {
  44. return true;
  45. }
  46. if (array1==null || array2==null) {
  47. return false;
  48. }
  49. int n = array1.length;
  50. if (array2.length != n) {
  51. return false;
  52. }
  53. for (int i=0; i<n; i++) {
  54. if (array1[i] != array2[i]) { return false; }
  55. }
  56. return true;
  57. }
  58. /**
  59. * Porównuje pierwsze {@code size} elementów w tablicach, i zwraca {@code true},
  60. * jeśli są równe.
  61. * @param size
  62. * @param array1
  63. * @param array2
  64. * @return
  65. */
  66. public static boolean isEqual(int size, byte[] array1, byte[] array2) { // @test
  67. if (array1==array2) {
  68. return true;
  69. }
  70. if (array1==null || array2==null) {
  71. return false;
  72. }
  73. if(array1.length != array2.length && (array1.length < size || array2.length < size) ) {
  74. return false;
  75. }
  76. for (int i=0, n=Math.min(array1.length, size); i<n; i++) {
  77. if (array1[i] != array2[i]) { return false; }
  78. }
  79. return true;
  80. }
  81. }