Skip to content

Commit

Permalink
Merge branch 'pr/16'
Browse files Browse the repository at this point in the history
  • Loading branch information
durran committed Apr 3, 2014
2 parents 70cfc02 + 1dbe748 commit ffef691
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
6 changes: 4 additions & 2 deletions ext/bson/native.c
Expand Up @@ -492,10 +492,12 @@ static VALUE rb_integer_to_bson_int64(VALUE self, VALUE encoded)
*/
static VALUE rb_time_to_bson(int argc, VALUE *argv, VALUE self)
{
double t = NUM2DBL(rb_funcall(self, rb_intern("to_f"), 0));
int64_t t = NUM2INT64(rb_funcall(self, rb_intern("to_i"), 0));
int64_t milliseconds = (int64_t)(t * 1000);
int32_t micro = NUM2INT(rb_funcall(self, rb_intern("usec"), 0));
int64_t time = milliseconds + (micro / 1000);
VALUE encoded = rb_get_default_encoded(argc, argv);
return int64_t_to_bson(milliseconds, encoded);
return int64_t_to_bson(time, encoded);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/bson/time.rb
Expand Up @@ -38,7 +38,7 @@ module Time
#
# @since 2.0.0
def to_bson(encoded = ''.force_encoding(BINARY))
encoded << [ (to_f * 1000.0).to_i ].pack(Int64::PACK)
encoded << [ (to_i * 1000) + (usec / 1000) ].pack(Int64::PACK)
end

module ClassMethods
Expand Down
20 changes: 16 additions & 4 deletions spec/bson/time_spec.rb
Expand Up @@ -24,11 +24,23 @@

context "when the time is post epoch" do

let(:obj) { Time.utc(2012, 1, 1, 0, 0, 0) }
let(:bson) { [ (obj.to_f * 1000).to_i ].pack(BSON::Int64::PACK) }
context "when the time has no microseconds" do

it_behaves_like "a serializable bson element"
it_behaves_like "a deserializable bson element"
let(:obj) { Time.utc(2012, 1, 1, 0, 0, 0) }
let(:bson) { [ (obj.to_i * 1000) + (obj.usec / 1000) ].pack(BSON::Int64::PACK) }

it_behaves_like "a serializable bson element"
it_behaves_like "a deserializable bson element"
end

context "when the time has microseconds" do

let(:obj) { Time.at(Time.utc(2014, 03, 22, 18, 05, 05).to_i, 505000).utc }
let(:bson) { [ (obj.to_i * 1000) + (obj.usec / 1000) ].pack(BSON::Int64::PACK) }

it_behaves_like "a serializable bson element"
it_behaves_like "a deserializable bson element"
end
end

context "when the time is pre epoch" do
Expand Down

0 comments on commit ffef691

Please sign in to comment.