From 754c23a560f3d7aa194863fe0bcdab0001a19d13 Mon Sep 17 00:00:00 2001 From: Fedor Korotkiy Date: Wed, 14 Apr 2021 18:41:01 +0300 Subject: [PATCH] Add illegal task --- illegal/README.md | 6 ++++++ illegal/field.go | 6 ++++++ illegal/field_test.go | 18 ++++++++++++++++++ illegal/internal/struct.go | 14 ++++++++++++++ illegal/string.go | 7 +++++++ illegal/string_test.go | 17 +++++++++++++++++ 6 files changed, 68 insertions(+) create mode 100644 illegal/README.md create mode 100644 illegal/field.go create mode 100644 illegal/field_test.go create mode 100644 illegal/internal/struct.go create mode 100644 illegal/string.go create mode 100644 illegal/string_test.go diff --git a/illegal/README.md b/illegal/README.md new file mode 100644 index 0000000..4940565 --- /dev/null +++ b/illegal/README.md @@ -0,0 +1,6 @@ +# illegal + +Используя пакет unsafe, реализуйте "незаконные" функции: + +- `SetPrivateField` меняет приватное поле структуры +- `StringFromBytes` создаёт строку из `[]byte` без доп. аллокаций diff --git a/illegal/field.go b/illegal/field.go new file mode 100644 index 0000000..daf0040 --- /dev/null +++ b/illegal/field.go @@ -0,0 +1,6 @@ +// +build !solution + +package illegal + +func SetPrivateField(obj interface{}, name string, value interface{}) { +} diff --git a/illegal/field_test.go b/illegal/field_test.go new file mode 100644 index 0000000..d542de1 --- /dev/null +++ b/illegal/field_test.go @@ -0,0 +1,18 @@ +package illegal_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "gitlab.com/slon/shad-go/illegal" + "gitlab.com/slon/shad-go/illegal/internal" +) + +func TestIllegalField(t *testing.T) { + var s internal.Struct + + illegal.SetPrivateField(&s, "a", 10) + illegal.SetPrivateField(&s, "b", "foo") + + assert.Equal(t, "10 foo", s.String()) +} diff --git a/illegal/internal/struct.go b/illegal/internal/struct.go new file mode 100644 index 0000000..4bfe525 --- /dev/null +++ b/illegal/internal/struct.go @@ -0,0 +1,14 @@ +// +build !change + +package internal + +import "fmt" + +type Struct struct { + a int + b string +} + +func (s *Struct) String() string { + return fmt.Sprintf("%d %s", s.a, s.b) +} diff --git a/illegal/string.go b/illegal/string.go new file mode 100644 index 0000000..92451ba --- /dev/null +++ b/illegal/string.go @@ -0,0 +1,7 @@ +// +build !solution + +package illegal + +func StringFromBytes(b []byte) string { + panic("implement me") +} diff --git a/illegal/string_test.go b/illegal/string_test.go new file mode 100644 index 0000000..bfd1014 --- /dev/null +++ b/illegal/string_test.go @@ -0,0 +1,17 @@ +package illegal_test + +import ( + "testing" + "unsafe" + + "github.com/stretchr/testify/assert" + "gitlab.com/slon/shad-go/illegal" +) + +func TestStringFromBytes(t *testing.T) { + b := []byte{'a', 'b', 'c'} + s := illegal.StringFromBytes(b) + + assert.Equal(t, "abc", s) + assert.Equal(t, **(**uintptr)(unsafe.Pointer(&b)), **(**uintptr)(unsafe.Pointer(&s))) +}