Merge branch 'illegal' into 'master'

Add 'illegal' task

See merge request slon/shad-go-private!49
This commit is contained in:
Fedor Korotkiy 2021-04-15 14:36:56 +00:00
commit 531b9745cc
6 changed files with 68 additions and 0 deletions

6
illegal/README.md Normal file
View file

@ -0,0 +1,6 @@
# illegal
Используя пакет unsafe, реализуйте "незаконные" функции:
- `SetPrivateField` меняет приватное поле структуры
- `StringFromBytes` создаёт строку из `[]byte` без доп. аллокаций

6
illegal/field.go Normal file
View file

@ -0,0 +1,6 @@
// +build !solution
package illegal
func SetPrivateField(obj interface{}, name string, value interface{}) {
}

18
illegal/field_test.go Normal file
View file

@ -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())
}

View file

@ -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)
}

7
illegal/string.go Normal file
View file

@ -0,0 +1,7 @@
// +build !solution
package illegal
func StringFromBytes(b []byte) string {
panic("implement me")
}

17
illegal/string_test.go Normal file
View file

@ -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)))
}