Skip to content

Commit

Permalink
Internal: Fix equality check of timevalue after serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
msbt authored and rjernst committed Mar 6, 2015
1 parent 3b234a9 commit ec4befa
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
14 changes: 6 additions & 8 deletions src/main/java/org/elasticsearch/common/unit/TimeValue.java
Expand Up @@ -268,6 +268,9 @@ public static TimeValue readTimeValue(StreamInput in) throws IOException {
return timeValue;
}

/**
* serialization converts TimeValue internally to NANOSECONDS
*/
@Override
public void readFrom(StreamInput in) throws IOException {
duration = in.readLong();
Expand All @@ -285,17 +288,12 @@ public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;

TimeValue timeValue = (TimeValue) o;

if (duration != timeValue.duration) return false;
if (timeUnit != timeValue.timeUnit) return false;

return true;
return timeUnit.toNanos(duration) == timeValue.timeUnit.toNanos(timeValue.duration);
}

@Override
public int hashCode() {
int result = (int) (duration ^ (duration >>> 32));
result = 31 * result + (timeUnit != null ? timeUnit.hashCode() : 0);
return result;
long normalized = timeUnit.toNanos(duration);
return (int) (normalized ^ (normalized >>> 32));
}
}
22 changes: 21 additions & 1 deletion src/test/java/org/elasticsearch/common/unit/TimeValueTests.java
Expand Up @@ -19,13 +19,15 @@

package org.elasticsearch.common.unit;

import org.elasticsearch.common.io.stream.BytesStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.joda.time.PeriodType;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;

Expand Down Expand Up @@ -66,4 +68,22 @@ public void testFormat() {
public void testMinusOne() {
assertThat(new TimeValue(-1).nanos(), lessThan(0l));
}

private void assertEqualityAfterSerialize(TimeValue value) throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
value.writeTo(out);

BytesStreamInput in = new BytesStreamInput(out.bytes());
TimeValue inValue = TimeValue.readTimeValue(in);

assertThat(inValue, equalTo(value));
}

@Test
public void testSerialize() throws Exception {
assertEqualityAfterSerialize(new TimeValue(100, TimeUnit.DAYS));
assertEqualityAfterSerialize(new TimeValue(-1));
assertEqualityAfterSerialize(new TimeValue(1, TimeUnit.NANOSECONDS));

}
}

0 comments on commit ec4befa

Please sign in to comment.