From ccefb57a0748463c97d2b91ec237b57c55829db9 Mon Sep 17 00:00:00 2001 From: dudaping Date: Mon, 30 Dec 2024 14:34:48 +0800 Subject: [PATCH] implement MarshalBinary --- database.go | 17 +++++++++++++++++ database_bench_test.go | 14 ++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/database.go b/database.go index 41323684..8e56cf29 100644 --- a/database.go +++ b/database.go @@ -55,6 +55,23 @@ func (c *Carbon) UnmarshalJSON(b []byte) error { return c.Error } +// MarshalBinary implements the interface encoding.BinaryMarshaler for Carbon struct. +// 实现 encoding.BinaryMarshaler 接口 +func (c Carbon) MarshalBinary() ([]byte, error) { + return []byte(c.String()), nil +} + +// UnmarshalBinary implements the interface encoding.BinaryUnmarshaler for Carbon struct +// 实现 encoding.BinaryUnmarshaler 接口 +func (c *Carbon) UnmarshalBinary(b []byte) error { + src := bytes.Clone(b) + if len(src) == 0 { + return nil + } + *c = ParseByLayout(string(src), c.layout) + return c.Error +} + // Scan an interface used by Scan in package database/sql for Scanning value from database to local golang variable. func (t *DateTime) Scan(src interface{}) error { switch v := src.(type) { diff --git a/database_bench_test.go b/database_bench_test.go index 5ff3805f..fb05b58f 100755 --- a/database_bench_test.go +++ b/database_bench_test.go @@ -226,6 +226,20 @@ func BenchmarkNewTimestampNano_Value(b *testing.B) { } } +func BenchmarkCarbon_MarshalBinary(b *testing.B) { + now := Now() + for n := 0; n < b.N; n++ { + now.MarshalBinary() + } +} + +func BenchmarkCarbon_UnmarshalBinary(b *testing.B) { + now := Now() + for n := 0; n < b.N; n++ { + now.UnmarshalBinary(nil) + } +} + func BenchmarkCarbon_MarshalJSON(b *testing.B) { now := Now() for n := 0; n < b.N; n++ {