Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions src/main/java/org/elasticsearch/common/unit/TimeValue.java
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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));

}
}