repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
golang/appengine
|
internal/api_classic.go
|
ClassicContextFromContext
|
func ClassicContextFromContext(ctx netcontext.Context) (appengine.Context, error) {
c := fromContext(ctx)
if c == nil {
return nil, errNotAppEngineContext
}
return c, nil
}
|
go
|
func ClassicContextFromContext(ctx netcontext.Context) (appengine.Context, error) {
c := fromContext(ctx)
if c == nil {
return nil, errNotAppEngineContext
}
return c, nil
}
|
[
"func",
"ClassicContextFromContext",
"(",
"ctx",
"netcontext",
".",
"Context",
")",
"(",
"appengine",
".",
"Context",
",",
"error",
")",
"{",
"c",
":=",
"fromContext",
"(",
"ctx",
")",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
",",
"errNotAppEngineContext",
"\n",
"}",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] |
// This is only for classic App Engine adapters.
|
[
"This",
"is",
"only",
"for",
"classic",
"App",
"Engine",
"adapters",
"."
] |
54a98f90d1c46b7731eb8fb305d2a321c30ef610
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/api_classic.go#L33-L39
|
test
|
golang/appengine
|
mail/mail.go
|
Send
|
func Send(c context.Context, msg *Message) error {
return send(c, "Send", msg)
}
|
go
|
func Send(c context.Context, msg *Message) error {
return send(c, "Send", msg)
}
|
[
"func",
"Send",
"(",
"c",
"context",
".",
"Context",
",",
"msg",
"*",
"Message",
")",
"error",
"{",
"return",
"send",
"(",
"c",
",",
"\"Send\"",
",",
"msg",
")",
"\n",
"}"
] |
// Send sends an email message.
|
[
"Send",
"sends",
"an",
"email",
"message",
"."
] |
54a98f90d1c46b7731eb8fb305d2a321c30ef610
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/mail/mail.go#L68-L70
|
test
|
golang/appengine
|
mail/mail.go
|
SendToAdmins
|
func SendToAdmins(c context.Context, msg *Message) error {
return send(c, "SendToAdmins", msg)
}
|
go
|
func SendToAdmins(c context.Context, msg *Message) error {
return send(c, "SendToAdmins", msg)
}
|
[
"func",
"SendToAdmins",
"(",
"c",
"context",
".",
"Context",
",",
"msg",
"*",
"Message",
")",
"error",
"{",
"return",
"send",
"(",
"c",
",",
"\"SendToAdmins\"",
",",
"msg",
")",
"\n",
"}"
] |
// SendToAdmins sends an email message to the application's administrators.
|
[
"SendToAdmins",
"sends",
"an",
"email",
"message",
"to",
"the",
"application",
"s",
"administrators",
"."
] |
54a98f90d1c46b7731eb8fb305d2a321c30ef610
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/mail/mail.go#L73-L75
|
test
|
jstemmer/go-junit-report
|
parser/parser.go
|
Failures
|
func (r *Report) Failures() int {
count := 0
for _, p := range r.Packages {
for _, t := range p.Tests {
if t.Result == FAIL {
count++
}
}
}
return count
}
|
go
|
func (r *Report) Failures() int {
count := 0
for _, p := range r.Packages {
for _, t := range p.Tests {
if t.Result == FAIL {
count++
}
}
}
return count
}
|
[
"func",
"(",
"r",
"*",
"Report",
")",
"Failures",
"(",
")",
"int",
"{",
"count",
":=",
"0",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"r",
".",
"Packages",
"{",
"for",
"_",
",",
"t",
":=",
"range",
"p",
".",
"Tests",
"{",
"if",
"t",
".",
"Result",
"==",
"FAIL",
"{",
"count",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"count",
"\n",
"}"
] |
// Failures counts the number of failed tests in this report
|
[
"Failures",
"counts",
"the",
"number",
"of",
"failed",
"tests",
"in",
"this",
"report"
] |
af01ea7f8024089b458d804d5cdf190f962a9a0c
|
https://github.com/jstemmer/go-junit-report/blob/af01ea7f8024089b458d804d5cdf190f962a9a0c/parser/parser.go#L291-L303
|
test
|
tendermint/go-amino
|
binary-decode.go
|
decodeFieldNumberAndTyp3
|
func decodeFieldNumberAndTyp3(bz []byte) (num uint32, typ Typ3, n int, err error) {
// Read uvarint value.
var value64 = uint64(0)
value64, n, err = DecodeUvarint(bz)
if err != nil {
return
}
// Decode first typ3 byte.
typ = Typ3(value64 & 0x07)
// Decode num.
var num64 uint64
num64 = value64 >> 3
if num64 > (1<<29 - 1) {
err = fmt.Errorf("invalid field num %v", num64)
return
}
num = uint32(num64)
return
}
|
go
|
func decodeFieldNumberAndTyp3(bz []byte) (num uint32, typ Typ3, n int, err error) {
// Read uvarint value.
var value64 = uint64(0)
value64, n, err = DecodeUvarint(bz)
if err != nil {
return
}
// Decode first typ3 byte.
typ = Typ3(value64 & 0x07)
// Decode num.
var num64 uint64
num64 = value64 >> 3
if num64 > (1<<29 - 1) {
err = fmt.Errorf("invalid field num %v", num64)
return
}
num = uint32(num64)
return
}
|
[
"func",
"decodeFieldNumberAndTyp3",
"(",
"bz",
"[",
"]",
"byte",
")",
"(",
"num",
"uint32",
",",
"typ",
"Typ3",
",",
"n",
"int",
",",
"err",
"error",
")",
"{",
"var",
"value64",
"=",
"uint64",
"(",
"0",
")",
"\n",
"value64",
",",
"n",
",",
"err",
"=",
"DecodeUvarint",
"(",
"bz",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"typ",
"=",
"Typ3",
"(",
"value64",
"&",
"0x07",
")",
"\n",
"var",
"num64",
"uint64",
"\n",
"num64",
"=",
"value64",
">>",
"3",
"\n",
"if",
"num64",
">",
"(",
"1",
"<<",
"29",
"-",
"1",
")",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"invalid field num %v\"",
",",
"num64",
")",
"\n",
"return",
"\n",
"}",
"\n",
"num",
"=",
"uint32",
"(",
"num64",
")",
"\n",
"return",
"\n",
"}"
] |
// Read field key.
|
[
"Read",
"field",
"key",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/binary-decode.go#L891-L912
|
test
|
tendermint/go-amino
|
binary-decode.go
|
checkTyp3
|
func checkTyp3(rt reflect.Type, typ Typ3, fopts FieldOptions) (err error) {
typWanted := typeToTyp3(rt, fopts)
if typ != typWanted {
err = fmt.Errorf("unexpected Typ3. want %v, got %v", typWanted, typ)
}
return
}
|
go
|
func checkTyp3(rt reflect.Type, typ Typ3, fopts FieldOptions) (err error) {
typWanted := typeToTyp3(rt, fopts)
if typ != typWanted {
err = fmt.Errorf("unexpected Typ3. want %v, got %v", typWanted, typ)
}
return
}
|
[
"func",
"checkTyp3",
"(",
"rt",
"reflect",
".",
"Type",
",",
"typ",
"Typ3",
",",
"fopts",
"FieldOptions",
")",
"(",
"err",
"error",
")",
"{",
"typWanted",
":=",
"typeToTyp3",
"(",
"rt",
",",
"fopts",
")",
"\n",
"if",
"typ",
"!=",
"typWanted",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"unexpected Typ3. want %v, got %v\"",
",",
"typWanted",
",",
"typ",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Error if typ doesn't match rt.
|
[
"Error",
"if",
"typ",
"doesn",
"t",
"match",
"rt",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/binary-decode.go#L915-L921
|
test
|
tendermint/go-amino
|
binary-decode.go
|
decodeTyp3
|
func decodeTyp3(bz []byte) (typ Typ3, n int, err error) {
if len(bz) == 0 {
err = fmt.Errorf("EOF while reading typ3 byte")
return
}
if bz[0]&0xF8 != 0 {
err = fmt.Errorf("invalid typ3 byte: %v", Typ3(bz[0]).String())
return
}
typ = Typ3(bz[0])
n = 1
return
}
|
go
|
func decodeTyp3(bz []byte) (typ Typ3, n int, err error) {
if len(bz) == 0 {
err = fmt.Errorf("EOF while reading typ3 byte")
return
}
if bz[0]&0xF8 != 0 {
err = fmt.Errorf("invalid typ3 byte: %v", Typ3(bz[0]).String())
return
}
typ = Typ3(bz[0])
n = 1
return
}
|
[
"func",
"decodeTyp3",
"(",
"bz",
"[",
"]",
"byte",
")",
"(",
"typ",
"Typ3",
",",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"bz",
")",
"==",
"0",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"EOF while reading typ3 byte\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"bz",
"[",
"0",
"]",
"&",
"0xF8",
"!=",
"0",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"invalid typ3 byte: %v\"",
",",
"Typ3",
"(",
"bz",
"[",
"0",
"]",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"typ",
"=",
"Typ3",
"(",
"bz",
"[",
"0",
"]",
")",
"\n",
"n",
"=",
"1",
"\n",
"return",
"\n",
"}"
] |
// Read typ3 byte.
|
[
"Read",
"typ3",
"byte",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/binary-decode.go#L924-L936
|
test
|
tendermint/go-amino
|
codec.go
|
NewPrefixBytes
|
func NewPrefixBytes(prefixBytes []byte) PrefixBytes {
pb := PrefixBytes{}
copy(pb[:], prefixBytes)
return pb
}
|
go
|
func NewPrefixBytes(prefixBytes []byte) PrefixBytes {
pb := PrefixBytes{}
copy(pb[:], prefixBytes)
return pb
}
|
[
"func",
"NewPrefixBytes",
"(",
"prefixBytes",
"[",
"]",
"byte",
")",
"PrefixBytes",
"{",
"pb",
":=",
"PrefixBytes",
"{",
"}",
"\n",
"copy",
"(",
"pb",
"[",
":",
"]",
",",
"prefixBytes",
")",
"\n",
"return",
"pb",
"\n",
"}"
] |
// Copy into PrefixBytes
|
[
"Copy",
"into",
"PrefixBytes"
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L32-L36
|
test
|
tendermint/go-amino
|
codec.go
|
getLengthStr
|
func getLengthStr(info *TypeInfo) string {
switch info.Type.Kind() {
case reflect.Array,
reflect.Int8,
reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Float32, reflect.Float64,
reflect.Complex64, reflect.Complex128:
s := info.Type.Size()
return fmt.Sprintf("0x%X", s)
default:
return "variable"
}
}
|
go
|
func getLengthStr(info *TypeInfo) string {
switch info.Type.Kind() {
case reflect.Array,
reflect.Int8,
reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Float32, reflect.Float64,
reflect.Complex64, reflect.Complex128:
s := info.Type.Size()
return fmt.Sprintf("0x%X", s)
default:
return "variable"
}
}
|
[
"func",
"getLengthStr",
"(",
"info",
"*",
"TypeInfo",
")",
"string",
"{",
"switch",
"info",
".",
"Type",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Array",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
",",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
",",
"reflect",
".",
"Complex64",
",",
"reflect",
".",
"Complex128",
":",
"s",
":=",
"info",
".",
"Type",
".",
"Size",
"(",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"0x%X\"",
",",
"s",
")",
"\n",
"default",
":",
"return",
"\"variable\"",
"\n",
"}",
"\n",
"}"
] |
// A heuristic to guess the size of a registered type and return it as a string.
// If the size is not fixed it returns "variable".
|
[
"A",
"heuristic",
"to",
"guess",
"the",
"size",
"of",
"a",
"registered",
"type",
"and",
"return",
"it",
"as",
"a",
"string",
".",
"If",
"the",
"size",
"is",
"not",
"fixed",
"it",
"returns",
"variable",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L307-L319
|
test
|
tendermint/go-amino
|
codec.go
|
collectImplementers_nolock
|
func (cdc *Codec) collectImplementers_nolock(info *TypeInfo) {
for _, cinfo := range cdc.concreteInfos {
if cinfo.PtrToType.Implements(info.Type) {
info.Implementers[cinfo.Prefix] = append(
info.Implementers[cinfo.Prefix], cinfo)
}
}
}
|
go
|
func (cdc *Codec) collectImplementers_nolock(info *TypeInfo) {
for _, cinfo := range cdc.concreteInfos {
if cinfo.PtrToType.Implements(info.Type) {
info.Implementers[cinfo.Prefix] = append(
info.Implementers[cinfo.Prefix], cinfo)
}
}
}
|
[
"func",
"(",
"cdc",
"*",
"Codec",
")",
"collectImplementers_nolock",
"(",
"info",
"*",
"TypeInfo",
")",
"{",
"for",
"_",
",",
"cinfo",
":=",
"range",
"cdc",
".",
"concreteInfos",
"{",
"if",
"cinfo",
".",
"PtrToType",
".",
"Implements",
"(",
"info",
".",
"Type",
")",
"{",
"info",
".",
"Implementers",
"[",
"cinfo",
".",
"Prefix",
"]",
"=",
"append",
"(",
"info",
".",
"Implementers",
"[",
"cinfo",
".",
"Prefix",
"]",
",",
"cinfo",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Find all conflicting prefixes for concrete types
// that "implement" the interface. "Implement" in quotes because
// we only consider the pointer, for extra safety.
|
[
"Find",
"all",
"conflicting",
"prefixes",
"for",
"concrete",
"types",
"that",
"implement",
"the",
"interface",
".",
"Implement",
"in",
"quotes",
"because",
"we",
"only",
"consider",
"the",
"pointer",
"for",
"extra",
"safety",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L617-L624
|
test
|
tendermint/go-amino
|
codec.go
|
checkConflictsInPrio_nolock
|
func (cdc *Codec) checkConflictsInPrio_nolock(iinfo *TypeInfo) error {
for _, cinfos := range iinfo.Implementers {
if len(cinfos) < 2 {
continue
}
for _, cinfo := range cinfos {
var inPrio = false
for _, disfix := range iinfo.InterfaceInfo.Priority {
if cinfo.GetDisfix() == disfix {
inPrio = true
}
}
if !inPrio {
return fmt.Errorf("%v conflicts with %v other(s). Add it to the priority list for %v.",
cinfo.Type, len(cinfos), iinfo.Type)
}
}
}
return nil
}
|
go
|
func (cdc *Codec) checkConflictsInPrio_nolock(iinfo *TypeInfo) error {
for _, cinfos := range iinfo.Implementers {
if len(cinfos) < 2 {
continue
}
for _, cinfo := range cinfos {
var inPrio = false
for _, disfix := range iinfo.InterfaceInfo.Priority {
if cinfo.GetDisfix() == disfix {
inPrio = true
}
}
if !inPrio {
return fmt.Errorf("%v conflicts with %v other(s). Add it to the priority list for %v.",
cinfo.Type, len(cinfos), iinfo.Type)
}
}
}
return nil
}
|
[
"func",
"(",
"cdc",
"*",
"Codec",
")",
"checkConflictsInPrio_nolock",
"(",
"iinfo",
"*",
"TypeInfo",
")",
"error",
"{",
"for",
"_",
",",
"cinfos",
":=",
"range",
"iinfo",
".",
"Implementers",
"{",
"if",
"len",
"(",
"cinfos",
")",
"<",
"2",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"cinfo",
":=",
"range",
"cinfos",
"{",
"var",
"inPrio",
"=",
"false",
"\n",
"for",
"_",
",",
"disfix",
":=",
"range",
"iinfo",
".",
"InterfaceInfo",
".",
"Priority",
"{",
"if",
"cinfo",
".",
"GetDisfix",
"(",
")",
"==",
"disfix",
"{",
"inPrio",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"inPrio",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"%v conflicts with %v other(s). Add it to the priority list for %v.\"",
",",
"cinfo",
".",
"Type",
",",
"len",
"(",
"cinfos",
")",
",",
"iinfo",
".",
"Type",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Ensure that prefix-conflicting implementing concrete types
// are all registered in the priority list.
// Returns an error if a disamb conflict is found.
|
[
"Ensure",
"that",
"prefix",
"-",
"conflicting",
"implementing",
"concrete",
"types",
"are",
"all",
"registered",
"in",
"the",
"priority",
"list",
".",
"Returns",
"an",
"error",
"if",
"a",
"disamb",
"conflict",
"is",
"found",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L629-L649
|
test
|
tendermint/go-amino
|
reflect.go
|
constructConcreteType
|
func constructConcreteType(cinfo *TypeInfo) (crv, irvSet reflect.Value) {
// Construct new concrete type.
if cinfo.PointerPreferred {
cPtrRv := reflect.New(cinfo.Type)
crv = cPtrRv.Elem()
irvSet = cPtrRv
} else {
crv = reflect.New(cinfo.Type).Elem()
irvSet = crv
}
return
}
|
go
|
func constructConcreteType(cinfo *TypeInfo) (crv, irvSet reflect.Value) {
// Construct new concrete type.
if cinfo.PointerPreferred {
cPtrRv := reflect.New(cinfo.Type)
crv = cPtrRv.Elem()
irvSet = cPtrRv
} else {
crv = reflect.New(cinfo.Type).Elem()
irvSet = crv
}
return
}
|
[
"func",
"constructConcreteType",
"(",
"cinfo",
"*",
"TypeInfo",
")",
"(",
"crv",
",",
"irvSet",
"reflect",
".",
"Value",
")",
"{",
"if",
"cinfo",
".",
"PointerPreferred",
"{",
"cPtrRv",
":=",
"reflect",
".",
"New",
"(",
"cinfo",
".",
"Type",
")",
"\n",
"crv",
"=",
"cPtrRv",
".",
"Elem",
"(",
")",
"\n",
"irvSet",
"=",
"cPtrRv",
"\n",
"}",
"else",
"{",
"crv",
"=",
"reflect",
".",
"New",
"(",
"cinfo",
".",
"Type",
")",
".",
"Elem",
"(",
")",
"\n",
"irvSet",
"=",
"crv",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// constructConcreteType creates the concrete value as
// well as the corresponding settable value for it.
// Return irvSet which should be set on caller's interface rv.
|
[
"constructConcreteType",
"creates",
"the",
"concrete",
"value",
"as",
"well",
"as",
"the",
"corresponding",
"settable",
"value",
"for",
"it",
".",
"Return",
"irvSet",
"which",
"should",
"be",
"set",
"on",
"caller",
"s",
"interface",
"rv",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/reflect.go#L181-L192
|
test
|
tendermint/go-amino
|
amino.go
|
MarshalBinaryLengthPrefixedWriter
|
func (cdc *Codec) MarshalBinaryLengthPrefixedWriter(w io.Writer, o interface{}) (n int64, err error) {
var bz, _n = []byte(nil), int(0)
bz, err = cdc.MarshalBinaryLengthPrefixed(o)
if err != nil {
return 0, err
}
_n, err = w.Write(bz) // TODO: handle overflow in 32-bit systems.
n = int64(_n)
return
}
|
go
|
func (cdc *Codec) MarshalBinaryLengthPrefixedWriter(w io.Writer, o interface{}) (n int64, err error) {
var bz, _n = []byte(nil), int(0)
bz, err = cdc.MarshalBinaryLengthPrefixed(o)
if err != nil {
return 0, err
}
_n, err = w.Write(bz) // TODO: handle overflow in 32-bit systems.
n = int64(_n)
return
}
|
[
"func",
"(",
"cdc",
"*",
"Codec",
")",
"MarshalBinaryLengthPrefixedWriter",
"(",
"w",
"io",
".",
"Writer",
",",
"o",
"interface",
"{",
"}",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"var",
"bz",
",",
"_n",
"=",
"[",
"]",
"byte",
"(",
"nil",
")",
",",
"int",
"(",
"0",
")",
"\n",
"bz",
",",
"err",
"=",
"cdc",
".",
"MarshalBinaryLengthPrefixed",
"(",
"o",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"_n",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"bz",
")",
"\n",
"n",
"=",
"int64",
"(",
"_n",
")",
"\n",
"return",
"\n",
"}"
] |
// MarshalBinaryLengthPrefixedWriter writes the bytes as would be returned from
// MarshalBinaryLengthPrefixed to the writer w.
|
[
"MarshalBinaryLengthPrefixedWriter",
"writes",
"the",
"bytes",
"as",
"would",
"be",
"returned",
"from",
"MarshalBinaryLengthPrefixed",
"to",
"the",
"writer",
"w",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L165-L174
|
test
|
tendermint/go-amino
|
amino.go
|
MarshalBinaryBare
|
func (cdc *Codec) MarshalBinaryBare(o interface{}) ([]byte, error) {
// Dereference value if pointer.
var rv, _, isNilPtr = derefPointers(reflect.ValueOf(o))
if isNilPtr {
// NOTE: You can still do so by calling
// `.MarshalBinaryLengthPrefixed(struct{ *SomeType })` or so on.
panic("MarshalBinaryBare cannot marshal a nil pointer directly. Try wrapping in a struct?")
}
// Encode Amino:binary bytes.
var bz []byte
buf := new(bytes.Buffer)
rt := rv.Type()
info, err := cdc.getTypeInfo_wlock(rt)
if err != nil {
return nil, err
}
err = cdc.encodeReflectBinary(buf, info, rv, FieldOptions{BinFieldNum: 1}, true)
if err != nil {
return nil, err
}
bz = buf.Bytes()
// If registered concrete, prepend prefix bytes.
if info.Registered {
pb := info.Prefix.Bytes()
bz = append(pb, bz...)
}
return bz, nil
}
|
go
|
func (cdc *Codec) MarshalBinaryBare(o interface{}) ([]byte, error) {
// Dereference value if pointer.
var rv, _, isNilPtr = derefPointers(reflect.ValueOf(o))
if isNilPtr {
// NOTE: You can still do so by calling
// `.MarshalBinaryLengthPrefixed(struct{ *SomeType })` or so on.
panic("MarshalBinaryBare cannot marshal a nil pointer directly. Try wrapping in a struct?")
}
// Encode Amino:binary bytes.
var bz []byte
buf := new(bytes.Buffer)
rt := rv.Type()
info, err := cdc.getTypeInfo_wlock(rt)
if err != nil {
return nil, err
}
err = cdc.encodeReflectBinary(buf, info, rv, FieldOptions{BinFieldNum: 1}, true)
if err != nil {
return nil, err
}
bz = buf.Bytes()
// If registered concrete, prepend prefix bytes.
if info.Registered {
pb := info.Prefix.Bytes()
bz = append(pb, bz...)
}
return bz, nil
}
|
[
"func",
"(",
"cdc",
"*",
"Codec",
")",
"MarshalBinaryBare",
"(",
"o",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"rv",
",",
"_",
",",
"isNilPtr",
"=",
"derefPointers",
"(",
"reflect",
".",
"ValueOf",
"(",
"o",
")",
")",
"\n",
"if",
"isNilPtr",
"{",
"panic",
"(",
"\"MarshalBinaryBare cannot marshal a nil pointer directly. Try wrapping in a struct?\"",
")",
"\n",
"}",
"\n",
"var",
"bz",
"[",
"]",
"byte",
"\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"rt",
":=",
"rv",
".",
"Type",
"(",
")",
"\n",
"info",
",",
"err",
":=",
"cdc",
".",
"getTypeInfo_wlock",
"(",
"rt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"cdc",
".",
"encodeReflectBinary",
"(",
"buf",
",",
"info",
",",
"rv",
",",
"FieldOptions",
"{",
"BinFieldNum",
":",
"1",
"}",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"bz",
"=",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"if",
"info",
".",
"Registered",
"{",
"pb",
":=",
"info",
".",
"Prefix",
".",
"Bytes",
"(",
")",
"\n",
"bz",
"=",
"append",
"(",
"pb",
",",
"bz",
"...",
")",
"\n",
"}",
"\n",
"return",
"bz",
",",
"nil",
"\n",
"}"
] |
// MarshalBinaryBare encodes the object o according to the Amino spec.
// MarshalBinaryBare doesn't prefix the byte-length of the encoding,
// so the caller must handle framing.
|
[
"MarshalBinaryBare",
"encodes",
"the",
"object",
"o",
"according",
"to",
"the",
"Amino",
"spec",
".",
"MarshalBinaryBare",
"doesn",
"t",
"prefix",
"the",
"byte",
"-",
"length",
"of",
"the",
"encoding",
"so",
"the",
"caller",
"must",
"handle",
"framing",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L188-L219
|
test
|
tendermint/go-amino
|
amino.go
|
UnmarshalBinaryLengthPrefixed
|
func (cdc *Codec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr interface{}) error {
if len(bz) == 0 {
return errors.New("UnmarshalBinaryLengthPrefixed cannot decode empty bytes")
}
// Read byte-length prefix.
u64, n := binary.Uvarint(bz)
if n < 0 {
return fmt.Errorf("Error reading msg byte-length prefix: got code %v", n)
}
if u64 > uint64(len(bz)-n) {
return fmt.Errorf("Not enough bytes to read in UnmarshalBinaryLengthPrefixed, want %v more bytes but only have %v",
u64, len(bz)-n)
} else if u64 < uint64(len(bz)-n) {
return fmt.Errorf("Bytes left over in UnmarshalBinaryLengthPrefixed, should read %v more bytes but have %v",
u64, len(bz)-n)
}
bz = bz[n:]
// Decode.
return cdc.UnmarshalBinaryBare(bz, ptr)
}
|
go
|
func (cdc *Codec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr interface{}) error {
if len(bz) == 0 {
return errors.New("UnmarshalBinaryLengthPrefixed cannot decode empty bytes")
}
// Read byte-length prefix.
u64, n := binary.Uvarint(bz)
if n < 0 {
return fmt.Errorf("Error reading msg byte-length prefix: got code %v", n)
}
if u64 > uint64(len(bz)-n) {
return fmt.Errorf("Not enough bytes to read in UnmarshalBinaryLengthPrefixed, want %v more bytes but only have %v",
u64, len(bz)-n)
} else if u64 < uint64(len(bz)-n) {
return fmt.Errorf("Bytes left over in UnmarshalBinaryLengthPrefixed, should read %v more bytes but have %v",
u64, len(bz)-n)
}
bz = bz[n:]
// Decode.
return cdc.UnmarshalBinaryBare(bz, ptr)
}
|
[
"func",
"(",
"cdc",
"*",
"Codec",
")",
"UnmarshalBinaryLengthPrefixed",
"(",
"bz",
"[",
"]",
"byte",
",",
"ptr",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"len",
"(",
"bz",
")",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"UnmarshalBinaryLengthPrefixed cannot decode empty bytes\"",
")",
"\n",
"}",
"\n",
"u64",
",",
"n",
":=",
"binary",
".",
"Uvarint",
"(",
"bz",
")",
"\n",
"if",
"n",
"<",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Error reading msg byte-length prefix: got code %v\"",
",",
"n",
")",
"\n",
"}",
"\n",
"if",
"u64",
">",
"uint64",
"(",
"len",
"(",
"bz",
")",
"-",
"n",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Not enough bytes to read in UnmarshalBinaryLengthPrefixed, want %v more bytes but only have %v\"",
",",
"u64",
",",
"len",
"(",
"bz",
")",
"-",
"n",
")",
"\n",
"}",
"else",
"if",
"u64",
"<",
"uint64",
"(",
"len",
"(",
"bz",
")",
"-",
"n",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Bytes left over in UnmarshalBinaryLengthPrefixed, should read %v more bytes but have %v\"",
",",
"u64",
",",
"len",
"(",
"bz",
")",
"-",
"n",
")",
"\n",
"}",
"\n",
"bz",
"=",
"bz",
"[",
"n",
":",
"]",
"\n",
"return",
"cdc",
".",
"UnmarshalBinaryBare",
"(",
"bz",
",",
"ptr",
")",
"\n",
"}"
] |
// Like UnmarshalBinaryBare, but will first decode the byte-length prefix.
// UnmarshalBinaryLengthPrefixed will panic if ptr is a nil-pointer.
// Returns an error if not all of bz is consumed.
|
[
"Like",
"UnmarshalBinaryBare",
"but",
"will",
"first",
"decode",
"the",
"byte",
"-",
"length",
"prefix",
".",
"UnmarshalBinaryLengthPrefixed",
"will",
"panic",
"if",
"ptr",
"is",
"a",
"nil",
"-",
"pointer",
".",
"Returns",
"an",
"error",
"if",
"not",
"all",
"of",
"bz",
"is",
"consumed",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L233-L254
|
test
|
tendermint/go-amino
|
amino.go
|
UnmarshalBinaryBare
|
func (cdc *Codec) UnmarshalBinaryBare(bz []byte, ptr interface{}) error {
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
panic("Unmarshal expects a pointer")
}
rv = rv.Elem()
rt := rv.Type()
info, err := cdc.getTypeInfo_wlock(rt)
if err != nil {
return err
}
// If registered concrete, consume and verify prefix bytes.
if info.Registered {
pb := info.Prefix.Bytes()
if len(bz) < 4 {
return fmt.Errorf("UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X", pb, bz)
} else if !bytes.Equal(bz[:4], pb) {
return fmt.Errorf("UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X...", pb, bz[:4])
}
bz = bz[4:]
}
// Decode contents into rv.
n, err := cdc.decodeReflectBinary(bz, info, rv, FieldOptions{BinFieldNum: 1}, true)
if err != nil {
return fmt.Errorf("unmarshal to %v failed after %d bytes (%v): %X", info.Type, n, err, bz)
}
if n != len(bz) {
return fmt.Errorf("unmarshal to %v didn't read all bytes. Expected to read %v, only read %v: %X", info.Type, len(bz), n, bz)
}
return nil
}
|
go
|
func (cdc *Codec) UnmarshalBinaryBare(bz []byte, ptr interface{}) error {
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
panic("Unmarshal expects a pointer")
}
rv = rv.Elem()
rt := rv.Type()
info, err := cdc.getTypeInfo_wlock(rt)
if err != nil {
return err
}
// If registered concrete, consume and verify prefix bytes.
if info.Registered {
pb := info.Prefix.Bytes()
if len(bz) < 4 {
return fmt.Errorf("UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X", pb, bz)
} else if !bytes.Equal(bz[:4], pb) {
return fmt.Errorf("UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X...", pb, bz[:4])
}
bz = bz[4:]
}
// Decode contents into rv.
n, err := cdc.decodeReflectBinary(bz, info, rv, FieldOptions{BinFieldNum: 1}, true)
if err != nil {
return fmt.Errorf("unmarshal to %v failed after %d bytes (%v): %X", info.Type, n, err, bz)
}
if n != len(bz) {
return fmt.Errorf("unmarshal to %v didn't read all bytes. Expected to read %v, only read %v: %X", info.Type, len(bz), n, bz)
}
return nil
}
|
[
"func",
"(",
"cdc",
"*",
"Codec",
")",
"UnmarshalBinaryBare",
"(",
"bz",
"[",
"]",
"byte",
",",
"ptr",
"interface",
"{",
"}",
")",
"error",
"{",
"rv",
":=",
"reflect",
".",
"ValueOf",
"(",
"ptr",
")",
"\n",
"if",
"rv",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"panic",
"(",
"\"Unmarshal expects a pointer\"",
")",
"\n",
"}",
"\n",
"rv",
"=",
"rv",
".",
"Elem",
"(",
")",
"\n",
"rt",
":=",
"rv",
".",
"Type",
"(",
")",
"\n",
"info",
",",
"err",
":=",
"cdc",
".",
"getTypeInfo_wlock",
"(",
"rt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"info",
".",
"Registered",
"{",
"pb",
":=",
"info",
".",
"Prefix",
".",
"Bytes",
"(",
")",
"\n",
"if",
"len",
"(",
"bz",
")",
"<",
"4",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X\"",
",",
"pb",
",",
"bz",
")",
"\n",
"}",
"else",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"bz",
"[",
":",
"4",
"]",
",",
"pb",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X...\"",
",",
"pb",
",",
"bz",
"[",
":",
"4",
"]",
")",
"\n",
"}",
"\n",
"bz",
"=",
"bz",
"[",
"4",
":",
"]",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"cdc",
".",
"decodeReflectBinary",
"(",
"bz",
",",
"info",
",",
"rv",
",",
"FieldOptions",
"{",
"BinFieldNum",
":",
"1",
"}",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unmarshal to %v failed after %d bytes (%v): %X\"",
",",
"info",
".",
"Type",
",",
"n",
",",
"err",
",",
"bz",
")",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"len",
"(",
"bz",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unmarshal to %v didn't read all bytes. Expected to read %v, only read %v: %X\"",
",",
"info",
".",
"Type",
",",
"len",
"(",
"bz",
")",
",",
"n",
",",
"bz",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalBinaryBare will panic if ptr is a nil-pointer.
|
[
"UnmarshalBinaryBare",
"will",
"panic",
"if",
"ptr",
"is",
"a",
"nil",
"-",
"pointer",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L321-L352
|
test
|
tendermint/go-amino
|
amino.go
|
MustMarshalJSON
|
func (cdc *Codec) MustMarshalJSON(o interface{}) []byte {
bz, err := cdc.MarshalJSON(o)
if err != nil {
panic(err)
}
return bz
}
|
go
|
func (cdc *Codec) MustMarshalJSON(o interface{}) []byte {
bz, err := cdc.MarshalJSON(o)
if err != nil {
panic(err)
}
return bz
}
|
[
"func",
"(",
"cdc",
"*",
"Codec",
")",
"MustMarshalJSON",
"(",
"o",
"interface",
"{",
"}",
")",
"[",
"]",
"byte",
"{",
"bz",
",",
"err",
":=",
"cdc",
".",
"MarshalJSON",
"(",
"o",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"bz",
"\n",
"}"
] |
// MustMarshalJSON panics if an error occurs. Besides tha behaves exactly like MarshalJSON.
|
[
"MustMarshalJSON",
"panics",
"if",
"an",
"error",
"occurs",
".",
"Besides",
"tha",
"behaves",
"exactly",
"like",
"MarshalJSON",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L403-L409
|
test
|
tendermint/go-amino
|
amino.go
|
MustUnmarshalJSON
|
func (cdc *Codec) MustUnmarshalJSON(bz []byte, ptr interface{}) {
if err := cdc.UnmarshalJSON(bz, ptr); err != nil {
panic(err)
}
}
|
go
|
func (cdc *Codec) MustUnmarshalJSON(bz []byte, ptr interface{}) {
if err := cdc.UnmarshalJSON(bz, ptr); err != nil {
panic(err)
}
}
|
[
"func",
"(",
"cdc",
"*",
"Codec",
")",
"MustUnmarshalJSON",
"(",
"bz",
"[",
"]",
"byte",
",",
"ptr",
"interface",
"{",
"}",
")",
"{",
"if",
"err",
":=",
"cdc",
".",
"UnmarshalJSON",
"(",
"bz",
",",
"ptr",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// MustUnmarshalJSON panics if an error occurs. Besides tha behaves exactly like UnmarshalJSON.
|
[
"MustUnmarshalJSON",
"panics",
"if",
"an",
"error",
"occurs",
".",
"Besides",
"tha",
"behaves",
"exactly",
"like",
"UnmarshalJSON",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L443-L447
|
test
|
tendermint/go-amino
|
amino.go
|
MarshalJSONIndent
|
func (cdc *Codec) MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) {
bz, err := cdc.MarshalJSON(o)
if err != nil {
return nil, err
}
var out bytes.Buffer
err = json.Indent(&out, bz, prefix, indent)
if err != nil {
return nil, err
}
return out.Bytes(), nil
}
|
go
|
func (cdc *Codec) MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) {
bz, err := cdc.MarshalJSON(o)
if err != nil {
return nil, err
}
var out bytes.Buffer
err = json.Indent(&out, bz, prefix, indent)
if err != nil {
return nil, err
}
return out.Bytes(), nil
}
|
[
"func",
"(",
"cdc",
"*",
"Codec",
")",
"MarshalJSONIndent",
"(",
"o",
"interface",
"{",
"}",
",",
"prefix",
",",
"indent",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"bz",
",",
"err",
":=",
"cdc",
".",
"MarshalJSON",
"(",
"o",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"out",
"bytes",
".",
"Buffer",
"\n",
"err",
"=",
"json",
".",
"Indent",
"(",
"&",
"out",
",",
"bz",
",",
"prefix",
",",
"indent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"out",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// MarshalJSONIndent calls json.Indent on the output of cdc.MarshalJSON
// using the given prefix and indent string.
|
[
"MarshalJSONIndent",
"calls",
"json",
".",
"Indent",
"on",
"the",
"output",
"of",
"cdc",
".",
"MarshalJSON",
"using",
"the",
"given",
"prefix",
"and",
"indent",
"string",
"."
] |
dc14acf9ef15f85828bfbc561ed9dd9d2a284885
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L451-L462
|
test
|
reiver/go-telnet
|
data_reader.go
|
newDataReader
|
func newDataReader(r io.Reader) *internalDataReader {
buffered := bufio.NewReader(r)
reader := internalDataReader{
wrapped:r,
buffered:buffered,
}
return &reader
}
|
go
|
func newDataReader(r io.Reader) *internalDataReader {
buffered := bufio.NewReader(r)
reader := internalDataReader{
wrapped:r,
buffered:buffered,
}
return &reader
}
|
[
"func",
"newDataReader",
"(",
"r",
"io",
".",
"Reader",
")",
"*",
"internalDataReader",
"{",
"buffered",
":=",
"bufio",
".",
"NewReader",
"(",
"r",
")",
"\n",
"reader",
":=",
"internalDataReader",
"{",
"wrapped",
":",
"r",
",",
"buffered",
":",
"buffered",
",",
"}",
"\n",
"return",
"&",
"reader",
"\n",
"}"
] |
// newDataReader creates a new DataReader reading from 'r'.
|
[
"newDataReader",
"creates",
"a",
"new",
"DataReader",
"reading",
"from",
"r",
"."
] |
9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c
|
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/data_reader.go#L65-L74
|
test
|
reiver/go-telnet
|
data_reader.go
|
Read
|
func (r *internalDataReader) Read(data []byte) (n int, err error) {
const IAC = 255
const SB = 250
const SE = 240
const WILL = 251
const WONT = 252
const DO = 253
const DONT = 254
p := data
for len(p) > 0 {
var b byte
b, err = r.buffered.ReadByte()
if nil != err {
return n, err
}
if IAC == b {
var peeked []byte
peeked, err = r.buffered.Peek(1)
if nil != err {
return n, err
}
switch peeked[0] {
case WILL, WONT, DO, DONT:
_, err = r.buffered.Discard(2)
if nil != err {
return n, err
}
case IAC:
p[0] = IAC
n++
p = p[1:]
_, err = r.buffered.Discard(1)
if nil != err {
return n, err
}
case SB:
for {
var b2 byte
b2, err = r.buffered.ReadByte()
if nil != err {
return n, err
}
if IAC == b2 {
peeked, err = r.buffered.Peek(1)
if nil != err {
return n, err
}
if IAC == peeked[0] {
_, err = r.buffered.Discard(1)
if nil != err {
return n, err
}
}
if SE == peeked[0] {
_, err = r.buffered.Discard(1)
if nil != err {
return n, err
}
break
}
}
}
case SE:
_, err = r.buffered.Discard(1)
if nil != err {
return n, err
}
default:
// If we get in here, this is not following the TELNET protocol.
//@TODO: Make a better error.
err = errCorrupted
return n, err
}
} else {
p[0] = b
n++
p = p[1:]
}
}
return n, nil
}
|
go
|
func (r *internalDataReader) Read(data []byte) (n int, err error) {
const IAC = 255
const SB = 250
const SE = 240
const WILL = 251
const WONT = 252
const DO = 253
const DONT = 254
p := data
for len(p) > 0 {
var b byte
b, err = r.buffered.ReadByte()
if nil != err {
return n, err
}
if IAC == b {
var peeked []byte
peeked, err = r.buffered.Peek(1)
if nil != err {
return n, err
}
switch peeked[0] {
case WILL, WONT, DO, DONT:
_, err = r.buffered.Discard(2)
if nil != err {
return n, err
}
case IAC:
p[0] = IAC
n++
p = p[1:]
_, err = r.buffered.Discard(1)
if nil != err {
return n, err
}
case SB:
for {
var b2 byte
b2, err = r.buffered.ReadByte()
if nil != err {
return n, err
}
if IAC == b2 {
peeked, err = r.buffered.Peek(1)
if nil != err {
return n, err
}
if IAC == peeked[0] {
_, err = r.buffered.Discard(1)
if nil != err {
return n, err
}
}
if SE == peeked[0] {
_, err = r.buffered.Discard(1)
if nil != err {
return n, err
}
break
}
}
}
case SE:
_, err = r.buffered.Discard(1)
if nil != err {
return n, err
}
default:
// If we get in here, this is not following the TELNET protocol.
//@TODO: Make a better error.
err = errCorrupted
return n, err
}
} else {
p[0] = b
n++
p = p[1:]
}
}
return n, nil
}
|
[
"func",
"(",
"r",
"*",
"internalDataReader",
")",
"Read",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"const",
"IAC",
"=",
"255",
"\n",
"const",
"SB",
"=",
"250",
"\n",
"const",
"SE",
"=",
"240",
"\n",
"const",
"WILL",
"=",
"251",
"\n",
"const",
"WONT",
"=",
"252",
"\n",
"const",
"DO",
"=",
"253",
"\n",
"const",
"DONT",
"=",
"254",
"\n",
"p",
":=",
"data",
"\n",
"for",
"len",
"(",
"p",
")",
">",
"0",
"{",
"var",
"b",
"byte",
"\n",
"b",
",",
"err",
"=",
"r",
".",
"buffered",
".",
"ReadByte",
"(",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"if",
"IAC",
"==",
"b",
"{",
"var",
"peeked",
"[",
"]",
"byte",
"\n",
"peeked",
",",
"err",
"=",
"r",
".",
"buffered",
".",
"Peek",
"(",
"1",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"switch",
"peeked",
"[",
"0",
"]",
"{",
"case",
"WILL",
",",
"WONT",
",",
"DO",
",",
"DONT",
":",
"_",
",",
"err",
"=",
"r",
".",
"buffered",
".",
"Discard",
"(",
"2",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"case",
"IAC",
":",
"p",
"[",
"0",
"]",
"=",
"IAC",
"\n",
"n",
"++",
"\n",
"p",
"=",
"p",
"[",
"1",
":",
"]",
"\n",
"_",
",",
"err",
"=",
"r",
".",
"buffered",
".",
"Discard",
"(",
"1",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"case",
"SB",
":",
"for",
"{",
"var",
"b2",
"byte",
"\n",
"b2",
",",
"err",
"=",
"r",
".",
"buffered",
".",
"ReadByte",
"(",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"if",
"IAC",
"==",
"b2",
"{",
"peeked",
",",
"err",
"=",
"r",
".",
"buffered",
".",
"Peek",
"(",
"1",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"if",
"IAC",
"==",
"peeked",
"[",
"0",
"]",
"{",
"_",
",",
"err",
"=",
"r",
".",
"buffered",
".",
"Discard",
"(",
"1",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"SE",
"==",
"peeked",
"[",
"0",
"]",
"{",
"_",
",",
"err",
"=",
"r",
".",
"buffered",
".",
"Discard",
"(",
"1",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"SE",
":",
"_",
",",
"err",
"=",
"r",
".",
"buffered",
".",
"Discard",
"(",
"1",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"default",
":",
"err",
"=",
"errCorrupted",
"\n",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"p",
"[",
"0",
"]",
"=",
"b",
"\n",
"n",
"++",
"\n",
"p",
"=",
"p",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] |
// Read reads the TELNET escaped data from the wrapped io.Reader, and "un-escapes" it into 'data'.
|
[
"Read",
"reads",
"the",
"TELNET",
"escaped",
"data",
"from",
"the",
"wrapped",
"io",
".",
"Reader",
"and",
"un",
"-",
"escapes",
"it",
"into",
"data",
"."
] |
9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c
|
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/data_reader.go#L78-L173
|
test
|
reiver/go-telnet
|
tls.go
|
ListenAndServeTLS
|
func (server *Server) ListenAndServeTLS(certFile string, keyFile string) error {
addr := server.Addr
if "" == addr {
addr = ":telnets"
}
listener, err := net.Listen("tcp", addr)
if nil != err {
return err
}
// Apparently have to make a copy of the TLS config this way, rather than by
// simple assignment, to prevent some unexported fields from being copied over.
//
// It would be nice if tls.Config had a method that would do this "safely".
// (I.e., what happens if in the future more exported fields are added to
// tls.Config?)
var tlsConfig *tls.Config = nil
if nil == server.TLSConfig {
tlsConfig = &tls.Config{}
} else {
tlsConfig = &tls.Config{
Rand: server.TLSConfig.Rand,
Time: server.TLSConfig.Time,
Certificates: server.TLSConfig.Certificates,
NameToCertificate: server.TLSConfig.NameToCertificate,
GetCertificate: server.TLSConfig.GetCertificate,
RootCAs: server.TLSConfig.RootCAs,
NextProtos: server.TLSConfig.NextProtos,
ServerName: server.TLSConfig.ServerName,
ClientAuth: server.TLSConfig.ClientAuth,
ClientCAs: server.TLSConfig.ClientCAs,
InsecureSkipVerify: server.TLSConfig.InsecureSkipVerify,
CipherSuites: server.TLSConfig.CipherSuites,
PreferServerCipherSuites: server.TLSConfig.PreferServerCipherSuites,
SessionTicketsDisabled: server.TLSConfig.SessionTicketsDisabled,
SessionTicketKey: server.TLSConfig.SessionTicketKey,
ClientSessionCache: server.TLSConfig.ClientSessionCache,
MinVersion: server.TLSConfig.MinVersion,
MaxVersion: server.TLSConfig.MaxVersion,
CurvePreferences: server.TLSConfig.CurvePreferences,
}
}
tlsConfigHasCertificate := len(tlsConfig.Certificates) > 0 || nil != tlsConfig.GetCertificate
if "" == certFile || "" == keyFile || !tlsConfigHasCertificate {
tlsConfig.Certificates = make([]tls.Certificate, 1)
var err error
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if nil != err {
return err
}
}
tlsListener := tls.NewListener(listener, tlsConfig)
return server.Serve(tlsListener)
}
|
go
|
func (server *Server) ListenAndServeTLS(certFile string, keyFile string) error {
addr := server.Addr
if "" == addr {
addr = ":telnets"
}
listener, err := net.Listen("tcp", addr)
if nil != err {
return err
}
// Apparently have to make a copy of the TLS config this way, rather than by
// simple assignment, to prevent some unexported fields from being copied over.
//
// It would be nice if tls.Config had a method that would do this "safely".
// (I.e., what happens if in the future more exported fields are added to
// tls.Config?)
var tlsConfig *tls.Config = nil
if nil == server.TLSConfig {
tlsConfig = &tls.Config{}
} else {
tlsConfig = &tls.Config{
Rand: server.TLSConfig.Rand,
Time: server.TLSConfig.Time,
Certificates: server.TLSConfig.Certificates,
NameToCertificate: server.TLSConfig.NameToCertificate,
GetCertificate: server.TLSConfig.GetCertificate,
RootCAs: server.TLSConfig.RootCAs,
NextProtos: server.TLSConfig.NextProtos,
ServerName: server.TLSConfig.ServerName,
ClientAuth: server.TLSConfig.ClientAuth,
ClientCAs: server.TLSConfig.ClientCAs,
InsecureSkipVerify: server.TLSConfig.InsecureSkipVerify,
CipherSuites: server.TLSConfig.CipherSuites,
PreferServerCipherSuites: server.TLSConfig.PreferServerCipherSuites,
SessionTicketsDisabled: server.TLSConfig.SessionTicketsDisabled,
SessionTicketKey: server.TLSConfig.SessionTicketKey,
ClientSessionCache: server.TLSConfig.ClientSessionCache,
MinVersion: server.TLSConfig.MinVersion,
MaxVersion: server.TLSConfig.MaxVersion,
CurvePreferences: server.TLSConfig.CurvePreferences,
}
}
tlsConfigHasCertificate := len(tlsConfig.Certificates) > 0 || nil != tlsConfig.GetCertificate
if "" == certFile || "" == keyFile || !tlsConfigHasCertificate {
tlsConfig.Certificates = make([]tls.Certificate, 1)
var err error
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if nil != err {
return err
}
}
tlsListener := tls.NewListener(listener, tlsConfig)
return server.Serve(tlsListener)
}
|
[
"func",
"(",
"server",
"*",
"Server",
")",
"ListenAndServeTLS",
"(",
"certFile",
"string",
",",
"keyFile",
"string",
")",
"error",
"{",
"addr",
":=",
"server",
".",
"Addr",
"\n",
"if",
"\"\"",
"==",
"addr",
"{",
"addr",
"=",
"\":telnets\"",
"\n",
"}",
"\n",
"listener",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"tcp\"",
",",
"addr",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"tlsConfig",
"*",
"tls",
".",
"Config",
"=",
"nil",
"\n",
"if",
"nil",
"==",
"server",
".",
"TLSConfig",
"{",
"tlsConfig",
"=",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n",
"}",
"else",
"{",
"tlsConfig",
"=",
"&",
"tls",
".",
"Config",
"{",
"Rand",
":",
"server",
".",
"TLSConfig",
".",
"Rand",
",",
"Time",
":",
"server",
".",
"TLSConfig",
".",
"Time",
",",
"Certificates",
":",
"server",
".",
"TLSConfig",
".",
"Certificates",
",",
"NameToCertificate",
":",
"server",
".",
"TLSConfig",
".",
"NameToCertificate",
",",
"GetCertificate",
":",
"server",
".",
"TLSConfig",
".",
"GetCertificate",
",",
"RootCAs",
":",
"server",
".",
"TLSConfig",
".",
"RootCAs",
",",
"NextProtos",
":",
"server",
".",
"TLSConfig",
".",
"NextProtos",
",",
"ServerName",
":",
"server",
".",
"TLSConfig",
".",
"ServerName",
",",
"ClientAuth",
":",
"server",
".",
"TLSConfig",
".",
"ClientAuth",
",",
"ClientCAs",
":",
"server",
".",
"TLSConfig",
".",
"ClientCAs",
",",
"InsecureSkipVerify",
":",
"server",
".",
"TLSConfig",
".",
"InsecureSkipVerify",
",",
"CipherSuites",
":",
"server",
".",
"TLSConfig",
".",
"CipherSuites",
",",
"PreferServerCipherSuites",
":",
"server",
".",
"TLSConfig",
".",
"PreferServerCipherSuites",
",",
"SessionTicketsDisabled",
":",
"server",
".",
"TLSConfig",
".",
"SessionTicketsDisabled",
",",
"SessionTicketKey",
":",
"server",
".",
"TLSConfig",
".",
"SessionTicketKey",
",",
"ClientSessionCache",
":",
"server",
".",
"TLSConfig",
".",
"ClientSessionCache",
",",
"MinVersion",
":",
"server",
".",
"TLSConfig",
".",
"MinVersion",
",",
"MaxVersion",
":",
"server",
".",
"TLSConfig",
".",
"MaxVersion",
",",
"CurvePreferences",
":",
"server",
".",
"TLSConfig",
".",
"CurvePreferences",
",",
"}",
"\n",
"}",
"\n",
"tlsConfigHasCertificate",
":=",
"len",
"(",
"tlsConfig",
".",
"Certificates",
")",
">",
"0",
"||",
"nil",
"!=",
"tlsConfig",
".",
"GetCertificate",
"\n",
"if",
"\"\"",
"==",
"certFile",
"||",
"\"\"",
"==",
"keyFile",
"||",
"!",
"tlsConfigHasCertificate",
"{",
"tlsConfig",
".",
"Certificates",
"=",
"make",
"(",
"[",
"]",
"tls",
".",
"Certificate",
",",
"1",
")",
"\n",
"var",
"err",
"error",
"\n",
"tlsConfig",
".",
"Certificates",
"[",
"0",
"]",
",",
"err",
"=",
"tls",
".",
"LoadX509KeyPair",
"(",
"certFile",
",",
"keyFile",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"tlsListener",
":=",
"tls",
".",
"NewListener",
"(",
"listener",
",",
"tlsConfig",
")",
"\n",
"return",
"server",
".",
"Serve",
"(",
"tlsListener",
")",
"\n",
"}"
] |
// ListenAndServeTLS acts identically to ListenAndServe, except that it
// uses the TELNET protocol over TLS.
//
// From a TELNET protocol point-of-view, it allows for 'secured telnet', also known as TELNETS,
// which by default listens to port 992.
|
[
"ListenAndServeTLS",
"acts",
"identically",
"to",
"ListenAndServe",
"except",
"that",
"it",
"uses",
"the",
"TELNET",
"protocol",
"over",
"TLS",
".",
"From",
"a",
"TELNET",
"protocol",
"point",
"-",
"of",
"-",
"view",
"it",
"allows",
"for",
"secured",
"telnet",
"also",
"known",
"as",
"TELNETS",
"which",
"by",
"default",
"listens",
"to",
"port",
"992",
"."
] |
9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c
|
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/tls.go#L49-L113
|
test
|
reiver/go-telnet
|
telsh/producer.go
|
Produce
|
func (fn ProducerFunc) Produce(ctx telnet.Context, name string, args ...string) Handler {
return fn(ctx, name, args...)
}
|
go
|
func (fn ProducerFunc) Produce(ctx telnet.Context, name string, args ...string) Handler {
return fn(ctx, name, args...)
}
|
[
"func",
"(",
"fn",
"ProducerFunc",
")",
"Produce",
"(",
"ctx",
"telnet",
".",
"Context",
",",
"name",
"string",
",",
"args",
"...",
"string",
")",
"Handler",
"{",
"return",
"fn",
"(",
"ctx",
",",
"name",
",",
"args",
"...",
")",
"\n",
"}"
] |
// Produce makes ProducerFunc fit the Producer interface.
|
[
"Produce",
"makes",
"ProducerFunc",
"fit",
"the",
"Producer",
"interface",
"."
] |
9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c
|
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/telsh/producer.go#L34-L36
|
test
|
reiver/go-telnet
|
telsh/handler.go
|
PromoteHandlerFunc
|
func PromoteHandlerFunc(fn HandlerFunc, args ...string) Handler {
stdin, stdinPipe := io.Pipe()
stdoutPipe, stdout := io.Pipe()
stderrPipe, stderr := io.Pipe()
argsCopy := make([]string, len(args))
for i, datum := range args {
argsCopy[i] = datum
}
handler := internalPromotedHandlerFunc{
err:nil,
fn:fn,
stdin:stdin,
stdout:stdout,
stderr:stderr,
stdinPipe:stdinPipe,
stdoutPipe:stdoutPipe,
stderrPipe:stderrPipe,
args:argsCopy,
}
return &handler
}
|
go
|
func PromoteHandlerFunc(fn HandlerFunc, args ...string) Handler {
stdin, stdinPipe := io.Pipe()
stdoutPipe, stdout := io.Pipe()
stderrPipe, stderr := io.Pipe()
argsCopy := make([]string, len(args))
for i, datum := range args {
argsCopy[i] = datum
}
handler := internalPromotedHandlerFunc{
err:nil,
fn:fn,
stdin:stdin,
stdout:stdout,
stderr:stderr,
stdinPipe:stdinPipe,
stdoutPipe:stdoutPipe,
stderrPipe:stderrPipe,
args:argsCopy,
}
return &handler
}
|
[
"func",
"PromoteHandlerFunc",
"(",
"fn",
"HandlerFunc",
",",
"args",
"...",
"string",
")",
"Handler",
"{",
"stdin",
",",
"stdinPipe",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"stdoutPipe",
",",
"stdout",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"stderrPipe",
",",
"stderr",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"argsCopy",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"args",
")",
")",
"\n",
"for",
"i",
",",
"datum",
":=",
"range",
"args",
"{",
"argsCopy",
"[",
"i",
"]",
"=",
"datum",
"\n",
"}",
"\n",
"handler",
":=",
"internalPromotedHandlerFunc",
"{",
"err",
":",
"nil",
",",
"fn",
":",
"fn",
",",
"stdin",
":",
"stdin",
",",
"stdout",
":",
"stdout",
",",
"stderr",
":",
"stderr",
",",
"stdinPipe",
":",
"stdinPipe",
",",
"stdoutPipe",
":",
"stdoutPipe",
",",
"stderrPipe",
":",
"stderrPipe",
",",
"args",
":",
"argsCopy",
",",
"}",
"\n",
"return",
"&",
"handler",
"\n",
"}"
] |
// PromoteHandlerFunc turns a HandlerFunc into a Handler.
|
[
"PromoteHandlerFunc",
"turns",
"a",
"HandlerFunc",
"into",
"a",
"Handler",
"."
] |
9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c
|
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/telsh/handler.go#L74-L101
|
test
|
reiver/go-telnet
|
server.go
|
Serve
|
func Serve(listener net.Listener, handler Handler) error {
server := &Server{Handler: handler}
return server.Serve(listener)
}
|
go
|
func Serve(listener net.Listener, handler Handler) error {
server := &Server{Handler: handler}
return server.Serve(listener)
}
|
[
"func",
"Serve",
"(",
"listener",
"net",
".",
"Listener",
",",
"handler",
"Handler",
")",
"error",
"{",
"server",
":=",
"&",
"Server",
"{",
"Handler",
":",
"handler",
"}",
"\n",
"return",
"server",
".",
"Serve",
"(",
"listener",
")",
"\n",
"}"
] |
// Serve accepts an incoming TELNET or TELNETS client connection on the net.Listener `listener`.
|
[
"Serve",
"accepts",
"an",
"incoming",
"TELNET",
"or",
"TELNETS",
"client",
"connection",
"on",
"the",
"net",
".",
"Listener",
"listener",
"."
] |
9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c
|
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/server.go#L39-L43
|
test
|
reiver/go-telnet
|
server.go
|
Serve
|
func (server *Server) Serve(listener net.Listener) error {
defer listener.Close()
logger := server.logger()
handler := server.Handler
if nil == handler {
//@TODO: Should this be a "ShellHandler" instead, that gives a shell-like experience by default
// If this is changd, then need to change the comment in the "type Server struct" definition.
logger.Debug("Defaulted handler to EchoHandler.")
handler = EchoHandler
}
for {
// Wait for a new TELNET client connection.
logger.Debugf("Listening at %q.", listener.Addr())
conn, err := listener.Accept()
if err != nil {
//@TODO: Could try to recover from certain kinds of errors. Maybe waiting a while before trying again.
return err
}
logger.Debugf("Received new connection from %q.", conn.RemoteAddr())
// Handle the new TELNET client connection by spawning
// a new goroutine.
go server.handle(conn, handler)
logger.Debugf("Spawned handler to handle connection from %q.", conn.RemoteAddr())
}
}
|
go
|
func (server *Server) Serve(listener net.Listener) error {
defer listener.Close()
logger := server.logger()
handler := server.Handler
if nil == handler {
//@TODO: Should this be a "ShellHandler" instead, that gives a shell-like experience by default
// If this is changd, then need to change the comment in the "type Server struct" definition.
logger.Debug("Defaulted handler to EchoHandler.")
handler = EchoHandler
}
for {
// Wait for a new TELNET client connection.
logger.Debugf("Listening at %q.", listener.Addr())
conn, err := listener.Accept()
if err != nil {
//@TODO: Could try to recover from certain kinds of errors. Maybe waiting a while before trying again.
return err
}
logger.Debugf("Received new connection from %q.", conn.RemoteAddr())
// Handle the new TELNET client connection by spawning
// a new goroutine.
go server.handle(conn, handler)
logger.Debugf("Spawned handler to handle connection from %q.", conn.RemoteAddr())
}
}
|
[
"func",
"(",
"server",
"*",
"Server",
")",
"Serve",
"(",
"listener",
"net",
".",
"Listener",
")",
"error",
"{",
"defer",
"listener",
".",
"Close",
"(",
")",
"\n",
"logger",
":=",
"server",
".",
"logger",
"(",
")",
"\n",
"handler",
":=",
"server",
".",
"Handler",
"\n",
"if",
"nil",
"==",
"handler",
"{",
"logger",
".",
"Debug",
"(",
"\"Defaulted handler to EchoHandler.\"",
")",
"\n",
"handler",
"=",
"EchoHandler",
"\n",
"}",
"\n",
"for",
"{",
"logger",
".",
"Debugf",
"(",
"\"Listening at %q.\"",
",",
"listener",
".",
"Addr",
"(",
")",
")",
"\n",
"conn",
",",
"err",
":=",
"listener",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"Received new connection from %q.\"",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
")",
"\n",
"go",
"server",
".",
"handle",
"(",
"conn",
",",
"handler",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"Spawned handler to handle connection from %q.\"",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Serve accepts an incoming TELNET client connection on the net.Listener `listener`.
|
[
"Serve",
"accepts",
"an",
"incoming",
"TELNET",
"client",
"connection",
"on",
"the",
"net",
".",
"Listener",
"listener",
"."
] |
9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c
|
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/server.go#L125-L157
|
test
|
alexflint/go-arg
|
usage.go
|
Fail
|
func (p *Parser) Fail(msg string) {
p.WriteUsage(os.Stderr)
fmt.Fprintln(os.Stderr, "error:", msg)
os.Exit(-1)
}
|
go
|
func (p *Parser) Fail(msg string) {
p.WriteUsage(os.Stderr)
fmt.Fprintln(os.Stderr, "error:", msg)
os.Exit(-1)
}
|
[
"func",
"(",
"p",
"*",
"Parser",
")",
"Fail",
"(",
"msg",
"string",
")",
"{",
"p",
".",
"WriteUsage",
"(",
"os",
".",
"Stderr",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"os",
".",
"Stderr",
",",
"\"error:\"",
",",
"msg",
")",
"\n",
"os",
".",
"Exit",
"(",
"-",
"1",
")",
"\n",
"}"
] |
// Fail prints usage information to stderr and exits with non-zero status
|
[
"Fail",
"prints",
"usage",
"information",
"to",
"stderr",
"and",
"exits",
"with",
"non",
"-",
"zero",
"status"
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/usage.go#L16-L20
|
test
|
alexflint/go-arg
|
usage.go
|
WriteUsage
|
func (p *Parser) WriteUsage(w io.Writer) {
var positionals, options []*spec
for _, spec := range p.specs {
if spec.positional {
positionals = append(positionals, spec)
} else {
options = append(options, spec)
}
}
if p.version != "" {
fmt.Fprintln(w, p.version)
}
fmt.Fprintf(w, "Usage: %s", p.config.Program)
// write the option component of the usage message
for _, spec := range options {
// prefix with a space
fmt.Fprint(w, " ")
if !spec.required {
fmt.Fprint(w, "[")
}
fmt.Fprint(w, synopsis(spec, "--"+spec.long))
if !spec.required {
fmt.Fprint(w, "]")
}
}
// write the positional component of the usage message
for _, spec := range positionals {
// prefix with a space
fmt.Fprint(w, " ")
up := strings.ToUpper(spec.long)
if spec.multiple {
if !spec.required {
fmt.Fprint(w, "[")
}
fmt.Fprintf(w, "%s [%s ...]", up, up)
if !spec.required {
fmt.Fprint(w, "]")
}
} else {
fmt.Fprint(w, up)
}
}
fmt.Fprint(w, "\n")
}
|
go
|
func (p *Parser) WriteUsage(w io.Writer) {
var positionals, options []*spec
for _, spec := range p.specs {
if spec.positional {
positionals = append(positionals, spec)
} else {
options = append(options, spec)
}
}
if p.version != "" {
fmt.Fprintln(w, p.version)
}
fmt.Fprintf(w, "Usage: %s", p.config.Program)
// write the option component of the usage message
for _, spec := range options {
// prefix with a space
fmt.Fprint(w, " ")
if !spec.required {
fmt.Fprint(w, "[")
}
fmt.Fprint(w, synopsis(spec, "--"+spec.long))
if !spec.required {
fmt.Fprint(w, "]")
}
}
// write the positional component of the usage message
for _, spec := range positionals {
// prefix with a space
fmt.Fprint(w, " ")
up := strings.ToUpper(spec.long)
if spec.multiple {
if !spec.required {
fmt.Fprint(w, "[")
}
fmt.Fprintf(w, "%s [%s ...]", up, up)
if !spec.required {
fmt.Fprint(w, "]")
}
} else {
fmt.Fprint(w, up)
}
}
fmt.Fprint(w, "\n")
}
|
[
"func",
"(",
"p",
"*",
"Parser",
")",
"WriteUsage",
"(",
"w",
"io",
".",
"Writer",
")",
"{",
"var",
"positionals",
",",
"options",
"[",
"]",
"*",
"spec",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"p",
".",
"specs",
"{",
"if",
"spec",
".",
"positional",
"{",
"positionals",
"=",
"append",
"(",
"positionals",
",",
"spec",
")",
"\n",
"}",
"else",
"{",
"options",
"=",
"append",
"(",
"options",
",",
"spec",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"p",
".",
"version",
"!=",
"\"\"",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"p",
".",
"version",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"Usage: %s\"",
",",
"p",
".",
"config",
".",
"Program",
")",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"options",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\" \"",
")",
"\n",
"if",
"!",
"spec",
".",
"required",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"[\"",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"synopsis",
"(",
"spec",
",",
"\"--\"",
"+",
"spec",
".",
"long",
")",
")",
"\n",
"if",
"!",
"spec",
".",
"required",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"]\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"positionals",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\" \"",
")",
"\n",
"up",
":=",
"strings",
".",
"ToUpper",
"(",
"spec",
".",
"long",
")",
"\n",
"if",
"spec",
".",
"multiple",
"{",
"if",
"!",
"spec",
".",
"required",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"[\"",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"%s [%s ...]\"",
",",
"up",
",",
"up",
")",
"\n",
"if",
"!",
"spec",
".",
"required",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"]\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"up",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"\\n\"",
")",
"\n",
"}"
] |
// WriteUsage writes usage information to the given writer
|
[
"WriteUsage",
"writes",
"usage",
"information",
"to",
"the",
"given",
"writer"
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/usage.go#L23-L70
|
test
|
alexflint/go-arg
|
usage.go
|
WriteHelp
|
func (p *Parser) WriteHelp(w io.Writer) {
var positionals, options []*spec
for _, spec := range p.specs {
if spec.positional {
positionals = append(positionals, spec)
} else {
options = append(options, spec)
}
}
if p.description != "" {
fmt.Fprintln(w, p.description)
}
p.WriteUsage(w)
// write the list of positionals
if len(positionals) > 0 {
fmt.Fprint(w, "\nPositional arguments:\n")
for _, spec := range positionals {
left := " " + strings.ToUpper(spec.long)
fmt.Fprint(w, left)
if spec.help != "" {
if len(left)+2 < colWidth {
fmt.Fprint(w, strings.Repeat(" ", colWidth-len(left)))
} else {
fmt.Fprint(w, "\n"+strings.Repeat(" ", colWidth))
}
fmt.Fprint(w, spec.help)
}
fmt.Fprint(w, "\n")
}
}
// write the list of options
fmt.Fprint(w, "\nOptions:\n")
for _, spec := range options {
printOption(w, spec)
}
// write the list of built in options
printOption(w, &spec{boolean: true, long: "help", short: "h", help: "display this help and exit"})
if p.version != "" {
printOption(w, &spec{boolean: true, long: "version", help: "display version and exit"})
}
}
|
go
|
func (p *Parser) WriteHelp(w io.Writer) {
var positionals, options []*spec
for _, spec := range p.specs {
if spec.positional {
positionals = append(positionals, spec)
} else {
options = append(options, spec)
}
}
if p.description != "" {
fmt.Fprintln(w, p.description)
}
p.WriteUsage(w)
// write the list of positionals
if len(positionals) > 0 {
fmt.Fprint(w, "\nPositional arguments:\n")
for _, spec := range positionals {
left := " " + strings.ToUpper(spec.long)
fmt.Fprint(w, left)
if spec.help != "" {
if len(left)+2 < colWidth {
fmt.Fprint(w, strings.Repeat(" ", colWidth-len(left)))
} else {
fmt.Fprint(w, "\n"+strings.Repeat(" ", colWidth))
}
fmt.Fprint(w, spec.help)
}
fmt.Fprint(w, "\n")
}
}
// write the list of options
fmt.Fprint(w, "\nOptions:\n")
for _, spec := range options {
printOption(w, spec)
}
// write the list of built in options
printOption(w, &spec{boolean: true, long: "help", short: "h", help: "display this help and exit"})
if p.version != "" {
printOption(w, &spec{boolean: true, long: "version", help: "display version and exit"})
}
}
|
[
"func",
"(",
"p",
"*",
"Parser",
")",
"WriteHelp",
"(",
"w",
"io",
".",
"Writer",
")",
"{",
"var",
"positionals",
",",
"options",
"[",
"]",
"*",
"spec",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"p",
".",
"specs",
"{",
"if",
"spec",
".",
"positional",
"{",
"positionals",
"=",
"append",
"(",
"positionals",
",",
"spec",
")",
"\n",
"}",
"else",
"{",
"options",
"=",
"append",
"(",
"options",
",",
"spec",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"p",
".",
"description",
"!=",
"\"\"",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"p",
".",
"description",
")",
"\n",
"}",
"\n",
"p",
".",
"WriteUsage",
"(",
"w",
")",
"\n",
"if",
"len",
"(",
"positionals",
")",
">",
"0",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"\\nPositional arguments:\\n\"",
")",
"\n",
"\\n",
"\n",
"}",
"\n",
"\\n",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"positionals",
"{",
"left",
":=",
"\" \"",
"+",
"strings",
".",
"ToUpper",
"(",
"spec",
".",
"long",
")",
"\n",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"left",
")",
"\n",
"if",
"spec",
".",
"help",
"!=",
"\"\"",
"{",
"if",
"len",
"(",
"left",
")",
"+",
"2",
"<",
"colWidth",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"strings",
".",
"Repeat",
"(",
"\" \"",
",",
"colWidth",
"-",
"len",
"(",
"left",
")",
")",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"\\n\"",
"+",
"\\n",
")",
"\n",
"}",
"\n",
"strings",
".",
"Repeat",
"(",
"\" \"",
",",
"colWidth",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"spec",
".",
"help",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"\\n\"",
")",
"\n",
"\\n",
"\n",
"}"
] |
// WriteHelp writes the usage string followed by the full help string for each option
|
[
"WriteHelp",
"writes",
"the",
"usage",
"string",
"followed",
"by",
"the",
"full",
"help",
"string",
"for",
"each",
"option"
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/usage.go#L73-L117
|
test
|
alexflint/go-arg
|
parse.go
|
MustParse
|
func MustParse(dest ...interface{}) *Parser {
p, err := NewParser(Config{}, dest...)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
err = p.Parse(flags())
if err == ErrHelp {
p.WriteHelp(os.Stdout)
os.Exit(0)
}
if err == ErrVersion {
fmt.Println(p.version)
os.Exit(0)
}
if err != nil {
p.Fail(err.Error())
}
return p
}
|
go
|
func MustParse(dest ...interface{}) *Parser {
p, err := NewParser(Config{}, dest...)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
err = p.Parse(flags())
if err == ErrHelp {
p.WriteHelp(os.Stdout)
os.Exit(0)
}
if err == ErrVersion {
fmt.Println(p.version)
os.Exit(0)
}
if err != nil {
p.Fail(err.Error())
}
return p
}
|
[
"func",
"MustParse",
"(",
"dest",
"...",
"interface",
"{",
"}",
")",
"*",
"Parser",
"{",
"p",
",",
"err",
":=",
"NewParser",
"(",
"Config",
"{",
"}",
",",
"dest",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"err",
")",
"\n",
"os",
".",
"Exit",
"(",
"-",
"1",
")",
"\n",
"}",
"\n",
"err",
"=",
"p",
".",
"Parse",
"(",
"flags",
"(",
")",
")",
"\n",
"if",
"err",
"==",
"ErrHelp",
"{",
"p",
".",
"WriteHelp",
"(",
"os",
".",
"Stdout",
")",
"\n",
"os",
".",
"Exit",
"(",
"0",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"ErrVersion",
"{",
"fmt",
".",
"Println",
"(",
"p",
".",
"version",
")",
"\n",
"os",
".",
"Exit",
"(",
"0",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"Fail",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] |
// MustParse processes command line arguments and exits upon failure
|
[
"MustParse",
"processes",
"command",
"line",
"arguments",
"and",
"exits",
"upon",
"failure"
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L37-L56
|
test
|
alexflint/go-arg
|
parse.go
|
Parse
|
func Parse(dest ...interface{}) error {
p, err := NewParser(Config{}, dest...)
if err != nil {
return err
}
return p.Parse(flags())
}
|
go
|
func Parse(dest ...interface{}) error {
p, err := NewParser(Config{}, dest...)
if err != nil {
return err
}
return p.Parse(flags())
}
|
[
"func",
"Parse",
"(",
"dest",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"p",
",",
"err",
":=",
"NewParser",
"(",
"Config",
"{",
"}",
",",
"dest",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"p",
".",
"Parse",
"(",
"flags",
"(",
")",
")",
"\n",
"}"
] |
// Parse processes command line arguments and stores them in dest
|
[
"Parse",
"processes",
"command",
"line",
"arguments",
"and",
"stores",
"them",
"in",
"dest"
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L59-L65
|
test
|
alexflint/go-arg
|
parse.go
|
walkFields
|
func walkFields(v reflect.Value, visit func(field reflect.StructField, val reflect.Value, owner reflect.Type) bool) {
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
val := v.Field(i)
expand := visit(field, val, t)
if expand && field.Type.Kind() == reflect.Struct {
walkFields(val, visit)
}
}
}
|
go
|
func walkFields(v reflect.Value, visit func(field reflect.StructField, val reflect.Value, owner reflect.Type) bool) {
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
val := v.Field(i)
expand := visit(field, val, t)
if expand && field.Type.Kind() == reflect.Struct {
walkFields(val, visit)
}
}
}
|
[
"func",
"walkFields",
"(",
"v",
"reflect",
".",
"Value",
",",
"visit",
"func",
"(",
"field",
"reflect",
".",
"StructField",
",",
"val",
"reflect",
".",
"Value",
",",
"owner",
"reflect",
".",
"Type",
")",
"bool",
")",
"{",
"t",
":=",
"v",
".",
"Type",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"t",
".",
"NumField",
"(",
")",
";",
"i",
"++",
"{",
"field",
":=",
"t",
".",
"Field",
"(",
"i",
")",
"\n",
"val",
":=",
"v",
".",
"Field",
"(",
"i",
")",
"\n",
"expand",
":=",
"visit",
"(",
"field",
",",
"val",
",",
"t",
")",
"\n",
"if",
"expand",
"&&",
"field",
".",
"Type",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Struct",
"{",
"walkFields",
"(",
"val",
",",
"visit",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// walkFields calls a function for each field of a struct, recursively expanding struct fields.
|
[
"walkFields",
"calls",
"a",
"function",
"for",
"each",
"field",
"of",
"a",
"struct",
"recursively",
"expanding",
"struct",
"fields",
"."
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L105-L115
|
test
|
alexflint/go-arg
|
parse.go
|
Parse
|
func (p *Parser) Parse(args []string) error {
// If -h or --help were specified then print usage
for _, arg := range args {
if arg == "-h" || arg == "--help" {
return ErrHelp
}
if arg == "--version" {
return ErrVersion
}
if arg == "--" {
break
}
}
// Process all command line arguments
return process(p.specs, args)
}
|
go
|
func (p *Parser) Parse(args []string) error {
// If -h or --help were specified then print usage
for _, arg := range args {
if arg == "-h" || arg == "--help" {
return ErrHelp
}
if arg == "--version" {
return ErrVersion
}
if arg == "--" {
break
}
}
// Process all command line arguments
return process(p.specs, args)
}
|
[
"func",
"(",
"p",
"*",
"Parser",
")",
"Parse",
"(",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"_",
",",
"arg",
":=",
"range",
"args",
"{",
"if",
"arg",
"==",
"\"-h\"",
"||",
"arg",
"==",
"\"--help\"",
"{",
"return",
"ErrHelp",
"\n",
"}",
"\n",
"if",
"arg",
"==",
"\"--version\"",
"{",
"return",
"ErrVersion",
"\n",
"}",
"\n",
"if",
"arg",
"==",
"\"--\"",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"process",
"(",
"p",
".",
"specs",
",",
"args",
")",
"\n",
"}"
] |
// Parse processes the given command line option, storing the results in the field
// of the structs from which NewParser was constructed
|
[
"Parse",
"processes",
"the",
"given",
"command",
"line",
"option",
"storing",
"the",
"results",
"in",
"the",
"field",
"of",
"the",
"structs",
"from",
"which",
"NewParser",
"was",
"constructed"
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L237-L253
|
test
|
alexflint/go-arg
|
parse.go
|
setSlice
|
func setSlice(dest reflect.Value, values []string, trunc bool) error {
if !dest.CanSet() {
return fmt.Errorf("field is not writable")
}
var ptr bool
elem := dest.Type().Elem()
if elem.Kind() == reflect.Ptr && !elem.Implements(textUnmarshalerType) {
ptr = true
elem = elem.Elem()
}
// Truncate the dest slice in case default values exist
if trunc && !dest.IsNil() {
dest.SetLen(0)
}
for _, s := range values {
v := reflect.New(elem)
if err := scalar.ParseValue(v.Elem(), s); err != nil {
return err
}
if !ptr {
v = v.Elem()
}
dest.Set(reflect.Append(dest, v))
}
return nil
}
|
go
|
func setSlice(dest reflect.Value, values []string, trunc bool) error {
if !dest.CanSet() {
return fmt.Errorf("field is not writable")
}
var ptr bool
elem := dest.Type().Elem()
if elem.Kind() == reflect.Ptr && !elem.Implements(textUnmarshalerType) {
ptr = true
elem = elem.Elem()
}
// Truncate the dest slice in case default values exist
if trunc && !dest.IsNil() {
dest.SetLen(0)
}
for _, s := range values {
v := reflect.New(elem)
if err := scalar.ParseValue(v.Elem(), s); err != nil {
return err
}
if !ptr {
v = v.Elem()
}
dest.Set(reflect.Append(dest, v))
}
return nil
}
|
[
"func",
"setSlice",
"(",
"dest",
"reflect",
".",
"Value",
",",
"values",
"[",
"]",
"string",
",",
"trunc",
"bool",
")",
"error",
"{",
"if",
"!",
"dest",
".",
"CanSet",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"field is not writable\"",
")",
"\n",
"}",
"\n",
"var",
"ptr",
"bool",
"\n",
"elem",
":=",
"dest",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
"\n",
"if",
"elem",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"&&",
"!",
"elem",
".",
"Implements",
"(",
"textUnmarshalerType",
")",
"{",
"ptr",
"=",
"true",
"\n",
"elem",
"=",
"elem",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"if",
"trunc",
"&&",
"!",
"dest",
".",
"IsNil",
"(",
")",
"{",
"dest",
".",
"SetLen",
"(",
"0",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"values",
"{",
"v",
":=",
"reflect",
".",
"New",
"(",
"elem",
")",
"\n",
"if",
"err",
":=",
"scalar",
".",
"ParseValue",
"(",
"v",
".",
"Elem",
"(",
")",
",",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"ptr",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"dest",
".",
"Set",
"(",
"reflect",
".",
"Append",
"(",
"dest",
",",
"v",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// parse a value as the appropriate type and store it in the struct
|
[
"parse",
"a",
"value",
"as",
"the",
"appropriate",
"type",
"and",
"store",
"it",
"in",
"the",
"struct"
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L449-L477
|
test
|
alexflint/go-arg
|
parse.go
|
canParse
|
func canParse(t reflect.Type) (parseable, boolean, multiple bool) {
parseable = scalar.CanParse(t)
boolean = isBoolean(t)
if parseable {
return
}
// Look inside pointer types
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
// Look inside slice types
if t.Kind() == reflect.Slice {
multiple = true
t = t.Elem()
}
parseable = scalar.CanParse(t)
boolean = isBoolean(t)
if parseable {
return
}
// Look inside pointer types (again, in case of []*Type)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
parseable = scalar.CanParse(t)
boolean = isBoolean(t)
if parseable {
return
}
return false, false, false
}
|
go
|
func canParse(t reflect.Type) (parseable, boolean, multiple bool) {
parseable = scalar.CanParse(t)
boolean = isBoolean(t)
if parseable {
return
}
// Look inside pointer types
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
// Look inside slice types
if t.Kind() == reflect.Slice {
multiple = true
t = t.Elem()
}
parseable = scalar.CanParse(t)
boolean = isBoolean(t)
if parseable {
return
}
// Look inside pointer types (again, in case of []*Type)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
parseable = scalar.CanParse(t)
boolean = isBoolean(t)
if parseable {
return
}
return false, false, false
}
|
[
"func",
"canParse",
"(",
"t",
"reflect",
".",
"Type",
")",
"(",
"parseable",
",",
"boolean",
",",
"multiple",
"bool",
")",
"{",
"parseable",
"=",
"scalar",
".",
"CanParse",
"(",
"t",
")",
"\n",
"boolean",
"=",
"isBoolean",
"(",
"t",
")",
"\n",
"if",
"parseable",
"{",
"return",
"\n",
"}",
"\n",
"if",
"t",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"t",
"=",
"t",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Slice",
"{",
"multiple",
"=",
"true",
"\n",
"t",
"=",
"t",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"parseable",
"=",
"scalar",
".",
"CanParse",
"(",
"t",
")",
"\n",
"boolean",
"=",
"isBoolean",
"(",
"t",
")",
"\n",
"if",
"parseable",
"{",
"return",
"\n",
"}",
"\n",
"if",
"t",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"t",
"=",
"t",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"parseable",
"=",
"scalar",
".",
"CanParse",
"(",
"t",
")",
"\n",
"boolean",
"=",
"isBoolean",
"(",
"t",
")",
"\n",
"if",
"parseable",
"{",
"return",
"\n",
"}",
"\n",
"return",
"false",
",",
"false",
",",
"false",
"\n",
"}"
] |
// canParse returns true if the type can be parsed from a string
|
[
"canParse",
"returns",
"true",
"if",
"the",
"type",
"can",
"be",
"parsed",
"from",
"a",
"string"
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L480-L515
|
test
|
alexflint/go-arg
|
parse.go
|
isBoolean
|
func isBoolean(t reflect.Type) bool {
switch {
case t.Implements(textUnmarshalerType):
return false
case t.Kind() == reflect.Bool:
return true
case t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Bool:
return true
default:
return false
}
}
|
go
|
func isBoolean(t reflect.Type) bool {
switch {
case t.Implements(textUnmarshalerType):
return false
case t.Kind() == reflect.Bool:
return true
case t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Bool:
return true
default:
return false
}
}
|
[
"func",
"isBoolean",
"(",
"t",
"reflect",
".",
"Type",
")",
"bool",
"{",
"switch",
"{",
"case",
"t",
".",
"Implements",
"(",
"textUnmarshalerType",
")",
":",
"return",
"false",
"\n",
"case",
"t",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Bool",
":",
"return",
"true",
"\n",
"case",
"t",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"&&",
"t",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Bool",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] |
// isBoolean returns true if the type can be parsed from a single string
|
[
"isBoolean",
"returns",
"true",
"if",
"the",
"type",
"can",
"be",
"parsed",
"from",
"a",
"single",
"string"
] |
fb1ae1c3e0bd00d45333c3d51384afc05846f7a0
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L520-L531
|
test
|
armon/go-radix
|
radix.go
|
NewFromMap
|
func NewFromMap(m map[string]interface{}) *Tree {
t := &Tree{root: &node{}}
for k, v := range m {
t.Insert(k, v)
}
return t
}
|
go
|
func NewFromMap(m map[string]interface{}) *Tree {
t := &Tree{root: &node{}}
for k, v := range m {
t.Insert(k, v)
}
return t
}
|
[
"func",
"NewFromMap",
"(",
"m",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"*",
"Tree",
"{",
"t",
":=",
"&",
"Tree",
"{",
"root",
":",
"&",
"node",
"{",
"}",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"t",
".",
"Insert",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"return",
"t",
"\n",
"}"
] |
// NewFromMap returns a new tree containing the keys
// from an existing map
|
[
"NewFromMap",
"returns",
"a",
"new",
"tree",
"containing",
"the",
"keys",
"from",
"an",
"existing",
"map"
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L116-L122
|
test
|
armon/go-radix
|
radix.go
|
Insert
|
func (t *Tree) Insert(s string, v interface{}) (interface{}, bool) {
var parent *node
n := t.root
search := s
for {
// Handle key exhaution
if len(search) == 0 {
if n.isLeaf() {
old := n.leaf.val
n.leaf.val = v
return old, true
}
n.leaf = &leafNode{
key: s,
val: v,
}
t.size++
return nil, false
}
// Look for the edge
parent = n
n = n.getEdge(search[0])
// No edge, create one
if n == nil {
e := edge{
label: search[0],
node: &node{
leaf: &leafNode{
key: s,
val: v,
},
prefix: search,
},
}
parent.addEdge(e)
t.size++
return nil, false
}
// Determine longest prefix of the search key on match
commonPrefix := longestPrefix(search, n.prefix)
if commonPrefix == len(n.prefix) {
search = search[commonPrefix:]
continue
}
// Split the node
t.size++
child := &node{
prefix: search[:commonPrefix],
}
parent.updateEdge(search[0], child)
// Restore the existing node
child.addEdge(edge{
label: n.prefix[commonPrefix],
node: n,
})
n.prefix = n.prefix[commonPrefix:]
// Create a new leaf node
leaf := &leafNode{
key: s,
val: v,
}
// If the new key is a subset, add to to this node
search = search[commonPrefix:]
if len(search) == 0 {
child.leaf = leaf
return nil, false
}
// Create a new edge for the node
child.addEdge(edge{
label: search[0],
node: &node{
leaf: leaf,
prefix: search,
},
})
return nil, false
}
}
|
go
|
func (t *Tree) Insert(s string, v interface{}) (interface{}, bool) {
var parent *node
n := t.root
search := s
for {
// Handle key exhaution
if len(search) == 0 {
if n.isLeaf() {
old := n.leaf.val
n.leaf.val = v
return old, true
}
n.leaf = &leafNode{
key: s,
val: v,
}
t.size++
return nil, false
}
// Look for the edge
parent = n
n = n.getEdge(search[0])
// No edge, create one
if n == nil {
e := edge{
label: search[0],
node: &node{
leaf: &leafNode{
key: s,
val: v,
},
prefix: search,
},
}
parent.addEdge(e)
t.size++
return nil, false
}
// Determine longest prefix of the search key on match
commonPrefix := longestPrefix(search, n.prefix)
if commonPrefix == len(n.prefix) {
search = search[commonPrefix:]
continue
}
// Split the node
t.size++
child := &node{
prefix: search[:commonPrefix],
}
parent.updateEdge(search[0], child)
// Restore the existing node
child.addEdge(edge{
label: n.prefix[commonPrefix],
node: n,
})
n.prefix = n.prefix[commonPrefix:]
// Create a new leaf node
leaf := &leafNode{
key: s,
val: v,
}
// If the new key is a subset, add to to this node
search = search[commonPrefix:]
if len(search) == 0 {
child.leaf = leaf
return nil, false
}
// Create a new edge for the node
child.addEdge(edge{
label: search[0],
node: &node{
leaf: leaf,
prefix: search,
},
})
return nil, false
}
}
|
[
"func",
"(",
"t",
"*",
"Tree",
")",
"Insert",
"(",
"s",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"var",
"parent",
"*",
"node",
"\n",
"n",
":=",
"t",
".",
"root",
"\n",
"search",
":=",
"s",
"\n",
"for",
"{",
"if",
"len",
"(",
"search",
")",
"==",
"0",
"{",
"if",
"n",
".",
"isLeaf",
"(",
")",
"{",
"old",
":=",
"n",
".",
"leaf",
".",
"val",
"\n",
"n",
".",
"leaf",
".",
"val",
"=",
"v",
"\n",
"return",
"old",
",",
"true",
"\n",
"}",
"\n",
"n",
".",
"leaf",
"=",
"&",
"leafNode",
"{",
"key",
":",
"s",
",",
"val",
":",
"v",
",",
"}",
"\n",
"t",
".",
"size",
"++",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"parent",
"=",
"n",
"\n",
"n",
"=",
"n",
".",
"getEdge",
"(",
"search",
"[",
"0",
"]",
")",
"\n",
"if",
"n",
"==",
"nil",
"{",
"e",
":=",
"edge",
"{",
"label",
":",
"search",
"[",
"0",
"]",
",",
"node",
":",
"&",
"node",
"{",
"leaf",
":",
"&",
"leafNode",
"{",
"key",
":",
"s",
",",
"val",
":",
"v",
",",
"}",
",",
"prefix",
":",
"search",
",",
"}",
",",
"}",
"\n",
"parent",
".",
"addEdge",
"(",
"e",
")",
"\n",
"t",
".",
"size",
"++",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"commonPrefix",
":=",
"longestPrefix",
"(",
"search",
",",
"n",
".",
"prefix",
")",
"\n",
"if",
"commonPrefix",
"==",
"len",
"(",
"n",
".",
"prefix",
")",
"{",
"search",
"=",
"search",
"[",
"commonPrefix",
":",
"]",
"\n",
"continue",
"\n",
"}",
"\n",
"t",
".",
"size",
"++",
"\n",
"child",
":=",
"&",
"node",
"{",
"prefix",
":",
"search",
"[",
":",
"commonPrefix",
"]",
",",
"}",
"\n",
"parent",
".",
"updateEdge",
"(",
"search",
"[",
"0",
"]",
",",
"child",
")",
"\n",
"child",
".",
"addEdge",
"(",
"edge",
"{",
"label",
":",
"n",
".",
"prefix",
"[",
"commonPrefix",
"]",
",",
"node",
":",
"n",
",",
"}",
")",
"\n",
"n",
".",
"prefix",
"=",
"n",
".",
"prefix",
"[",
"commonPrefix",
":",
"]",
"\n",
"leaf",
":=",
"&",
"leafNode",
"{",
"key",
":",
"s",
",",
"val",
":",
"v",
",",
"}",
"\n",
"search",
"=",
"search",
"[",
"commonPrefix",
":",
"]",
"\n",
"if",
"len",
"(",
"search",
")",
"==",
"0",
"{",
"child",
".",
"leaf",
"=",
"leaf",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"child",
".",
"addEdge",
"(",
"edge",
"{",
"label",
":",
"search",
"[",
"0",
"]",
",",
"node",
":",
"&",
"node",
"{",
"leaf",
":",
"leaf",
",",
"prefix",
":",
"search",
",",
"}",
",",
"}",
")",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"}"
] |
// Insert is used to add a newentry or update
// an existing entry. Returns if updated.
|
[
"Insert",
"is",
"used",
"to",
"add",
"a",
"newentry",
"or",
"update",
"an",
"existing",
"entry",
".",
"Returns",
"if",
"updated",
"."
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L147-L233
|
test
|
armon/go-radix
|
radix.go
|
Delete
|
func (t *Tree) Delete(s string) (interface{}, bool) {
var parent *node
var label byte
n := t.root
search := s
for {
// Check for key exhaution
if len(search) == 0 {
if !n.isLeaf() {
break
}
goto DELETE
}
// Look for an edge
parent = n
label = search[0]
n = n.getEdge(label)
if n == nil {
break
}
// Consume the search prefix
if strings.HasPrefix(search, n.prefix) {
search = search[len(n.prefix):]
} else {
break
}
}
return nil, false
DELETE:
// Delete the leaf
leaf := n.leaf
n.leaf = nil
t.size--
// Check if we should delete this node from the parent
if parent != nil && len(n.edges) == 0 {
parent.delEdge(label)
}
// Check if we should merge this node
if n != t.root && len(n.edges) == 1 {
n.mergeChild()
}
// Check if we should merge the parent's other child
if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() {
parent.mergeChild()
}
return leaf.val, true
}
|
go
|
func (t *Tree) Delete(s string) (interface{}, bool) {
var parent *node
var label byte
n := t.root
search := s
for {
// Check for key exhaution
if len(search) == 0 {
if !n.isLeaf() {
break
}
goto DELETE
}
// Look for an edge
parent = n
label = search[0]
n = n.getEdge(label)
if n == nil {
break
}
// Consume the search prefix
if strings.HasPrefix(search, n.prefix) {
search = search[len(n.prefix):]
} else {
break
}
}
return nil, false
DELETE:
// Delete the leaf
leaf := n.leaf
n.leaf = nil
t.size--
// Check if we should delete this node from the parent
if parent != nil && len(n.edges) == 0 {
parent.delEdge(label)
}
// Check if we should merge this node
if n != t.root && len(n.edges) == 1 {
n.mergeChild()
}
// Check if we should merge the parent's other child
if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() {
parent.mergeChild()
}
return leaf.val, true
}
|
[
"func",
"(",
"t",
"*",
"Tree",
")",
"Delete",
"(",
"s",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"var",
"parent",
"*",
"node",
"\n",
"var",
"label",
"byte",
"\n",
"n",
":=",
"t",
".",
"root",
"\n",
"search",
":=",
"s",
"\n",
"for",
"{",
"if",
"len",
"(",
"search",
")",
"==",
"0",
"{",
"if",
"!",
"n",
".",
"isLeaf",
"(",
")",
"{",
"break",
"\n",
"}",
"\n",
"goto",
"DELETE",
"\n",
"}",
"\n",
"parent",
"=",
"n",
"\n",
"label",
"=",
"search",
"[",
"0",
"]",
"\n",
"n",
"=",
"n",
".",
"getEdge",
"(",
"label",
")",
"\n",
"if",
"n",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"search",
",",
"n",
".",
"prefix",
")",
"{",
"search",
"=",
"search",
"[",
"len",
"(",
"n",
".",
"prefix",
")",
":",
"]",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"DELETE",
":",
"leaf",
":=",
"n",
".",
"leaf",
"\n",
"n",
".",
"leaf",
"=",
"nil",
"\n",
"t",
".",
"size",
"--",
"\n",
"if",
"parent",
"!=",
"nil",
"&&",
"len",
"(",
"n",
".",
"edges",
")",
"==",
"0",
"{",
"parent",
".",
"delEdge",
"(",
"label",
")",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"t",
".",
"root",
"&&",
"len",
"(",
"n",
".",
"edges",
")",
"==",
"1",
"{",
"n",
".",
"mergeChild",
"(",
")",
"\n",
"}",
"\n",
"if",
"parent",
"!=",
"nil",
"&&",
"parent",
"!=",
"t",
".",
"root",
"&&",
"len",
"(",
"parent",
".",
"edges",
")",
"==",
"1",
"&&",
"!",
"parent",
".",
"isLeaf",
"(",
")",
"{",
"parent",
".",
"mergeChild",
"(",
")",
"\n",
"}",
"\n",
"return",
"leaf",
".",
"val",
",",
"true",
"\n",
"}"
] |
// Delete is used to delete a key, returning the previous
// value and if it was deleted
|
[
"Delete",
"is",
"used",
"to",
"delete",
"a",
"key",
"returning",
"the",
"previous",
"value",
"and",
"if",
"it",
"was",
"deleted"
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L237-L290
|
test
|
armon/go-radix
|
radix.go
|
DeletePrefix
|
func (t *Tree) DeletePrefix(s string) int {
return t.deletePrefix(nil, t.root, s)
}
|
go
|
func (t *Tree) DeletePrefix(s string) int {
return t.deletePrefix(nil, t.root, s)
}
|
[
"func",
"(",
"t",
"*",
"Tree",
")",
"DeletePrefix",
"(",
"s",
"string",
")",
"int",
"{",
"return",
"t",
".",
"deletePrefix",
"(",
"nil",
",",
"t",
".",
"root",
",",
"s",
")",
"\n",
"}"
] |
// DeletePrefix is used to delete the subtree under a prefix
// Returns how many nodes were deleted
// Use this to delete large subtrees efficiently
|
[
"DeletePrefix",
"is",
"used",
"to",
"delete",
"the",
"subtree",
"under",
"a",
"prefix",
"Returns",
"how",
"many",
"nodes",
"were",
"deleted",
"Use",
"this",
"to",
"delete",
"large",
"subtrees",
"efficiently"
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L295-L297
|
test
|
armon/go-radix
|
radix.go
|
deletePrefix
|
func (t *Tree) deletePrefix(parent, n *node, prefix string) int {
// Check for key exhaustion
if len(prefix) == 0 {
// Remove the leaf node
subTreeSize := 0
//recursively walk from all edges of the node to be deleted
recursiveWalk(n, func(s string, v interface{}) bool {
subTreeSize++
return false
})
if n.isLeaf() {
n.leaf = nil
}
n.edges = nil // deletes the entire subtree
// Check if we should merge the parent's other child
if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() {
parent.mergeChild()
}
t.size -= subTreeSize
return subTreeSize
}
// Look for an edge
label := prefix[0]
child := n.getEdge(label)
if child == nil || (!strings.HasPrefix(child.prefix, prefix) && !strings.HasPrefix(prefix, child.prefix)) {
return 0
}
// Consume the search prefix
if len(child.prefix) > len(prefix) {
prefix = prefix[len(prefix):]
} else {
prefix = prefix[len(child.prefix):]
}
return t.deletePrefix(n, child, prefix)
}
|
go
|
func (t *Tree) deletePrefix(parent, n *node, prefix string) int {
// Check for key exhaustion
if len(prefix) == 0 {
// Remove the leaf node
subTreeSize := 0
//recursively walk from all edges of the node to be deleted
recursiveWalk(n, func(s string, v interface{}) bool {
subTreeSize++
return false
})
if n.isLeaf() {
n.leaf = nil
}
n.edges = nil // deletes the entire subtree
// Check if we should merge the parent's other child
if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() {
parent.mergeChild()
}
t.size -= subTreeSize
return subTreeSize
}
// Look for an edge
label := prefix[0]
child := n.getEdge(label)
if child == nil || (!strings.HasPrefix(child.prefix, prefix) && !strings.HasPrefix(prefix, child.prefix)) {
return 0
}
// Consume the search prefix
if len(child.prefix) > len(prefix) {
prefix = prefix[len(prefix):]
} else {
prefix = prefix[len(child.prefix):]
}
return t.deletePrefix(n, child, prefix)
}
|
[
"func",
"(",
"t",
"*",
"Tree",
")",
"deletePrefix",
"(",
"parent",
",",
"n",
"*",
"node",
",",
"prefix",
"string",
")",
"int",
"{",
"if",
"len",
"(",
"prefix",
")",
"==",
"0",
"{",
"subTreeSize",
":=",
"0",
"\n",
"recursiveWalk",
"(",
"n",
",",
"func",
"(",
"s",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"subTreeSize",
"++",
"\n",
"return",
"false",
"\n",
"}",
")",
"\n",
"if",
"n",
".",
"isLeaf",
"(",
")",
"{",
"n",
".",
"leaf",
"=",
"nil",
"\n",
"}",
"\n",
"n",
".",
"edges",
"=",
"nil",
"\n",
"if",
"parent",
"!=",
"nil",
"&&",
"parent",
"!=",
"t",
".",
"root",
"&&",
"len",
"(",
"parent",
".",
"edges",
")",
"==",
"1",
"&&",
"!",
"parent",
".",
"isLeaf",
"(",
")",
"{",
"parent",
".",
"mergeChild",
"(",
")",
"\n",
"}",
"\n",
"t",
".",
"size",
"-=",
"subTreeSize",
"\n",
"return",
"subTreeSize",
"\n",
"}",
"\n",
"label",
":=",
"prefix",
"[",
"0",
"]",
"\n",
"child",
":=",
"n",
".",
"getEdge",
"(",
"label",
")",
"\n",
"if",
"child",
"==",
"nil",
"||",
"(",
"!",
"strings",
".",
"HasPrefix",
"(",
"child",
".",
"prefix",
",",
"prefix",
")",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"prefix",
",",
"child",
".",
"prefix",
")",
")",
"{",
"return",
"0",
"\n",
"}",
"\n",
"if",
"len",
"(",
"child",
".",
"prefix",
")",
">",
"len",
"(",
"prefix",
")",
"{",
"prefix",
"=",
"prefix",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"\n",
"}",
"else",
"{",
"prefix",
"=",
"prefix",
"[",
"len",
"(",
"child",
".",
"prefix",
")",
":",
"]",
"\n",
"}",
"\n",
"return",
"t",
".",
"deletePrefix",
"(",
"n",
",",
"child",
",",
"prefix",
")",
"\n",
"}"
] |
// delete does a recursive deletion
|
[
"delete",
"does",
"a",
"recursive",
"deletion"
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L300-L337
|
test
|
armon/go-radix
|
radix.go
|
Get
|
func (t *Tree) Get(s string) (interface{}, bool) {
n := t.root
search := s
for {
// Check for key exhaution
if len(search) == 0 {
if n.isLeaf() {
return n.leaf.val, true
}
break
}
// Look for an edge
n = n.getEdge(search[0])
if n == nil {
break
}
// Consume the search prefix
if strings.HasPrefix(search, n.prefix) {
search = search[len(n.prefix):]
} else {
break
}
}
return nil, false
}
|
go
|
func (t *Tree) Get(s string) (interface{}, bool) {
n := t.root
search := s
for {
// Check for key exhaution
if len(search) == 0 {
if n.isLeaf() {
return n.leaf.val, true
}
break
}
// Look for an edge
n = n.getEdge(search[0])
if n == nil {
break
}
// Consume the search prefix
if strings.HasPrefix(search, n.prefix) {
search = search[len(n.prefix):]
} else {
break
}
}
return nil, false
}
|
[
"func",
"(",
"t",
"*",
"Tree",
")",
"Get",
"(",
"s",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"n",
":=",
"t",
".",
"root",
"\n",
"search",
":=",
"s",
"\n",
"for",
"{",
"if",
"len",
"(",
"search",
")",
"==",
"0",
"{",
"if",
"n",
".",
"isLeaf",
"(",
")",
"{",
"return",
"n",
".",
"leaf",
".",
"val",
",",
"true",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"n",
"=",
"n",
".",
"getEdge",
"(",
"search",
"[",
"0",
"]",
")",
"\n",
"if",
"n",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"search",
",",
"n",
".",
"prefix",
")",
"{",
"search",
"=",
"search",
"[",
"len",
"(",
"n",
".",
"prefix",
")",
":",
"]",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
] |
// Get is used to lookup a specific key, returning
// the value and if it was found
|
[
"Get",
"is",
"used",
"to",
"lookup",
"a",
"specific",
"key",
"returning",
"the",
"value",
"and",
"if",
"it",
"was",
"found"
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L349-L375
|
test
|
armon/go-radix
|
radix.go
|
LongestPrefix
|
func (t *Tree) LongestPrefix(s string) (string, interface{}, bool) {
var last *leafNode
n := t.root
search := s
for {
// Look for a leaf node
if n.isLeaf() {
last = n.leaf
}
// Check for key exhaution
if len(search) == 0 {
break
}
// Look for an edge
n = n.getEdge(search[0])
if n == nil {
break
}
// Consume the search prefix
if strings.HasPrefix(search, n.prefix) {
search = search[len(n.prefix):]
} else {
break
}
}
if last != nil {
return last.key, last.val, true
}
return "", nil, false
}
|
go
|
func (t *Tree) LongestPrefix(s string) (string, interface{}, bool) {
var last *leafNode
n := t.root
search := s
for {
// Look for a leaf node
if n.isLeaf() {
last = n.leaf
}
// Check for key exhaution
if len(search) == 0 {
break
}
// Look for an edge
n = n.getEdge(search[0])
if n == nil {
break
}
// Consume the search prefix
if strings.HasPrefix(search, n.prefix) {
search = search[len(n.prefix):]
} else {
break
}
}
if last != nil {
return last.key, last.val, true
}
return "", nil, false
}
|
[
"func",
"(",
"t",
"*",
"Tree",
")",
"LongestPrefix",
"(",
"s",
"string",
")",
"(",
"string",
",",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"var",
"last",
"*",
"leafNode",
"\n",
"n",
":=",
"t",
".",
"root",
"\n",
"search",
":=",
"s",
"\n",
"for",
"{",
"if",
"n",
".",
"isLeaf",
"(",
")",
"{",
"last",
"=",
"n",
".",
"leaf",
"\n",
"}",
"\n",
"if",
"len",
"(",
"search",
")",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"n",
"=",
"n",
".",
"getEdge",
"(",
"search",
"[",
"0",
"]",
")",
"\n",
"if",
"n",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"search",
",",
"n",
".",
"prefix",
")",
"{",
"search",
"=",
"search",
"[",
"len",
"(",
"n",
".",
"prefix",
")",
":",
"]",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"last",
"!=",
"nil",
"{",
"return",
"last",
".",
"key",
",",
"last",
".",
"val",
",",
"true",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"nil",
",",
"false",
"\n",
"}"
] |
// LongestPrefix is like Get, but instead of an
// exact match, it will return the longest prefix match.
|
[
"LongestPrefix",
"is",
"like",
"Get",
"but",
"instead",
"of",
"an",
"exact",
"match",
"it",
"will",
"return",
"the",
"longest",
"prefix",
"match",
"."
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L379-L411
|
test
|
armon/go-radix
|
radix.go
|
Minimum
|
func (t *Tree) Minimum() (string, interface{}, bool) {
n := t.root
for {
if n.isLeaf() {
return n.leaf.key, n.leaf.val, true
}
if len(n.edges) > 0 {
n = n.edges[0].node
} else {
break
}
}
return "", nil, false
}
|
go
|
func (t *Tree) Minimum() (string, interface{}, bool) {
n := t.root
for {
if n.isLeaf() {
return n.leaf.key, n.leaf.val, true
}
if len(n.edges) > 0 {
n = n.edges[0].node
} else {
break
}
}
return "", nil, false
}
|
[
"func",
"(",
"t",
"*",
"Tree",
")",
"Minimum",
"(",
")",
"(",
"string",
",",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"n",
":=",
"t",
".",
"root",
"\n",
"for",
"{",
"if",
"n",
".",
"isLeaf",
"(",
")",
"{",
"return",
"n",
".",
"leaf",
".",
"key",
",",
"n",
".",
"leaf",
".",
"val",
",",
"true",
"\n",
"}",
"\n",
"if",
"len",
"(",
"n",
".",
"edges",
")",
">",
"0",
"{",
"n",
"=",
"n",
".",
"edges",
"[",
"0",
"]",
".",
"node",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"nil",
",",
"false",
"\n",
"}"
] |
// Minimum is used to return the minimum value in the tree
|
[
"Minimum",
"is",
"used",
"to",
"return",
"the",
"minimum",
"value",
"in",
"the",
"tree"
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L414-L427
|
test
|
armon/go-radix
|
radix.go
|
WalkPrefix
|
func (t *Tree) WalkPrefix(prefix string, fn WalkFn) {
n := t.root
search := prefix
for {
// Check for key exhaution
if len(search) == 0 {
recursiveWalk(n, fn)
return
}
// Look for an edge
n = n.getEdge(search[0])
if n == nil {
break
}
// Consume the search prefix
if strings.HasPrefix(search, n.prefix) {
search = search[len(n.prefix):]
} else if strings.HasPrefix(n.prefix, search) {
// Child may be under our search prefix
recursiveWalk(n, fn)
return
} else {
break
}
}
}
|
go
|
func (t *Tree) WalkPrefix(prefix string, fn WalkFn) {
n := t.root
search := prefix
for {
// Check for key exhaution
if len(search) == 0 {
recursiveWalk(n, fn)
return
}
// Look for an edge
n = n.getEdge(search[0])
if n == nil {
break
}
// Consume the search prefix
if strings.HasPrefix(search, n.prefix) {
search = search[len(n.prefix):]
} else if strings.HasPrefix(n.prefix, search) {
// Child may be under our search prefix
recursiveWalk(n, fn)
return
} else {
break
}
}
}
|
[
"func",
"(",
"t",
"*",
"Tree",
")",
"WalkPrefix",
"(",
"prefix",
"string",
",",
"fn",
"WalkFn",
")",
"{",
"n",
":=",
"t",
".",
"root",
"\n",
"search",
":=",
"prefix",
"\n",
"for",
"{",
"if",
"len",
"(",
"search",
")",
"==",
"0",
"{",
"recursiveWalk",
"(",
"n",
",",
"fn",
")",
"\n",
"return",
"\n",
"}",
"\n",
"n",
"=",
"n",
".",
"getEdge",
"(",
"search",
"[",
"0",
"]",
")",
"\n",
"if",
"n",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"search",
",",
"n",
".",
"prefix",
")",
"{",
"search",
"=",
"search",
"[",
"len",
"(",
"n",
".",
"prefix",
")",
":",
"]",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"n",
".",
"prefix",
",",
"search",
")",
"{",
"recursiveWalk",
"(",
"n",
",",
"fn",
")",
"\n",
"return",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// WalkPrefix is used to walk the tree under a prefix
|
[
"WalkPrefix",
"is",
"used",
"to",
"walk",
"the",
"tree",
"under",
"a",
"prefix"
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L451-L480
|
test
|
armon/go-radix
|
radix.go
|
recursiveWalk
|
func recursiveWalk(n *node, fn WalkFn) bool {
// Visit the leaf values if any
if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
return true
}
// Recurse on the children
for _, e := range n.edges {
if recursiveWalk(e.node, fn) {
return true
}
}
return false
}
|
go
|
func recursiveWalk(n *node, fn WalkFn) bool {
// Visit the leaf values if any
if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
return true
}
// Recurse on the children
for _, e := range n.edges {
if recursiveWalk(e.node, fn) {
return true
}
}
return false
}
|
[
"func",
"recursiveWalk",
"(",
"n",
"*",
"node",
",",
"fn",
"WalkFn",
")",
"bool",
"{",
"if",
"n",
".",
"leaf",
"!=",
"nil",
"&&",
"fn",
"(",
"n",
".",
"leaf",
".",
"key",
",",
"n",
".",
"leaf",
".",
"val",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"n",
".",
"edges",
"{",
"if",
"recursiveWalk",
"(",
"e",
".",
"node",
",",
"fn",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// recursiveWalk is used to do a pre-order walk of a node
// recursively. Returns true if the walk should be aborted
|
[
"recursiveWalk",
"is",
"used",
"to",
"do",
"a",
"pre",
"-",
"order",
"walk",
"of",
"a",
"node",
"recursively",
".",
"Returns",
"true",
"if",
"the",
"walk",
"should",
"be",
"aborted"
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L517-L530
|
test
|
armon/go-radix
|
radix.go
|
ToMap
|
func (t *Tree) ToMap() map[string]interface{} {
out := make(map[string]interface{}, t.size)
t.Walk(func(k string, v interface{}) bool {
out[k] = v
return false
})
return out
}
|
go
|
func (t *Tree) ToMap() map[string]interface{} {
out := make(map[string]interface{}, t.size)
t.Walk(func(k string, v interface{}) bool {
out[k] = v
return false
})
return out
}
|
[
"func",
"(",
"t",
"*",
"Tree",
")",
"ToMap",
"(",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"t",
".",
"size",
")",
"\n",
"t",
".",
"Walk",
"(",
"func",
"(",
"k",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"out",
"[",
"k",
"]",
"=",
"v",
"\n",
"return",
"false",
"\n",
"}",
")",
"\n",
"return",
"out",
"\n",
"}"
] |
// ToMap is used to walk the tree and convert it into a map
|
[
"ToMap",
"is",
"used",
"to",
"walk",
"the",
"tree",
"and",
"convert",
"it",
"into",
"a",
"map"
] |
1a2de0c21c94309923825da3df33a4381872c795
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L533-L540
|
test
|
ip2location/ip2location-go
|
ip2location.go
|
checkip
|
func checkip(ip string) (iptype uint32, ipnum *big.Int, ipindex uint32) {
iptype = 0
ipnum = big.NewInt(0)
ipnumtmp := big.NewInt(0)
ipindex = 0
ipaddress := net.ParseIP(ip)
if ipaddress != nil {
v4 := ipaddress.To4()
if v4 != nil {
iptype = 4
ipnum.SetBytes(v4)
} else {
v6 := ipaddress.To16()
if v6 != nil {
iptype = 6
ipnum.SetBytes(v6)
}
}
}
if iptype == 4 {
if meta.ipv4indexbaseaddr > 0 {
ipnumtmp.Rsh(ipnum, 16)
ipnumtmp.Lsh(ipnumtmp, 3)
ipindex = uint32(ipnumtmp.Add(ipnumtmp, big.NewInt(int64(meta.ipv4indexbaseaddr))).Uint64())
}
} else if iptype == 6 {
if meta.ipv6indexbaseaddr > 0 {
ipnumtmp.Rsh(ipnum, 112)
ipnumtmp.Lsh(ipnumtmp, 3)
ipindex = uint32(ipnumtmp.Add(ipnumtmp, big.NewInt(int64(meta.ipv6indexbaseaddr))).Uint64())
}
}
return
}
|
go
|
func checkip(ip string) (iptype uint32, ipnum *big.Int, ipindex uint32) {
iptype = 0
ipnum = big.NewInt(0)
ipnumtmp := big.NewInt(0)
ipindex = 0
ipaddress := net.ParseIP(ip)
if ipaddress != nil {
v4 := ipaddress.To4()
if v4 != nil {
iptype = 4
ipnum.SetBytes(v4)
} else {
v6 := ipaddress.To16()
if v6 != nil {
iptype = 6
ipnum.SetBytes(v6)
}
}
}
if iptype == 4 {
if meta.ipv4indexbaseaddr > 0 {
ipnumtmp.Rsh(ipnum, 16)
ipnumtmp.Lsh(ipnumtmp, 3)
ipindex = uint32(ipnumtmp.Add(ipnumtmp, big.NewInt(int64(meta.ipv4indexbaseaddr))).Uint64())
}
} else if iptype == 6 {
if meta.ipv6indexbaseaddr > 0 {
ipnumtmp.Rsh(ipnum, 112)
ipnumtmp.Lsh(ipnumtmp, 3)
ipindex = uint32(ipnumtmp.Add(ipnumtmp, big.NewInt(int64(meta.ipv6indexbaseaddr))).Uint64())
}
}
return
}
|
[
"func",
"checkip",
"(",
"ip",
"string",
")",
"(",
"iptype",
"uint32",
",",
"ipnum",
"*",
"big",
".",
"Int",
",",
"ipindex",
"uint32",
")",
"{",
"iptype",
"=",
"0",
"\n",
"ipnum",
"=",
"big",
".",
"NewInt",
"(",
"0",
")",
"\n",
"ipnumtmp",
":=",
"big",
".",
"NewInt",
"(",
"0",
")",
"\n",
"ipindex",
"=",
"0",
"\n",
"ipaddress",
":=",
"net",
".",
"ParseIP",
"(",
"ip",
")",
"\n",
"if",
"ipaddress",
"!=",
"nil",
"{",
"v4",
":=",
"ipaddress",
".",
"To4",
"(",
")",
"\n",
"if",
"v4",
"!=",
"nil",
"{",
"iptype",
"=",
"4",
"\n",
"ipnum",
".",
"SetBytes",
"(",
"v4",
")",
"\n",
"}",
"else",
"{",
"v6",
":=",
"ipaddress",
".",
"To16",
"(",
")",
"\n",
"if",
"v6",
"!=",
"nil",
"{",
"iptype",
"=",
"6",
"\n",
"ipnum",
".",
"SetBytes",
"(",
"v6",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"iptype",
"==",
"4",
"{",
"if",
"meta",
".",
"ipv4indexbaseaddr",
">",
"0",
"{",
"ipnumtmp",
".",
"Rsh",
"(",
"ipnum",
",",
"16",
")",
"\n",
"ipnumtmp",
".",
"Lsh",
"(",
"ipnumtmp",
",",
"3",
")",
"\n",
"ipindex",
"=",
"uint32",
"(",
"ipnumtmp",
".",
"Add",
"(",
"ipnumtmp",
",",
"big",
".",
"NewInt",
"(",
"int64",
"(",
"meta",
".",
"ipv4indexbaseaddr",
")",
")",
")",
".",
"Uint64",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"iptype",
"==",
"6",
"{",
"if",
"meta",
".",
"ipv6indexbaseaddr",
">",
"0",
"{",
"ipnumtmp",
".",
"Rsh",
"(",
"ipnum",
",",
"112",
")",
"\n",
"ipnumtmp",
".",
"Lsh",
"(",
"ipnumtmp",
",",
"3",
")",
"\n",
"ipindex",
"=",
"uint32",
"(",
"ipnumtmp",
".",
"Add",
"(",
"ipnumtmp",
",",
"big",
".",
"NewInt",
"(",
"int64",
"(",
"meta",
".",
"ipv6indexbaseaddr",
")",
")",
")",
".",
"Uint64",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// get IP type and calculate IP number; calculates index too if exists
|
[
"get",
"IP",
"type",
"and",
"calculate",
"IP",
"number",
";",
"calculates",
"index",
"too",
"if",
"exists"
] |
a417f19539fd2a0eb0adf273b4190241cacc0499
|
https://github.com/ip2location/ip2location-go/blob/a417f19539fd2a0eb0adf273b4190241cacc0499/ip2location.go#L150-L186
|
test
|
ip2location/ip2location-go
|
ip2location.go
|
readuint32
|
func readuint32(pos uint32) uint32 {
pos2 := int64(pos)
var retval uint32
data := make([]byte, 4)
_, err := f.ReadAt(data, pos2 - 1)
if err != nil {
fmt.Println("File read failed:", err)
}
buf := bytes.NewReader(data)
err = binary.Read(buf, binary.LittleEndian, &retval)
if err != nil {
fmt.Println("Binary read failed:", err)
}
return retval
}
|
go
|
func readuint32(pos uint32) uint32 {
pos2 := int64(pos)
var retval uint32
data := make([]byte, 4)
_, err := f.ReadAt(data, pos2 - 1)
if err != nil {
fmt.Println("File read failed:", err)
}
buf := bytes.NewReader(data)
err = binary.Read(buf, binary.LittleEndian, &retval)
if err != nil {
fmt.Println("Binary read failed:", err)
}
return retval
}
|
[
"func",
"readuint32",
"(",
"pos",
"uint32",
")",
"uint32",
"{",
"pos2",
":=",
"int64",
"(",
"pos",
")",
"\n",
"var",
"retval",
"uint32",
"\n",
"data",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"_",
",",
"err",
":=",
"f",
".",
"ReadAt",
"(",
"data",
",",
"pos2",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"File read failed:\"",
",",
"err",
")",
"\n",
"}",
"\n",
"buf",
":=",
"bytes",
".",
"NewReader",
"(",
"data",
")",
"\n",
"err",
"=",
"binary",
".",
"Read",
"(",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"retval",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"Binary read failed:\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"retval",
"\n",
"}"
] |
// read unsigned 32-bit integer
|
[
"read",
"unsigned",
"32",
"-",
"bit",
"integer"
] |
a417f19539fd2a0eb0adf273b4190241cacc0499
|
https://github.com/ip2location/ip2location-go/blob/a417f19539fd2a0eb0adf273b4190241cacc0499/ip2location.go#L201-L215
|
test
|
ip2location/ip2location-go
|
ip2location.go
|
readuint128
|
func readuint128(pos uint32) *big.Int {
pos2 := int64(pos)
retval := big.NewInt(0)
data := make([]byte, 16)
_, err := f.ReadAt(data, pos2 - 1)
if err != nil {
fmt.Println("File read failed:", err)
}
// little endian to big endian
for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {
data[i], data[j] = data[j], data[i]
}
retval.SetBytes(data)
return retval
}
|
go
|
func readuint128(pos uint32) *big.Int {
pos2 := int64(pos)
retval := big.NewInt(0)
data := make([]byte, 16)
_, err := f.ReadAt(data, pos2 - 1)
if err != nil {
fmt.Println("File read failed:", err)
}
// little endian to big endian
for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {
data[i], data[j] = data[j], data[i]
}
retval.SetBytes(data)
return retval
}
|
[
"func",
"readuint128",
"(",
"pos",
"uint32",
")",
"*",
"big",
".",
"Int",
"{",
"pos2",
":=",
"int64",
"(",
"pos",
")",
"\n",
"retval",
":=",
"big",
".",
"NewInt",
"(",
"0",
")",
"\n",
"data",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"16",
")",
"\n",
"_",
",",
"err",
":=",
"f",
".",
"ReadAt",
"(",
"data",
",",
"pos2",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"File read failed:\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"j",
":=",
"0",
",",
"len",
"(",
"data",
")",
"-",
"1",
";",
"i",
"<",
"j",
";",
"i",
",",
"j",
"=",
"i",
"+",
"1",
",",
"j",
"-",
"1",
"{",
"data",
"[",
"i",
"]",
",",
"data",
"[",
"j",
"]",
"=",
"data",
"[",
"j",
"]",
",",
"data",
"[",
"i",
"]",
"\n",
"}",
"\n",
"retval",
".",
"SetBytes",
"(",
"data",
")",
"\n",
"return",
"retval",
"\n",
"}"
] |
// read unsigned 128-bit integer
|
[
"read",
"unsigned",
"128",
"-",
"bit",
"integer"
] |
a417f19539fd2a0eb0adf273b4190241cacc0499
|
https://github.com/ip2location/ip2location-go/blob/a417f19539fd2a0eb0adf273b4190241cacc0499/ip2location.go#L218-L233
|
test
|
ip2location/ip2location-go
|
ip2location.go
|
loadmessage
|
func loadmessage (mesg string) IP2Locationrecord {
var x IP2Locationrecord
x.Country_short = mesg
x.Country_long = mesg
x.Region = mesg
x.City = mesg
x.Isp = mesg
x.Domain = mesg
x.Zipcode = mesg
x.Timezone = mesg
x.Netspeed = mesg
x.Iddcode = mesg
x.Areacode = mesg
x.Weatherstationcode = mesg
x.Weatherstationname = mesg
x.Mcc = mesg
x.Mnc = mesg
x.Mobilebrand = mesg
x.Usagetype = mesg
return x
}
|
go
|
func loadmessage (mesg string) IP2Locationrecord {
var x IP2Locationrecord
x.Country_short = mesg
x.Country_long = mesg
x.Region = mesg
x.City = mesg
x.Isp = mesg
x.Domain = mesg
x.Zipcode = mesg
x.Timezone = mesg
x.Netspeed = mesg
x.Iddcode = mesg
x.Areacode = mesg
x.Weatherstationcode = mesg
x.Weatherstationname = mesg
x.Mcc = mesg
x.Mnc = mesg
x.Mobilebrand = mesg
x.Usagetype = mesg
return x
}
|
[
"func",
"loadmessage",
"(",
"mesg",
"string",
")",
"IP2Locationrecord",
"{",
"var",
"x",
"IP2Locationrecord",
"\n",
"x",
".",
"Country_short",
"=",
"mesg",
"\n",
"x",
".",
"Country_long",
"=",
"mesg",
"\n",
"x",
".",
"Region",
"=",
"mesg",
"\n",
"x",
".",
"City",
"=",
"mesg",
"\n",
"x",
".",
"Isp",
"=",
"mesg",
"\n",
"x",
".",
"Domain",
"=",
"mesg",
"\n",
"x",
".",
"Zipcode",
"=",
"mesg",
"\n",
"x",
".",
"Timezone",
"=",
"mesg",
"\n",
"x",
".",
"Netspeed",
"=",
"mesg",
"\n",
"x",
".",
"Iddcode",
"=",
"mesg",
"\n",
"x",
".",
"Areacode",
"=",
"mesg",
"\n",
"x",
".",
"Weatherstationcode",
"=",
"mesg",
"\n",
"x",
".",
"Weatherstationname",
"=",
"mesg",
"\n",
"x",
".",
"Mcc",
"=",
"mesg",
"\n",
"x",
".",
"Mnc",
"=",
"mesg",
"\n",
"x",
".",
"Mobilebrand",
"=",
"mesg",
"\n",
"x",
".",
"Usagetype",
"=",
"mesg",
"\n",
"return",
"x",
"\n",
"}"
] |
// populate record with message
|
[
"populate",
"record",
"with",
"message"
] |
a417f19539fd2a0eb0adf273b4190241cacc0499
|
https://github.com/ip2location/ip2location-go/blob/a417f19539fd2a0eb0adf273b4190241cacc0499/ip2location.go#L389-L411
|
test
|
ip2location/ip2location-go
|
ip2location.go
|
Printrecord
|
func Printrecord(x IP2Locationrecord) {
fmt.Printf("country_short: %s\n", x.Country_short)
fmt.Printf("country_long: %s\n", x.Country_long)
fmt.Printf("region: %s\n", x.Region)
fmt.Printf("city: %s\n", x.City)
fmt.Printf("isp: %s\n", x.Isp)
fmt.Printf("latitude: %f\n", x.Latitude)
fmt.Printf("longitude: %f\n", x.Longitude)
fmt.Printf("domain: %s\n", x.Domain)
fmt.Printf("zipcode: %s\n", x.Zipcode)
fmt.Printf("timezone: %s\n", x.Timezone)
fmt.Printf("netspeed: %s\n", x.Netspeed)
fmt.Printf("iddcode: %s\n", x.Iddcode)
fmt.Printf("areacode: %s\n", x.Areacode)
fmt.Printf("weatherstationcode: %s\n", x.Weatherstationcode)
fmt.Printf("weatherstationname: %s\n", x.Weatherstationname)
fmt.Printf("mcc: %s\n", x.Mcc)
fmt.Printf("mnc: %s\n", x.Mnc)
fmt.Printf("mobilebrand: %s\n", x.Mobilebrand)
fmt.Printf("elevation: %f\n", x.Elevation)
fmt.Printf("usagetype: %s\n", x.Usagetype)
}
|
go
|
func Printrecord(x IP2Locationrecord) {
fmt.Printf("country_short: %s\n", x.Country_short)
fmt.Printf("country_long: %s\n", x.Country_long)
fmt.Printf("region: %s\n", x.Region)
fmt.Printf("city: %s\n", x.City)
fmt.Printf("isp: %s\n", x.Isp)
fmt.Printf("latitude: %f\n", x.Latitude)
fmt.Printf("longitude: %f\n", x.Longitude)
fmt.Printf("domain: %s\n", x.Domain)
fmt.Printf("zipcode: %s\n", x.Zipcode)
fmt.Printf("timezone: %s\n", x.Timezone)
fmt.Printf("netspeed: %s\n", x.Netspeed)
fmt.Printf("iddcode: %s\n", x.Iddcode)
fmt.Printf("areacode: %s\n", x.Areacode)
fmt.Printf("weatherstationcode: %s\n", x.Weatherstationcode)
fmt.Printf("weatherstationname: %s\n", x.Weatherstationname)
fmt.Printf("mcc: %s\n", x.Mcc)
fmt.Printf("mnc: %s\n", x.Mnc)
fmt.Printf("mobilebrand: %s\n", x.Mobilebrand)
fmt.Printf("elevation: %f\n", x.Elevation)
fmt.Printf("usagetype: %s\n", x.Usagetype)
}
|
[
"func",
"Printrecord",
"(",
"x",
"IP2Locationrecord",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"country_short: %s\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"Country_short",
"\n",
"fmt",
".",
"Printf",
"(",
"\"country_long: %s\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"Country_long",
"\n",
"fmt",
".",
"Printf",
"(",
"\"region: %s\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"Region",
"\n",
"fmt",
".",
"Printf",
"(",
"\"city: %s\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"City",
"\n",
"fmt",
".",
"Printf",
"(",
"\"isp: %s\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"Isp",
"\n",
"fmt",
".",
"Printf",
"(",
"\"latitude: %f\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"Latitude",
"\n",
"fmt",
".",
"Printf",
"(",
"\"longitude: %f\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"Longitude",
"\n",
"fmt",
".",
"Printf",
"(",
"\"domain: %s\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"Domain",
"\n",
"fmt",
".",
"Printf",
"(",
"\"zipcode: %s\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"Zipcode",
"\n",
"fmt",
".",
"Printf",
"(",
"\"timezone: %s\\n\"",
",",
"\\n",
")",
"\n",
"x",
".",
"Timezone",
"\n",
"}"
] |
// for debugging purposes
|
[
"for",
"debugging",
"purposes"
] |
a417f19539fd2a0eb0adf273b4190241cacc0499
|
https://github.com/ip2location/ip2location-go/blob/a417f19539fd2a0eb0adf273b4190241cacc0499/ip2location.go#L681-L702
|
test
|
llgcode/draw2d
|
samples/gopher/gopher.go
|
Main
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
gc.Save()
gc.Scale(0.5, 0.5)
// Draw a (partial) gopher
Draw(gc)
gc.Restore()
// Return the output filename
return samples.Output("gopher", ext), nil
}
|
go
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
gc.Save()
gc.Scale(0.5, 0.5)
// Draw a (partial) gopher
Draw(gc)
gc.Restore()
// Return the output filename
return samples.Output("gopher", ext), nil
}
|
[
"func",
"Main",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"ext",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"gc",
".",
"Save",
"(",
")",
"\n",
"gc",
".",
"Scale",
"(",
"0.5",
",",
"0.5",
")",
"\n",
"Draw",
"(",
"gc",
")",
"\n",
"gc",
".",
"Restore",
"(",
")",
"\n",
"return",
"samples",
".",
"Output",
"(",
"\"gopher\"",
",",
"ext",
")",
",",
"nil",
"\n",
"}"
] |
// Main draws a left hand and ear of a gopher. Afterwards it returns
// the filename. This should only be used during testing.
|
[
"Main",
"draws",
"a",
"left",
"hand",
"and",
"ear",
"of",
"a",
"gopher",
".",
"Afterwards",
"it",
"returns",
"the",
"filename",
".",
"This",
"should",
"only",
"be",
"used",
"during",
"testing",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/gopher/gopher.go#L17-L26
|
test
|
llgcode/draw2d
|
draw2dpdf/fileutil.go
|
SaveToPdfFile
|
func SaveToPdfFile(filePath string, pdf *gofpdf.Fpdf) error {
return pdf.OutputFileAndClose(filePath)
}
|
go
|
func SaveToPdfFile(filePath string, pdf *gofpdf.Fpdf) error {
return pdf.OutputFileAndClose(filePath)
}
|
[
"func",
"SaveToPdfFile",
"(",
"filePath",
"string",
",",
"pdf",
"*",
"gofpdf",
".",
"Fpdf",
")",
"error",
"{",
"return",
"pdf",
".",
"OutputFileAndClose",
"(",
"filePath",
")",
"\n",
"}"
] |
// SaveToPdfFile creates and saves a pdf document to a file
|
[
"SaveToPdfFile",
"creates",
"and",
"saves",
"a",
"pdf",
"document",
"to",
"a",
"file"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/fileutil.go#L9-L11
|
test
|
llgcode/draw2d
|
path.go
|
CubicCurveTo
|
func (p *Path) CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64) {
if len(p.Components) == 0 { //special case when no move has been done
p.MoveTo(x, y)
} else {
p.appendToPath(CubicCurveToCmp, cx1, cy1, cx2, cy2, x, y)
}
p.x = x
p.y = y
}
|
go
|
func (p *Path) CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64) {
if len(p.Components) == 0 { //special case when no move has been done
p.MoveTo(x, y)
} else {
p.appendToPath(CubicCurveToCmp, cx1, cy1, cx2, cy2, x, y)
}
p.x = x
p.y = y
}
|
[
"func",
"(",
"p",
"*",
"Path",
")",
"CubicCurveTo",
"(",
"cx1",
",",
"cy1",
",",
"cx2",
",",
"cy2",
",",
"x",
",",
"y",
"float64",
")",
"{",
"if",
"len",
"(",
"p",
".",
"Components",
")",
"==",
"0",
"{",
"p",
".",
"MoveTo",
"(",
"x",
",",
"y",
")",
"\n",
"}",
"else",
"{",
"p",
".",
"appendToPath",
"(",
"CubicCurveToCmp",
",",
"cx1",
",",
"cy1",
",",
"cx2",
",",
"cy2",
",",
"x",
",",
"y",
")",
"\n",
"}",
"\n",
"p",
".",
"x",
"=",
"x",
"\n",
"p",
".",
"y",
"=",
"y",
"\n",
"}"
] |
// CubicCurveTo adds a cubic bezier curve to the current path
|
[
"CubicCurveTo",
"adds",
"a",
"cubic",
"bezier",
"curve",
"to",
"the",
"current",
"path"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/path.go#L99-L107
|
test
|
llgcode/draw2d
|
path.go
|
ArcTo
|
func (p *Path) ArcTo(cx, cy, rx, ry, startAngle, angle float64) {
endAngle := startAngle + angle
clockWise := true
if angle < 0 {
clockWise = false
}
// normalize
if clockWise {
for endAngle < startAngle {
endAngle += math.Pi * 2.0
}
} else {
for startAngle < endAngle {
startAngle += math.Pi * 2.0
}
}
startX := cx + math.Cos(startAngle)*rx
startY := cy + math.Sin(startAngle)*ry
if len(p.Components) > 0 {
p.LineTo(startX, startY)
} else {
p.MoveTo(startX, startY)
}
p.appendToPath(ArcToCmp, cx, cy, rx, ry, startAngle, angle)
p.x = cx + math.Cos(endAngle)*rx
p.y = cy + math.Sin(endAngle)*ry
}
|
go
|
func (p *Path) ArcTo(cx, cy, rx, ry, startAngle, angle float64) {
endAngle := startAngle + angle
clockWise := true
if angle < 0 {
clockWise = false
}
// normalize
if clockWise {
for endAngle < startAngle {
endAngle += math.Pi * 2.0
}
} else {
for startAngle < endAngle {
startAngle += math.Pi * 2.0
}
}
startX := cx + math.Cos(startAngle)*rx
startY := cy + math.Sin(startAngle)*ry
if len(p.Components) > 0 {
p.LineTo(startX, startY)
} else {
p.MoveTo(startX, startY)
}
p.appendToPath(ArcToCmp, cx, cy, rx, ry, startAngle, angle)
p.x = cx + math.Cos(endAngle)*rx
p.y = cy + math.Sin(endAngle)*ry
}
|
[
"func",
"(",
"p",
"*",
"Path",
")",
"ArcTo",
"(",
"cx",
",",
"cy",
",",
"rx",
",",
"ry",
",",
"startAngle",
",",
"angle",
"float64",
")",
"{",
"endAngle",
":=",
"startAngle",
"+",
"angle",
"\n",
"clockWise",
":=",
"true",
"\n",
"if",
"angle",
"<",
"0",
"{",
"clockWise",
"=",
"false",
"\n",
"}",
"\n",
"if",
"clockWise",
"{",
"for",
"endAngle",
"<",
"startAngle",
"{",
"endAngle",
"+=",
"math",
".",
"Pi",
"*",
"2.0",
"\n",
"}",
"\n",
"}",
"else",
"{",
"for",
"startAngle",
"<",
"endAngle",
"{",
"startAngle",
"+=",
"math",
".",
"Pi",
"*",
"2.0",
"\n",
"}",
"\n",
"}",
"\n",
"startX",
":=",
"cx",
"+",
"math",
".",
"Cos",
"(",
"startAngle",
")",
"*",
"rx",
"\n",
"startY",
":=",
"cy",
"+",
"math",
".",
"Sin",
"(",
"startAngle",
")",
"*",
"ry",
"\n",
"if",
"len",
"(",
"p",
".",
"Components",
")",
">",
"0",
"{",
"p",
".",
"LineTo",
"(",
"startX",
",",
"startY",
")",
"\n",
"}",
"else",
"{",
"p",
".",
"MoveTo",
"(",
"startX",
",",
"startY",
")",
"\n",
"}",
"\n",
"p",
".",
"appendToPath",
"(",
"ArcToCmp",
",",
"cx",
",",
"cy",
",",
"rx",
",",
"ry",
",",
"startAngle",
",",
"angle",
")",
"\n",
"p",
".",
"x",
"=",
"cx",
"+",
"math",
".",
"Cos",
"(",
"endAngle",
")",
"*",
"rx",
"\n",
"p",
".",
"y",
"=",
"cy",
"+",
"math",
".",
"Sin",
"(",
"endAngle",
")",
"*",
"ry",
"\n",
"}"
] |
// ArcTo adds an arc to the path
|
[
"ArcTo",
"adds",
"an",
"arc",
"to",
"the",
"path"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/path.go#L110-L136
|
test
|
llgcode/draw2d
|
path.go
|
String
|
func (p *Path) String() string {
s := ""
j := 0
for _, cmd := range p.Components {
switch cmd {
case MoveToCmp:
s += fmt.Sprintf("MoveTo: %f, %f\n", p.Points[j], p.Points[j+1])
j = j + 2
case LineToCmp:
s += fmt.Sprintf("LineTo: %f, %f\n", p.Points[j], p.Points[j+1])
j = j + 2
case QuadCurveToCmp:
s += fmt.Sprintf("QuadCurveTo: %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3])
j = j + 4
case CubicCurveToCmp:
s += fmt.Sprintf("CubicCurveTo: %f, %f, %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3], p.Points[j+4], p.Points[j+5])
j = j + 6
case ArcToCmp:
s += fmt.Sprintf("ArcTo: %f, %f, %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3], p.Points[j+4], p.Points[j+5])
j = j + 6
case CloseCmp:
s += "Close\n"
}
}
return s
}
|
go
|
func (p *Path) String() string {
s := ""
j := 0
for _, cmd := range p.Components {
switch cmd {
case MoveToCmp:
s += fmt.Sprintf("MoveTo: %f, %f\n", p.Points[j], p.Points[j+1])
j = j + 2
case LineToCmp:
s += fmt.Sprintf("LineTo: %f, %f\n", p.Points[j], p.Points[j+1])
j = j + 2
case QuadCurveToCmp:
s += fmt.Sprintf("QuadCurveTo: %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3])
j = j + 4
case CubicCurveToCmp:
s += fmt.Sprintf("CubicCurveTo: %f, %f, %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3], p.Points[j+4], p.Points[j+5])
j = j + 6
case ArcToCmp:
s += fmt.Sprintf("ArcTo: %f, %f, %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3], p.Points[j+4], p.Points[j+5])
j = j + 6
case CloseCmp:
s += "Close\n"
}
}
return s
}
|
[
"func",
"(",
"p",
"*",
"Path",
")",
"String",
"(",
")",
"string",
"{",
"s",
":=",
"\"\"",
"\n",
"j",
":=",
"0",
"\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"p",
".",
"Components",
"{",
"switch",
"cmd",
"{",
"case",
"MoveToCmp",
":",
"s",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"MoveTo: %f, %f\\n\"",
",",
"\\n",
",",
"p",
".",
"Points",
"[",
"j",
"]",
")",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"\n",
"j",
"=",
"j",
"+",
"2",
"case",
"LineToCmp",
":",
"s",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"LineTo: %f, %f\\n\"",
",",
"\\n",
",",
"p",
".",
"Points",
"[",
"j",
"]",
")",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"\n",
"j",
"=",
"j",
"+",
"2",
"case",
"QuadCurveToCmp",
":",
"s",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"QuadCurveTo: %f, %f, %f, %f\\n\"",
",",
"\\n",
",",
"p",
".",
"Points",
"[",
"j",
"]",
",",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
",",
"p",
".",
"Points",
"[",
"j",
"+",
"2",
"]",
")",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"3",
"]",
"\n",
"j",
"=",
"j",
"+",
"4",
"}",
"\n",
"}",
"\n",
"case",
"CubicCurveToCmp",
":",
"s",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"CubicCurveTo: %f, %f, %f, %f, %f, %f\\n\"",
",",
"\\n",
",",
"p",
".",
"Points",
"[",
"j",
"]",
",",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
",",
"p",
".",
"Points",
"[",
"j",
"+",
"2",
"]",
",",
"p",
".",
"Points",
"[",
"j",
"+",
"3",
"]",
",",
"p",
".",
"Points",
"[",
"j",
"+",
"4",
"]",
")",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"5",
"]",
"\n",
"\n",
"}"
] |
// String returns a debug text view of the path
|
[
"String",
"returns",
"a",
"debug",
"text",
"view",
"of",
"the",
"path"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/path.go#L167-L192
|
test
|
llgcode/draw2d
|
path.go
|
VerticalFlip
|
func (path *Path) VerticalFlip() *Path {
p := path.Copy()
j := 0
for _, cmd := range p.Components {
switch cmd {
case MoveToCmp, LineToCmp:
p.Points[j+1] = -p.Points[j+1]
j = j + 2
case QuadCurveToCmp:
p.Points[j+1] = -p.Points[j+1]
p.Points[j+3] = -p.Points[j+3]
j = j + 4
case CubicCurveToCmp:
p.Points[j+1] = -p.Points[j+1]
p.Points[j+3] = -p.Points[j+3]
p.Points[j+5] = -p.Points[j+5]
j = j + 6
case ArcToCmp:
p.Points[j+1] = -p.Points[j+1]
p.Points[j+3] = -p.Points[j+3]
p.Points[j+4] = -p.Points[j+4] // start angle
p.Points[j+5] = -p.Points[j+5] // angle
j = j + 6
case CloseCmp:
}
}
p.y = -p.y
return p
}
|
go
|
func (path *Path) VerticalFlip() *Path {
p := path.Copy()
j := 0
for _, cmd := range p.Components {
switch cmd {
case MoveToCmp, LineToCmp:
p.Points[j+1] = -p.Points[j+1]
j = j + 2
case QuadCurveToCmp:
p.Points[j+1] = -p.Points[j+1]
p.Points[j+3] = -p.Points[j+3]
j = j + 4
case CubicCurveToCmp:
p.Points[j+1] = -p.Points[j+1]
p.Points[j+3] = -p.Points[j+3]
p.Points[j+5] = -p.Points[j+5]
j = j + 6
case ArcToCmp:
p.Points[j+1] = -p.Points[j+1]
p.Points[j+3] = -p.Points[j+3]
p.Points[j+4] = -p.Points[j+4] // start angle
p.Points[j+5] = -p.Points[j+5] // angle
j = j + 6
case CloseCmp:
}
}
p.y = -p.y
return p
}
|
[
"func",
"(",
"path",
"*",
"Path",
")",
"VerticalFlip",
"(",
")",
"*",
"Path",
"{",
"p",
":=",
"path",
".",
"Copy",
"(",
")",
"\n",
"j",
":=",
"0",
"\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"p",
".",
"Components",
"{",
"switch",
"cmd",
"{",
"case",
"MoveToCmp",
",",
"LineToCmp",
":",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"\n",
"j",
"=",
"j",
"+",
"2",
"\n",
"case",
"QuadCurveToCmp",
":",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"3",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"3",
"]",
"\n",
"j",
"=",
"j",
"+",
"4",
"\n",
"case",
"CubicCurveToCmp",
":",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"3",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"3",
"]",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"5",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"5",
"]",
"\n",
"j",
"=",
"j",
"+",
"6",
"\n",
"case",
"ArcToCmp",
":",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"1",
"]",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"3",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"3",
"]",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"4",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"4",
"]",
"\n",
"p",
".",
"Points",
"[",
"j",
"+",
"5",
"]",
"=",
"-",
"p",
".",
"Points",
"[",
"j",
"+",
"5",
"]",
"\n",
"j",
"=",
"j",
"+",
"6",
"\n",
"case",
"CloseCmp",
":",
"}",
"\n",
"}",
"\n",
"p",
".",
"y",
"=",
"-",
"p",
".",
"y",
"\n",
"return",
"p",
"\n",
"}"
] |
// Returns new Path with flipped y axes
|
[
"Returns",
"new",
"Path",
"with",
"flipped",
"y",
"axes"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/path.go#L195-L223
|
test
|
llgcode/draw2d
|
draw2dbase/text.go
|
NewGlyphCache
|
func NewGlyphCache() *GlyphCacheImp {
glyphs := make(map[string]map[rune]*Glyph)
return &GlyphCacheImp {
glyphs: glyphs,
}
}
|
go
|
func NewGlyphCache() *GlyphCacheImp {
glyphs := make(map[string]map[rune]*Glyph)
return &GlyphCacheImp {
glyphs: glyphs,
}
}
|
[
"func",
"NewGlyphCache",
"(",
")",
"*",
"GlyphCacheImp",
"{",
"glyphs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"rune",
"]",
"*",
"Glyph",
")",
"\n",
"return",
"&",
"GlyphCacheImp",
"{",
"glyphs",
":",
"glyphs",
",",
"}",
"\n",
"}"
] |
// NewGlyphCache initializes a GlyphCache
|
[
"NewGlyphCache",
"initializes",
"a",
"GlyphCache"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/text.go#L18-L23
|
test
|
llgcode/draw2d
|
draw2dbase/text.go
|
Fetch
|
func (glyphCache *GlyphCacheImp) Fetch(gc draw2d.GraphicContext, fontName string, chr rune) *Glyph {
if glyphCache.glyphs[fontName] == nil {
glyphCache.glyphs[fontName] = make(map[rune]*Glyph, 60)
}
if glyphCache.glyphs[fontName][chr] == nil {
glyphCache.glyphs[fontName][chr] = renderGlyph(gc, fontName, chr)
}
return glyphCache.glyphs[fontName][chr].Copy()
}
|
go
|
func (glyphCache *GlyphCacheImp) Fetch(gc draw2d.GraphicContext, fontName string, chr rune) *Glyph {
if glyphCache.glyphs[fontName] == nil {
glyphCache.glyphs[fontName] = make(map[rune]*Glyph, 60)
}
if glyphCache.glyphs[fontName][chr] == nil {
glyphCache.glyphs[fontName][chr] = renderGlyph(gc, fontName, chr)
}
return glyphCache.glyphs[fontName][chr].Copy()
}
|
[
"func",
"(",
"glyphCache",
"*",
"GlyphCacheImp",
")",
"Fetch",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"fontName",
"string",
",",
"chr",
"rune",
")",
"*",
"Glyph",
"{",
"if",
"glyphCache",
".",
"glyphs",
"[",
"fontName",
"]",
"==",
"nil",
"{",
"glyphCache",
".",
"glyphs",
"[",
"fontName",
"]",
"=",
"make",
"(",
"map",
"[",
"rune",
"]",
"*",
"Glyph",
",",
"60",
")",
"\n",
"}",
"\n",
"if",
"glyphCache",
".",
"glyphs",
"[",
"fontName",
"]",
"[",
"chr",
"]",
"==",
"nil",
"{",
"glyphCache",
".",
"glyphs",
"[",
"fontName",
"]",
"[",
"chr",
"]",
"=",
"renderGlyph",
"(",
"gc",
",",
"fontName",
",",
"chr",
")",
"\n",
"}",
"\n",
"return",
"glyphCache",
".",
"glyphs",
"[",
"fontName",
"]",
"[",
"chr",
"]",
".",
"Copy",
"(",
")",
"\n",
"}"
] |
// Fetch fetches a glyph from the cache, calling renderGlyph first if it doesn't already exist
|
[
"Fetch",
"fetches",
"a",
"glyph",
"from",
"the",
"cache",
"calling",
"renderGlyph",
"first",
"if",
"it",
"doesn",
"t",
"already",
"exist"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/text.go#L26-L34
|
test
|
llgcode/draw2d
|
draw2dbase/text.go
|
renderGlyph
|
func renderGlyph(gc draw2d.GraphicContext, fontName string, chr rune) *Glyph {
gc.Save()
defer gc.Restore()
gc.BeginPath()
width := gc.CreateStringPath(string(chr), 0, 0)
path := gc.GetPath()
return &Glyph{
Path: &path,
Width: width,
}
}
|
go
|
func renderGlyph(gc draw2d.GraphicContext, fontName string, chr rune) *Glyph {
gc.Save()
defer gc.Restore()
gc.BeginPath()
width := gc.CreateStringPath(string(chr), 0, 0)
path := gc.GetPath()
return &Glyph{
Path: &path,
Width: width,
}
}
|
[
"func",
"renderGlyph",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"fontName",
"string",
",",
"chr",
"rune",
")",
"*",
"Glyph",
"{",
"gc",
".",
"Save",
"(",
")",
"\n",
"defer",
"gc",
".",
"Restore",
"(",
")",
"\n",
"gc",
".",
"BeginPath",
"(",
")",
"\n",
"width",
":=",
"gc",
".",
"CreateStringPath",
"(",
"string",
"(",
"chr",
")",
",",
"0",
",",
"0",
")",
"\n",
"path",
":=",
"gc",
".",
"GetPath",
"(",
")",
"\n",
"return",
"&",
"Glyph",
"{",
"Path",
":",
"&",
"path",
",",
"Width",
":",
"width",
",",
"}",
"\n",
"}"
] |
// renderGlyph renders a glyph then caches and returns it
|
[
"renderGlyph",
"renders",
"a",
"glyph",
"then",
"caches",
"and",
"returns",
"it"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/text.go#L37-L47
|
test
|
llgcode/draw2d
|
draw2dbase/text.go
|
Copy
|
func (g *Glyph) Copy() *Glyph {
return &Glyph{
Path: g.Path.Copy(),
Width: g.Width,
}
}
|
go
|
func (g *Glyph) Copy() *Glyph {
return &Glyph{
Path: g.Path.Copy(),
Width: g.Width,
}
}
|
[
"func",
"(",
"g",
"*",
"Glyph",
")",
"Copy",
"(",
")",
"*",
"Glyph",
"{",
"return",
"&",
"Glyph",
"{",
"Path",
":",
"g",
".",
"Path",
".",
"Copy",
"(",
")",
",",
"Width",
":",
"g",
".",
"Width",
",",
"}",
"\n",
"}"
] |
// Copy Returns a copy of a Glyph
|
[
"Copy",
"Returns",
"a",
"copy",
"of",
"a",
"Glyph"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/text.go#L58-L63
|
test
|
llgcode/draw2d
|
draw2dbase/text.go
|
Fill
|
func (g *Glyph) Fill(gc draw2d.GraphicContext, x, y float64) float64 {
gc.Save()
gc.BeginPath()
gc.Translate(x, y)
gc.Fill(g.Path)
gc.Restore()
return g.Width
}
|
go
|
func (g *Glyph) Fill(gc draw2d.GraphicContext, x, y float64) float64 {
gc.Save()
gc.BeginPath()
gc.Translate(x, y)
gc.Fill(g.Path)
gc.Restore()
return g.Width
}
|
[
"func",
"(",
"g",
"*",
"Glyph",
")",
"Fill",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"x",
",",
"y",
"float64",
")",
"float64",
"{",
"gc",
".",
"Save",
"(",
")",
"\n",
"gc",
".",
"BeginPath",
"(",
")",
"\n",
"gc",
".",
"Translate",
"(",
"x",
",",
"y",
")",
"\n",
"gc",
".",
"Fill",
"(",
"g",
".",
"Path",
")",
"\n",
"gc",
".",
"Restore",
"(",
")",
"\n",
"return",
"g",
".",
"Width",
"\n",
"}"
] |
// Fill copies a glyph from the cache, and fills it
|
[
"Fill",
"copies",
"a",
"glyph",
"from",
"the",
"cache",
"and",
"fills",
"it"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/text.go#L66-L73
|
test
|
llgcode/draw2d
|
samples/line/line.go
|
Main
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
gc.SetFillRule(draw2d.FillRuleWinding)
gc.Clear()
// Draw the line
for x := 5.0; x < 297; x += 10 {
Draw(gc, x, 0, x, 210)
}
gc.ClearRect(100, 75, 197, 135)
draw2dkit.Ellipse(gc, 148.5, 105, 35, 25)
gc.SetFillColor(color.RGBA{0xff, 0xff, 0x44, 0xff})
gc.FillStroke()
// Return the output filename
return samples.Output("line", ext), nil
}
|
go
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
gc.SetFillRule(draw2d.FillRuleWinding)
gc.Clear()
// Draw the line
for x := 5.0; x < 297; x += 10 {
Draw(gc, x, 0, x, 210)
}
gc.ClearRect(100, 75, 197, 135)
draw2dkit.Ellipse(gc, 148.5, 105, 35, 25)
gc.SetFillColor(color.RGBA{0xff, 0xff, 0x44, 0xff})
gc.FillStroke()
// Return the output filename
return samples.Output("line", ext), nil
}
|
[
"func",
"Main",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"ext",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"gc",
".",
"SetFillRule",
"(",
"draw2d",
".",
"FillRuleWinding",
")",
"\n",
"gc",
".",
"Clear",
"(",
")",
"\n",
"for",
"x",
":=",
"5.0",
";",
"x",
"<",
"297",
";",
"x",
"+=",
"10",
"{",
"Draw",
"(",
"gc",
",",
"x",
",",
"0",
",",
"x",
",",
"210",
")",
"\n",
"}",
"\n",
"gc",
".",
"ClearRect",
"(",
"100",
",",
"75",
",",
"197",
",",
"135",
")",
"\n",
"draw2dkit",
".",
"Ellipse",
"(",
"gc",
",",
"148.5",
",",
"105",
",",
"35",
",",
"25",
")",
"\n",
"gc",
".",
"SetFillColor",
"(",
"color",
".",
"RGBA",
"{",
"0xff",
",",
"0xff",
",",
"0x44",
",",
"0xff",
"}",
")",
"\n",
"gc",
".",
"FillStroke",
"(",
")",
"\n",
"return",
"samples",
".",
"Output",
"(",
"\"line\"",
",",
"ext",
")",
",",
"nil",
"\n",
"}"
] |
// Main draws vertically spaced lines and returns the filename.
// This should only be used during testing.
|
[
"Main",
"draws",
"vertically",
"spaced",
"lines",
"and",
"returns",
"the",
"filename",
".",
"This",
"should",
"only",
"be",
"used",
"during",
"testing",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/line/line.go#L17-L31
|
test
|
llgcode/draw2d
|
samples/line/line.go
|
Draw
|
func Draw(gc draw2d.GraphicContext, x0, y0, x1, y1 float64) {
// Draw a line
gc.MoveTo(x0, y0)
gc.LineTo(x1, y1)
gc.Stroke()
}
|
go
|
func Draw(gc draw2d.GraphicContext, x0, y0, x1, y1 float64) {
// Draw a line
gc.MoveTo(x0, y0)
gc.LineTo(x1, y1)
gc.Stroke()
}
|
[
"func",
"Draw",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
"float64",
")",
"{",
"gc",
".",
"MoveTo",
"(",
"x0",
",",
"y0",
")",
"\n",
"gc",
".",
"LineTo",
"(",
"x1",
",",
"y1",
")",
"\n",
"gc",
".",
"Stroke",
"(",
")",
"\n",
"}"
] |
// Draw vertically spaced lines
|
[
"Draw",
"vertically",
"spaced",
"lines"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/line/line.go#L34-L39
|
test
|
llgcode/draw2d
|
draw2dgl/gc.go
|
Paint
|
func (p *Painter) Paint(ss []raster.Span, done bool) {
//gl.Begin(gl.LINES)
sslen := len(ss)
clenrequired := sslen * 8
vlenrequired := sslen * 4
if clenrequired >= (cap(p.colors) - len(p.colors)) {
p.Flush()
if clenrequired >= cap(p.colors) {
p.vertices = make([]int32, 0, vlenrequired+(vlenrequired/2))
p.colors = make([]uint8, 0, clenrequired+(clenrequired/2))
}
}
vi := len(p.vertices)
ci := len(p.colors)
p.vertices = p.vertices[0 : vi+vlenrequired]
p.colors = p.colors[0 : ci+clenrequired]
var (
colors []uint8
vertices []int32
)
for _, s := range ss {
a := uint8((s.Alpha * p.ca / M16) >> 8)
colors = p.colors[ci:]
colors[0] = p.cr
colors[1] = p.cg
colors[2] = p.cb
colors[3] = a
colors[4] = p.cr
colors[5] = p.cg
colors[6] = p.cb
colors[7] = a
ci += 8
vertices = p.vertices[vi:]
vertices[0] = int32(s.X0)
vertices[1] = int32(s.Y)
vertices[2] = int32(s.X1)
vertices[3] = int32(s.Y)
vi += 4
}
}
|
go
|
func (p *Painter) Paint(ss []raster.Span, done bool) {
//gl.Begin(gl.LINES)
sslen := len(ss)
clenrequired := sslen * 8
vlenrequired := sslen * 4
if clenrequired >= (cap(p.colors) - len(p.colors)) {
p.Flush()
if clenrequired >= cap(p.colors) {
p.vertices = make([]int32, 0, vlenrequired+(vlenrequired/2))
p.colors = make([]uint8, 0, clenrequired+(clenrequired/2))
}
}
vi := len(p.vertices)
ci := len(p.colors)
p.vertices = p.vertices[0 : vi+vlenrequired]
p.colors = p.colors[0 : ci+clenrequired]
var (
colors []uint8
vertices []int32
)
for _, s := range ss {
a := uint8((s.Alpha * p.ca / M16) >> 8)
colors = p.colors[ci:]
colors[0] = p.cr
colors[1] = p.cg
colors[2] = p.cb
colors[3] = a
colors[4] = p.cr
colors[5] = p.cg
colors[6] = p.cb
colors[7] = a
ci += 8
vertices = p.vertices[vi:]
vertices[0] = int32(s.X0)
vertices[1] = int32(s.Y)
vertices[2] = int32(s.X1)
vertices[3] = int32(s.Y)
vi += 4
}
}
|
[
"func",
"(",
"p",
"*",
"Painter",
")",
"Paint",
"(",
"ss",
"[",
"]",
"raster",
".",
"Span",
",",
"done",
"bool",
")",
"{",
"sslen",
":=",
"len",
"(",
"ss",
")",
"\n",
"clenrequired",
":=",
"sslen",
"*",
"8",
"\n",
"vlenrequired",
":=",
"sslen",
"*",
"4",
"\n",
"if",
"clenrequired",
">=",
"(",
"cap",
"(",
"p",
".",
"colors",
")",
"-",
"len",
"(",
"p",
".",
"colors",
")",
")",
"{",
"p",
".",
"Flush",
"(",
")",
"\n",
"if",
"clenrequired",
">=",
"cap",
"(",
"p",
".",
"colors",
")",
"{",
"p",
".",
"vertices",
"=",
"make",
"(",
"[",
"]",
"int32",
",",
"0",
",",
"vlenrequired",
"+",
"(",
"vlenrequired",
"/",
"2",
")",
")",
"\n",
"p",
".",
"colors",
"=",
"make",
"(",
"[",
"]",
"uint8",
",",
"0",
",",
"clenrequired",
"+",
"(",
"clenrequired",
"/",
"2",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"vi",
":=",
"len",
"(",
"p",
".",
"vertices",
")",
"\n",
"ci",
":=",
"len",
"(",
"p",
".",
"colors",
")",
"\n",
"p",
".",
"vertices",
"=",
"p",
".",
"vertices",
"[",
"0",
":",
"vi",
"+",
"vlenrequired",
"]",
"\n",
"p",
".",
"colors",
"=",
"p",
".",
"colors",
"[",
"0",
":",
"ci",
"+",
"clenrequired",
"]",
"\n",
"var",
"(",
"colors",
"[",
"]",
"uint8",
"\n",
"vertices",
"[",
"]",
"int32",
"\n",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"ss",
"{",
"a",
":=",
"uint8",
"(",
"(",
"s",
".",
"Alpha",
"*",
"p",
".",
"ca",
"/",
"M16",
")",
">>",
"8",
")",
"\n",
"colors",
"=",
"p",
".",
"colors",
"[",
"ci",
":",
"]",
"\n",
"colors",
"[",
"0",
"]",
"=",
"p",
".",
"cr",
"\n",
"colors",
"[",
"1",
"]",
"=",
"p",
".",
"cg",
"\n",
"colors",
"[",
"2",
"]",
"=",
"p",
".",
"cb",
"\n",
"colors",
"[",
"3",
"]",
"=",
"a",
"\n",
"colors",
"[",
"4",
"]",
"=",
"p",
".",
"cr",
"\n",
"colors",
"[",
"5",
"]",
"=",
"p",
".",
"cg",
"\n",
"colors",
"[",
"6",
"]",
"=",
"p",
".",
"cb",
"\n",
"colors",
"[",
"7",
"]",
"=",
"a",
"\n",
"ci",
"+=",
"8",
"\n",
"vertices",
"=",
"p",
".",
"vertices",
"[",
"vi",
":",
"]",
"\n",
"vertices",
"[",
"0",
"]",
"=",
"int32",
"(",
"s",
".",
"X0",
")",
"\n",
"vertices",
"[",
"1",
"]",
"=",
"int32",
"(",
"s",
".",
"Y",
")",
"\n",
"vertices",
"[",
"2",
"]",
"=",
"int32",
"(",
"s",
".",
"X1",
")",
"\n",
"vertices",
"[",
"3",
"]",
"=",
"int32",
"(",
"s",
".",
"Y",
")",
"\n",
"vi",
"+=",
"4",
"\n",
"}",
"\n",
"}"
] |
// Paint satisfies the Painter interface by painting ss onto an image.RGBA.
|
[
"Paint",
"satisfies",
"the",
"Painter",
"interface",
"by",
"painting",
"ss",
"onto",
"an",
"image",
".",
"RGBA",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L39-L80
|
test
|
llgcode/draw2d
|
draw2dgl/gc.go
|
SetColor
|
func (p *Painter) SetColor(c color.Color) {
r, g, b, a := c.RGBA()
if a == 0 {
p.cr = 0
p.cg = 0
p.cb = 0
p.ca = a
} else {
p.cr = uint8((r * M16 / a) >> 8)
p.cg = uint8((g * M16 / a) >> 8)
p.cb = uint8((b * M16 / a) >> 8)
p.ca = a
}
}
|
go
|
func (p *Painter) SetColor(c color.Color) {
r, g, b, a := c.RGBA()
if a == 0 {
p.cr = 0
p.cg = 0
p.cb = 0
p.ca = a
} else {
p.cr = uint8((r * M16 / a) >> 8)
p.cg = uint8((g * M16 / a) >> 8)
p.cb = uint8((b * M16 / a) >> 8)
p.ca = a
}
}
|
[
"func",
"(",
"p",
"*",
"Painter",
")",
"SetColor",
"(",
"c",
"color",
".",
"Color",
")",
"{",
"r",
",",
"g",
",",
"b",
",",
"a",
":=",
"c",
".",
"RGBA",
"(",
")",
"\n",
"if",
"a",
"==",
"0",
"{",
"p",
".",
"cr",
"=",
"0",
"\n",
"p",
".",
"cg",
"=",
"0",
"\n",
"p",
".",
"cb",
"=",
"0",
"\n",
"p",
".",
"ca",
"=",
"a",
"\n",
"}",
"else",
"{",
"p",
".",
"cr",
"=",
"uint8",
"(",
"(",
"r",
"*",
"M16",
"/",
"a",
")",
">>",
"8",
")",
"\n",
"p",
".",
"cg",
"=",
"uint8",
"(",
"(",
"g",
"*",
"M16",
"/",
"a",
")",
">>",
"8",
")",
"\n",
"p",
".",
"cb",
"=",
"uint8",
"(",
"(",
"b",
"*",
"M16",
"/",
"a",
")",
">>",
"8",
")",
"\n",
"p",
".",
"ca",
"=",
"a",
"\n",
"}",
"\n",
"}"
] |
// SetColor sets the color to paint the spans.
|
[
"SetColor",
"sets",
"the",
"color",
"to",
"paint",
"the",
"spans",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L99-L112
|
test
|
llgcode/draw2d
|
draw2dgl/gc.go
|
NewPainter
|
func NewPainter() *Painter {
p := new(Painter)
p.vertices = make([]int32, 0, 1024)
p.colors = make([]uint8, 0, 1024)
return p
}
|
go
|
func NewPainter() *Painter {
p := new(Painter)
p.vertices = make([]int32, 0, 1024)
p.colors = make([]uint8, 0, 1024)
return p
}
|
[
"func",
"NewPainter",
"(",
")",
"*",
"Painter",
"{",
"p",
":=",
"new",
"(",
"Painter",
")",
"\n",
"p",
".",
"vertices",
"=",
"make",
"(",
"[",
"]",
"int32",
",",
"0",
",",
"1024",
")",
"\n",
"p",
".",
"colors",
"=",
"make",
"(",
"[",
"]",
"uint8",
",",
"0",
",",
"1024",
")",
"\n",
"return",
"p",
"\n",
"}"
] |
// NewRGBAPainter creates a new RGBAPainter for the given image.
|
[
"NewRGBAPainter",
"creates",
"a",
"new",
"RGBAPainter",
"for",
"the",
"given",
"image",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L115-L120
|
test
|
llgcode/draw2d
|
draw2dgl/gc.go
|
GetStringBounds
|
func (gc *GraphicContext) GetStringBounds(s string) (left, top, right, bottom float64) {
f, err := gc.loadCurrentFont()
if err != nil {
log.Println(err)
return 0, 0, 0, 0
}
top, left, bottom, right = 10e6, 10e6, -10e6, -10e6
cursor := 0.0
prev, hasPrev := truetype.Index(0), false
for _, rune := range s {
index := f.Index(rune)
if hasPrev {
cursor += fUnitsToFloat64(f.Kern(fixed.Int26_6(gc.Current.Scale), prev, index))
}
if err := gc.glyphBuf.Load(gc.Current.Font, fixed.Int26_6(gc.Current.Scale), index, font.HintingNone); err != nil {
log.Println(err)
return 0, 0, 0, 0
}
e0 := 0
for _, e1 := range gc.glyphBuf.Ends {
ps := gc.glyphBuf.Points[e0:e1]
for _, p := range ps {
x, y := pointToF64Point(p)
top = math.Min(top, y)
bottom = math.Max(bottom, y)
left = math.Min(left, x+cursor)
right = math.Max(right, x+cursor)
}
}
cursor += fUnitsToFloat64(f.HMetric(fixed.Int26_6(gc.Current.Scale), index).AdvanceWidth)
prev, hasPrev = index, true
}
return left, top, right, bottom
}
|
go
|
func (gc *GraphicContext) GetStringBounds(s string) (left, top, right, bottom float64) {
f, err := gc.loadCurrentFont()
if err != nil {
log.Println(err)
return 0, 0, 0, 0
}
top, left, bottom, right = 10e6, 10e6, -10e6, -10e6
cursor := 0.0
prev, hasPrev := truetype.Index(0), false
for _, rune := range s {
index := f.Index(rune)
if hasPrev {
cursor += fUnitsToFloat64(f.Kern(fixed.Int26_6(gc.Current.Scale), prev, index))
}
if err := gc.glyphBuf.Load(gc.Current.Font, fixed.Int26_6(gc.Current.Scale), index, font.HintingNone); err != nil {
log.Println(err)
return 0, 0, 0, 0
}
e0 := 0
for _, e1 := range gc.glyphBuf.Ends {
ps := gc.glyphBuf.Points[e0:e1]
for _, p := range ps {
x, y := pointToF64Point(p)
top = math.Min(top, y)
bottom = math.Max(bottom, y)
left = math.Min(left, x+cursor)
right = math.Max(right, x+cursor)
}
}
cursor += fUnitsToFloat64(f.HMetric(fixed.Int26_6(gc.Current.Scale), index).AdvanceWidth)
prev, hasPrev = index, true
}
return left, top, right, bottom
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"GetStringBounds",
"(",
"s",
"string",
")",
"(",
"left",
",",
"top",
",",
"right",
",",
"bottom",
"float64",
")",
"{",
"f",
",",
"err",
":=",
"gc",
".",
"loadCurrentFont",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"err",
")",
"\n",
"return",
"0",
",",
"0",
",",
"0",
",",
"0",
"\n",
"}",
"\n",
"top",
",",
"left",
",",
"bottom",
",",
"right",
"=",
"10e6",
",",
"10e6",
",",
"-",
"10e6",
",",
"-",
"10e6",
"\n",
"cursor",
":=",
"0.0",
"\n",
"prev",
",",
"hasPrev",
":=",
"truetype",
".",
"Index",
"(",
"0",
")",
",",
"false",
"\n",
"for",
"_",
",",
"rune",
":=",
"range",
"s",
"{",
"index",
":=",
"f",
".",
"Index",
"(",
"rune",
")",
"\n",
"if",
"hasPrev",
"{",
"cursor",
"+=",
"fUnitsToFloat64",
"(",
"f",
".",
"Kern",
"(",
"fixed",
".",
"Int26_6",
"(",
"gc",
".",
"Current",
".",
"Scale",
")",
",",
"prev",
",",
"index",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"gc",
".",
"glyphBuf",
".",
"Load",
"(",
"gc",
".",
"Current",
".",
"Font",
",",
"fixed",
".",
"Int26_6",
"(",
"gc",
".",
"Current",
".",
"Scale",
")",
",",
"index",
",",
"font",
".",
"HintingNone",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"err",
")",
"\n",
"return",
"0",
",",
"0",
",",
"0",
",",
"0",
"\n",
"}",
"\n",
"e0",
":=",
"0",
"\n",
"for",
"_",
",",
"e1",
":=",
"range",
"gc",
".",
"glyphBuf",
".",
"Ends",
"{",
"ps",
":=",
"gc",
".",
"glyphBuf",
".",
"Points",
"[",
"e0",
":",
"e1",
"]",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"ps",
"{",
"x",
",",
"y",
":=",
"pointToF64Point",
"(",
"p",
")",
"\n",
"top",
"=",
"math",
".",
"Min",
"(",
"top",
",",
"y",
")",
"\n",
"bottom",
"=",
"math",
".",
"Max",
"(",
"bottom",
",",
"y",
")",
"\n",
"left",
"=",
"math",
".",
"Min",
"(",
"left",
",",
"x",
"+",
"cursor",
")",
"\n",
"right",
"=",
"math",
".",
"Max",
"(",
"right",
",",
"x",
"+",
"cursor",
")",
"\n",
"}",
"\n",
"}",
"\n",
"cursor",
"+=",
"fUnitsToFloat64",
"(",
"f",
".",
"HMetric",
"(",
"fixed",
".",
"Int26_6",
"(",
"gc",
".",
"Current",
".",
"Scale",
")",
",",
"index",
")",
".",
"AdvanceWidth",
")",
"\n",
"prev",
",",
"hasPrev",
"=",
"index",
",",
"true",
"\n",
"}",
"\n",
"return",
"left",
",",
"top",
",",
"right",
",",
"bottom",
"\n",
"}"
] |
// GetStringBounds returns the approximate pixel bounds of the string s at x, y.
// The the left edge of the em square of the first character of s
// and the baseline intersect at 0, 0 in the returned coordinates.
// Therefore the top and left coordinates may well be negative.
|
[
"GetStringBounds",
"returns",
"the",
"approximate",
"pixel",
"bounds",
"of",
"the",
"string",
"s",
"at",
"x",
"y",
".",
"The",
"the",
"left",
"edge",
"of",
"the",
"em",
"square",
"of",
"the",
"first",
"character",
"of",
"s",
"and",
"the",
"baseline",
"intersect",
"at",
"0",
"0",
"in",
"the",
"returned",
"coordinates",
".",
"Therefore",
"the",
"top",
"and",
"left",
"coordinates",
"may",
"well",
"be",
"negative",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L233-L266
|
test
|
llgcode/draw2d
|
draw2dgl/gc.go
|
recalc
|
func (gc *GraphicContext) recalc() {
gc.Current.Scale = gc.Current.FontSize * float64(gc.DPI) * (64.0 / 72.0)
}
|
go
|
func (gc *GraphicContext) recalc() {
gc.Current.Scale = gc.Current.FontSize * float64(gc.DPI) * (64.0 / 72.0)
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"recalc",
"(",
")",
"{",
"gc",
".",
"Current",
".",
"Scale",
"=",
"gc",
".",
"Current",
".",
"FontSize",
"*",
"float64",
"(",
"gc",
".",
"DPI",
")",
"*",
"(",
"64.0",
"/",
"72.0",
")",
"\n",
"}"
] |
// recalc recalculates scale and bounds values from the font size, screen
// resolution and font metrics, and invalidates the glyph cache.
|
[
"recalc",
"recalculates",
"scale",
"and",
"bounds",
"values",
"from",
"the",
"font",
"size",
"screen",
"resolution",
"and",
"font",
"metrics",
"and",
"invalidates",
"the",
"glyph",
"cache",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L297-L299
|
test
|
llgcode/draw2d
|
draw2dgl/gc.go
|
SetFont
|
func (gc *GraphicContext) SetFont(font *truetype.Font) {
gc.Current.Font = font
}
|
go
|
func (gc *GraphicContext) SetFont(font *truetype.Font) {
gc.Current.Font = font
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"SetFont",
"(",
"font",
"*",
"truetype",
".",
"Font",
")",
"{",
"gc",
".",
"Current",
".",
"Font",
"=",
"font",
"\n",
"}"
] |
// SetFont sets the font used to draw text.
|
[
"SetFont",
"sets",
"the",
"font",
"used",
"to",
"draw",
"text",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L307-L309
|
test
|
llgcode/draw2d
|
draw2dsvg/gc.go
|
ClearRect
|
func (gc *GraphicContext) ClearRect(x1, y1, x2, y2 int) {
mask := gc.newMask(x1, y1, x2-x1, y2-y1)
newGroup := &Group{
Groups: gc.svg.Groups,
Mask: "url(#" + mask.Id + ")",
}
// replace groups with new masked group
gc.svg.Groups = []*Group{newGroup}
}
|
go
|
func (gc *GraphicContext) ClearRect(x1, y1, x2, y2 int) {
mask := gc.newMask(x1, y1, x2-x1, y2-y1)
newGroup := &Group{
Groups: gc.svg.Groups,
Mask: "url(#" + mask.Id + ")",
}
// replace groups with new masked group
gc.svg.Groups = []*Group{newGroup}
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"ClearRect",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"int",
")",
"{",
"mask",
":=",
"gc",
".",
"newMask",
"(",
"x1",
",",
"y1",
",",
"x2",
"-",
"x1",
",",
"y2",
"-",
"y1",
")",
"\n",
"newGroup",
":=",
"&",
"Group",
"{",
"Groups",
":",
"gc",
".",
"svg",
".",
"Groups",
",",
"Mask",
":",
"\"url(#\"",
"+",
"mask",
".",
"Id",
"+",
"\")\"",
",",
"}",
"\n",
"gc",
".",
"svg",
".",
"Groups",
"=",
"[",
"]",
"*",
"Group",
"{",
"newGroup",
"}",
"\n",
"}"
] |
// ClearRect fills the specified rectangle with a default transparent color
|
[
"ClearRect",
"fills",
"the",
"specified",
"rectangle",
"with",
"a",
"default",
"transparent",
"color"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L137-L147
|
test
|
llgcode/draw2d
|
draw2dsvg/gc.go
|
drawString
|
func (gc *GraphicContext) drawString(text string, drawType drawType, x, y float64) float64 {
switch gc.svg.FontMode {
case PathFontMode:
w := gc.CreateStringPath(text, x, y)
gc.drawPaths(drawType)
gc.Current.Path.Clear()
return w
case SvgFontMode:
gc.embedSvgFont(text)
}
// create elements
svgText := Text{}
group := gc.newGroup(drawType)
// set attrs to text element
svgText.Text = text
svgText.FontSize = gc.Current.FontSize
svgText.X = x
svgText.Y = y
svgText.FontFamily = gc.Current.FontData.Name
// attach to group
group.Texts = []*Text{&svgText}
left, _, right, _ := gc.GetStringBounds(text)
return right - left
}
|
go
|
func (gc *GraphicContext) drawString(text string, drawType drawType, x, y float64) float64 {
switch gc.svg.FontMode {
case PathFontMode:
w := gc.CreateStringPath(text, x, y)
gc.drawPaths(drawType)
gc.Current.Path.Clear()
return w
case SvgFontMode:
gc.embedSvgFont(text)
}
// create elements
svgText := Text{}
group := gc.newGroup(drawType)
// set attrs to text element
svgText.Text = text
svgText.FontSize = gc.Current.FontSize
svgText.X = x
svgText.Y = y
svgText.FontFamily = gc.Current.FontData.Name
// attach to group
group.Texts = []*Text{&svgText}
left, _, right, _ := gc.GetStringBounds(text)
return right - left
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"drawString",
"(",
"text",
"string",
",",
"drawType",
"drawType",
",",
"x",
",",
"y",
"float64",
")",
"float64",
"{",
"switch",
"gc",
".",
"svg",
".",
"FontMode",
"{",
"case",
"PathFontMode",
":",
"w",
":=",
"gc",
".",
"CreateStringPath",
"(",
"text",
",",
"x",
",",
"y",
")",
"\n",
"gc",
".",
"drawPaths",
"(",
"drawType",
")",
"\n",
"gc",
".",
"Current",
".",
"Path",
".",
"Clear",
"(",
")",
"\n",
"return",
"w",
"\n",
"case",
"SvgFontMode",
":",
"gc",
".",
"embedSvgFont",
"(",
"text",
")",
"\n",
"}",
"\n",
"svgText",
":=",
"Text",
"{",
"}",
"\n",
"group",
":=",
"gc",
".",
"newGroup",
"(",
"drawType",
")",
"\n",
"svgText",
".",
"Text",
"=",
"text",
"\n",
"svgText",
".",
"FontSize",
"=",
"gc",
".",
"Current",
".",
"FontSize",
"\n",
"svgText",
".",
"X",
"=",
"x",
"\n",
"svgText",
".",
"Y",
"=",
"y",
"\n",
"svgText",
".",
"FontFamily",
"=",
"gc",
".",
"Current",
".",
"FontData",
".",
"Name",
"\n",
"group",
".",
"Texts",
"=",
"[",
"]",
"*",
"Text",
"{",
"&",
"svgText",
"}",
"\n",
"left",
",",
"_",
",",
"right",
",",
"_",
":=",
"gc",
".",
"GetStringBounds",
"(",
"text",
")",
"\n",
"return",
"right",
"-",
"left",
"\n",
"}"
] |
// Add text element to svg and returns its expected width
|
[
"Add",
"text",
"element",
"to",
"svg",
"and",
"returns",
"its",
"expected",
"width"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L248-L274
|
test
|
llgcode/draw2d
|
draw2dsvg/gc.go
|
newGroup
|
func (gc *GraphicContext) newGroup(drawType drawType) *Group {
group := Group{}
// set attrs to group
if drawType&stroked == stroked {
group.Stroke = toSvgRGBA(gc.Current.StrokeColor)
group.StrokeWidth = toSvgLength(gc.Current.LineWidth)
group.StrokeLinecap = gc.Current.Cap.String()
group.StrokeLinejoin = gc.Current.Join.String()
if len(gc.Current.Dash) > 0 {
group.StrokeDasharray = toSvgArray(gc.Current.Dash)
group.StrokeDashoffset = toSvgLength(gc.Current.DashOffset)
}
}
if drawType&filled == filled {
group.Fill = toSvgRGBA(gc.Current.FillColor)
group.FillRule = toSvgFillRule(gc.Current.FillRule)
}
group.Transform = toSvgTransform(gc.Current.Tr)
// attach
gc.svg.Groups = append(gc.svg.Groups, &group)
return &group
}
|
go
|
func (gc *GraphicContext) newGroup(drawType drawType) *Group {
group := Group{}
// set attrs to group
if drawType&stroked == stroked {
group.Stroke = toSvgRGBA(gc.Current.StrokeColor)
group.StrokeWidth = toSvgLength(gc.Current.LineWidth)
group.StrokeLinecap = gc.Current.Cap.String()
group.StrokeLinejoin = gc.Current.Join.String()
if len(gc.Current.Dash) > 0 {
group.StrokeDasharray = toSvgArray(gc.Current.Dash)
group.StrokeDashoffset = toSvgLength(gc.Current.DashOffset)
}
}
if drawType&filled == filled {
group.Fill = toSvgRGBA(gc.Current.FillColor)
group.FillRule = toSvgFillRule(gc.Current.FillRule)
}
group.Transform = toSvgTransform(gc.Current.Tr)
// attach
gc.svg.Groups = append(gc.svg.Groups, &group)
return &group
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"newGroup",
"(",
"drawType",
"drawType",
")",
"*",
"Group",
"{",
"group",
":=",
"Group",
"{",
"}",
"\n",
"if",
"drawType",
"&",
"stroked",
"==",
"stroked",
"{",
"group",
".",
"Stroke",
"=",
"toSvgRGBA",
"(",
"gc",
".",
"Current",
".",
"StrokeColor",
")",
"\n",
"group",
".",
"StrokeWidth",
"=",
"toSvgLength",
"(",
"gc",
".",
"Current",
".",
"LineWidth",
")",
"\n",
"group",
".",
"StrokeLinecap",
"=",
"gc",
".",
"Current",
".",
"Cap",
".",
"String",
"(",
")",
"\n",
"group",
".",
"StrokeLinejoin",
"=",
"gc",
".",
"Current",
".",
"Join",
".",
"String",
"(",
")",
"\n",
"if",
"len",
"(",
"gc",
".",
"Current",
".",
"Dash",
")",
">",
"0",
"{",
"group",
".",
"StrokeDasharray",
"=",
"toSvgArray",
"(",
"gc",
".",
"Current",
".",
"Dash",
")",
"\n",
"group",
".",
"StrokeDashoffset",
"=",
"toSvgLength",
"(",
"gc",
".",
"Current",
".",
"DashOffset",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"drawType",
"&",
"filled",
"==",
"filled",
"{",
"group",
".",
"Fill",
"=",
"toSvgRGBA",
"(",
"gc",
".",
"Current",
".",
"FillColor",
")",
"\n",
"group",
".",
"FillRule",
"=",
"toSvgFillRule",
"(",
"gc",
".",
"Current",
".",
"FillRule",
")",
"\n",
"}",
"\n",
"group",
".",
"Transform",
"=",
"toSvgTransform",
"(",
"gc",
".",
"Current",
".",
"Tr",
")",
"\n",
"gc",
".",
"svg",
".",
"Groups",
"=",
"append",
"(",
"gc",
".",
"svg",
".",
"Groups",
",",
"&",
"group",
")",
"\n",
"return",
"&",
"group",
"\n",
"}"
] |
// Creates new group from current context
// attach it to svg and return
|
[
"Creates",
"new",
"group",
"from",
"current",
"context",
"attach",
"it",
"to",
"svg",
"and",
"return"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L278-L303
|
test
|
llgcode/draw2d
|
draw2dsvg/gc.go
|
newMask
|
func (gc *GraphicContext) newMask(x, y, width, height int) *Mask {
mask := &Mask{}
mask.X = float64(x)
mask.Y = float64(y)
mask.Width = toSvgLength(float64(width))
mask.Height = toSvgLength(float64(height))
// attach mask
gc.svg.Masks = append(gc.svg.Masks, mask)
mask.Id = "mask-" + strconv.Itoa(len(gc.svg.Masks))
return mask
}
|
go
|
func (gc *GraphicContext) newMask(x, y, width, height int) *Mask {
mask := &Mask{}
mask.X = float64(x)
mask.Y = float64(y)
mask.Width = toSvgLength(float64(width))
mask.Height = toSvgLength(float64(height))
// attach mask
gc.svg.Masks = append(gc.svg.Masks, mask)
mask.Id = "mask-" + strconv.Itoa(len(gc.svg.Masks))
return mask
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"newMask",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
"int",
")",
"*",
"Mask",
"{",
"mask",
":=",
"&",
"Mask",
"{",
"}",
"\n",
"mask",
".",
"X",
"=",
"float64",
"(",
"x",
")",
"\n",
"mask",
".",
"Y",
"=",
"float64",
"(",
"y",
")",
"\n",
"mask",
".",
"Width",
"=",
"toSvgLength",
"(",
"float64",
"(",
"width",
")",
")",
"\n",
"mask",
".",
"Height",
"=",
"toSvgLength",
"(",
"float64",
"(",
"height",
")",
")",
"\n",
"gc",
".",
"svg",
".",
"Masks",
"=",
"append",
"(",
"gc",
".",
"svg",
".",
"Masks",
",",
"mask",
")",
"\n",
"mask",
".",
"Id",
"=",
"\"mask-\"",
"+",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"gc",
".",
"svg",
".",
"Masks",
")",
")",
"\n",
"return",
"mask",
"\n",
"}"
] |
// creates new mask attached to svg
|
[
"creates",
"new",
"mask",
"attached",
"to",
"svg"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L306-L317
|
test
|
llgcode/draw2d
|
draw2dsvg/gc.go
|
embedSvgFont
|
func (gc *GraphicContext) embedSvgFont(text string) *Font {
fontName := gc.Current.FontData.Name
gc.loadCurrentFont()
// find or create font Element
svgFont := (*Font)(nil)
for _, font := range gc.svg.Fonts {
if font.Name == fontName {
svgFont = font
break
}
}
if svgFont == nil {
// create new
svgFont = &Font{}
// and attach
gc.svg.Fonts = append(gc.svg.Fonts, svgFont)
}
// fill with glyphs
gc.Save()
defer gc.Restore()
gc.SetFontSize(2048)
defer gc.SetDPI(gc.GetDPI())
gc.SetDPI(92)
filling:
for _, rune := range text {
for _, g := range svgFont.Glyphs {
if g.Rune == Rune(rune) {
continue filling
}
}
glyph := gc.glyphCache.Fetch(gc, gc.GetFontName(), rune)
// glyphCache.Load indirectly calls CreateStringPath for single rune string
glypPath := glyph.Path.VerticalFlip() // svg font glyphs have oposite y axe
svgFont.Glyphs = append(svgFont.Glyphs, &Glyph{
Rune: Rune(rune),
Desc: toSvgPathDesc(glypPath),
HorizAdvX: glyph.Width,
})
}
// set attrs
svgFont.Id = "font-" + strconv.Itoa(len(gc.svg.Fonts))
svgFont.Name = fontName
// TODO use css @font-face with id instead of this
svgFont.Face = &Face{Family: fontName, Units: 2048, HorizAdvX: 2048}
return svgFont
}
|
go
|
func (gc *GraphicContext) embedSvgFont(text string) *Font {
fontName := gc.Current.FontData.Name
gc.loadCurrentFont()
// find or create font Element
svgFont := (*Font)(nil)
for _, font := range gc.svg.Fonts {
if font.Name == fontName {
svgFont = font
break
}
}
if svgFont == nil {
// create new
svgFont = &Font{}
// and attach
gc.svg.Fonts = append(gc.svg.Fonts, svgFont)
}
// fill with glyphs
gc.Save()
defer gc.Restore()
gc.SetFontSize(2048)
defer gc.SetDPI(gc.GetDPI())
gc.SetDPI(92)
filling:
for _, rune := range text {
for _, g := range svgFont.Glyphs {
if g.Rune == Rune(rune) {
continue filling
}
}
glyph := gc.glyphCache.Fetch(gc, gc.GetFontName(), rune)
// glyphCache.Load indirectly calls CreateStringPath for single rune string
glypPath := glyph.Path.VerticalFlip() // svg font glyphs have oposite y axe
svgFont.Glyphs = append(svgFont.Glyphs, &Glyph{
Rune: Rune(rune),
Desc: toSvgPathDesc(glypPath),
HorizAdvX: glyph.Width,
})
}
// set attrs
svgFont.Id = "font-" + strconv.Itoa(len(gc.svg.Fonts))
svgFont.Name = fontName
// TODO use css @font-face with id instead of this
svgFont.Face = &Face{Family: fontName, Units: 2048, HorizAdvX: 2048}
return svgFont
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"embedSvgFont",
"(",
"text",
"string",
")",
"*",
"Font",
"{",
"fontName",
":=",
"gc",
".",
"Current",
".",
"FontData",
".",
"Name",
"\n",
"gc",
".",
"loadCurrentFont",
"(",
")",
"\n",
"svgFont",
":=",
"(",
"*",
"Font",
")",
"(",
"nil",
")",
"\n",
"for",
"_",
",",
"font",
":=",
"range",
"gc",
".",
"svg",
".",
"Fonts",
"{",
"if",
"font",
".",
"Name",
"==",
"fontName",
"{",
"svgFont",
"=",
"font",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"svgFont",
"==",
"nil",
"{",
"svgFont",
"=",
"&",
"Font",
"{",
"}",
"\n",
"gc",
".",
"svg",
".",
"Fonts",
"=",
"append",
"(",
"gc",
".",
"svg",
".",
"Fonts",
",",
"svgFont",
")",
"\n",
"}",
"\n",
"gc",
".",
"Save",
"(",
")",
"\n",
"defer",
"gc",
".",
"Restore",
"(",
")",
"\n",
"gc",
".",
"SetFontSize",
"(",
"2048",
")",
"\n",
"defer",
"gc",
".",
"SetDPI",
"(",
"gc",
".",
"GetDPI",
"(",
")",
")",
"\n",
"gc",
".",
"SetDPI",
"(",
"92",
")",
"\n",
"filling",
":",
"for",
"_",
",",
"rune",
":=",
"range",
"text",
"{",
"for",
"_",
",",
"g",
":=",
"range",
"svgFont",
".",
"Glyphs",
"{",
"if",
"g",
".",
"Rune",
"==",
"Rune",
"(",
"rune",
")",
"{",
"continue",
"filling",
"\n",
"}",
"\n",
"}",
"\n",
"glyph",
":=",
"gc",
".",
"glyphCache",
".",
"Fetch",
"(",
"gc",
",",
"gc",
".",
"GetFontName",
"(",
")",
",",
"rune",
")",
"\n",
"glypPath",
":=",
"glyph",
".",
"Path",
".",
"VerticalFlip",
"(",
")",
"\n",
"svgFont",
".",
"Glyphs",
"=",
"append",
"(",
"svgFont",
".",
"Glyphs",
",",
"&",
"Glyph",
"{",
"Rune",
":",
"Rune",
"(",
"rune",
")",
",",
"Desc",
":",
"toSvgPathDesc",
"(",
"glypPath",
")",
",",
"HorizAdvX",
":",
"glyph",
".",
"Width",
",",
"}",
")",
"\n",
"}",
"\n",
"svgFont",
".",
"Id",
"=",
"\"font-\"",
"+",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"gc",
".",
"svg",
".",
"Fonts",
")",
")",
"\n",
"svgFont",
".",
"Name",
"=",
"fontName",
"\n",
"svgFont",
".",
"Face",
"=",
"&",
"Face",
"{",
"Family",
":",
"fontName",
",",
"Units",
":",
"2048",
",",
"HorizAdvX",
":",
"2048",
"}",
"\n",
"return",
"svgFont",
"\n",
"}"
] |
// Embed svg font definition to svg tree itself
// Or update existing if already exists for curent font data
|
[
"Embed",
"svg",
"font",
"definition",
"to",
"svg",
"tree",
"itself",
"Or",
"update",
"existing",
"if",
"already",
"exists",
"for",
"curent",
"font",
"data"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L321-L372
|
test
|
llgcode/draw2d
|
draw2dbase/curve.go
|
TraceQuad
|
func TraceQuad(t Liner, quad []float64, flatteningThreshold float64) error {
if len(quad) < 6 {
return errors.New("quad length must be >= 6")
}
// Allocates curves stack
var curves [CurveRecursionLimit * 6]float64
copy(curves[0:6], quad[0:6])
i := 0
// current curve
var c []float64
var dx, dy, d float64
for i >= 0 {
c = curves[i:]
dx = c[4] - c[0]
dy = c[5] - c[1]
d = math.Abs(((c[2]-c[4])*dy - (c[3]-c[5])*dx))
// if it's flat then trace a line
if (d*d) <= flatteningThreshold*(dx*dx+dy*dy) || i == len(curves)-6 {
t.LineTo(c[4], c[5])
i -= 6
} else {
// second half of bezier go lower onto the stack
SubdivideQuad(c, curves[i+6:], curves[i:])
i += 6
}
}
return nil
}
|
go
|
func TraceQuad(t Liner, quad []float64, flatteningThreshold float64) error {
if len(quad) < 6 {
return errors.New("quad length must be >= 6")
}
// Allocates curves stack
var curves [CurveRecursionLimit * 6]float64
copy(curves[0:6], quad[0:6])
i := 0
// current curve
var c []float64
var dx, dy, d float64
for i >= 0 {
c = curves[i:]
dx = c[4] - c[0]
dy = c[5] - c[1]
d = math.Abs(((c[2]-c[4])*dy - (c[3]-c[5])*dx))
// if it's flat then trace a line
if (d*d) <= flatteningThreshold*(dx*dx+dy*dy) || i == len(curves)-6 {
t.LineTo(c[4], c[5])
i -= 6
} else {
// second half of bezier go lower onto the stack
SubdivideQuad(c, curves[i+6:], curves[i:])
i += 6
}
}
return nil
}
|
[
"func",
"TraceQuad",
"(",
"t",
"Liner",
",",
"quad",
"[",
"]",
"float64",
",",
"flatteningThreshold",
"float64",
")",
"error",
"{",
"if",
"len",
"(",
"quad",
")",
"<",
"6",
"{",
"return",
"errors",
".",
"New",
"(",
"\"quad length must be >= 6\"",
")",
"\n",
"}",
"\n",
"var",
"curves",
"[",
"CurveRecursionLimit",
"*",
"6",
"]",
"float64",
"\n",
"copy",
"(",
"curves",
"[",
"0",
":",
"6",
"]",
",",
"quad",
"[",
"0",
":",
"6",
"]",
")",
"\n",
"i",
":=",
"0",
"\n",
"var",
"c",
"[",
"]",
"float64",
"\n",
"var",
"dx",
",",
"dy",
",",
"d",
"float64",
"\n",
"for",
"i",
">=",
"0",
"{",
"c",
"=",
"curves",
"[",
"i",
":",
"]",
"\n",
"dx",
"=",
"c",
"[",
"4",
"]",
"-",
"c",
"[",
"0",
"]",
"\n",
"dy",
"=",
"c",
"[",
"5",
"]",
"-",
"c",
"[",
"1",
"]",
"\n",
"d",
"=",
"math",
".",
"Abs",
"(",
"(",
"(",
"c",
"[",
"2",
"]",
"-",
"c",
"[",
"4",
"]",
")",
"*",
"dy",
"-",
"(",
"c",
"[",
"3",
"]",
"-",
"c",
"[",
"5",
"]",
")",
"*",
"dx",
")",
")",
"\n",
"if",
"(",
"d",
"*",
"d",
")",
"<=",
"flatteningThreshold",
"*",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")",
"||",
"i",
"==",
"len",
"(",
"curves",
")",
"-",
"6",
"{",
"t",
".",
"LineTo",
"(",
"c",
"[",
"4",
"]",
",",
"c",
"[",
"5",
"]",
")",
"\n",
"i",
"-=",
"6",
"\n",
"}",
"else",
"{",
"SubdivideQuad",
"(",
"c",
",",
"curves",
"[",
"i",
"+",
"6",
":",
"]",
",",
"curves",
"[",
"i",
":",
"]",
")",
"\n",
"i",
"+=",
"6",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// TraceQuad generate lines subdividing the curve using a Liner
// flattening_threshold helps determines the flattening expectation of the curve
|
[
"TraceQuad",
"generate",
"lines",
"subdividing",
"the",
"curve",
"using",
"a",
"Liner",
"flattening_threshold",
"helps",
"determines",
"the",
"flattening",
"expectation",
"of",
"the",
"curve"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/curve.go#L113-L143
|
test
|
llgcode/draw2d
|
draw2dbase/stack_gc.go
|
GetFontName
|
func (cs *ContextStack) GetFontName() string {
fontData := cs.FontData
return fmt.Sprintf("%s:%d:%d:%9.2f", fontData.Name, fontData.Family, fontData.Style, cs.FontSize)
}
|
go
|
func (cs *ContextStack) GetFontName() string {
fontData := cs.FontData
return fmt.Sprintf("%s:%d:%d:%9.2f", fontData.Name, fontData.Family, fontData.Style, cs.FontSize)
}
|
[
"func",
"(",
"cs",
"*",
"ContextStack",
")",
"GetFontName",
"(",
")",
"string",
"{",
"fontData",
":=",
"cs",
".",
"FontData",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s:%d:%d:%9.2f\"",
",",
"fontData",
".",
"Name",
",",
"fontData",
".",
"Family",
",",
"fontData",
".",
"Style",
",",
"cs",
".",
"FontSize",
")",
"\n",
"}"
] |
// GetFontName gets the current FontData with fontSize as a string
|
[
"GetFontName",
"gets",
"the",
"current",
"FontData",
"with",
"fontSize",
"as",
"a",
"string"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/stack_gc.go#L45-L48
|
test
|
llgcode/draw2d
|
draw2dbase/stack_gc.go
|
NewStackGraphicContext
|
func NewStackGraphicContext() *StackGraphicContext {
gc := &StackGraphicContext{}
gc.Current = new(ContextStack)
gc.Current.Tr = draw2d.NewIdentityMatrix()
gc.Current.Path = new(draw2d.Path)
gc.Current.LineWidth = 1.0
gc.Current.StrokeColor = image.Black
gc.Current.FillColor = image.White
gc.Current.Cap = draw2d.RoundCap
gc.Current.FillRule = draw2d.FillRuleEvenOdd
gc.Current.Join = draw2d.RoundJoin
gc.Current.FontSize = 10
gc.Current.FontData = DefaultFontData
return gc
}
|
go
|
func NewStackGraphicContext() *StackGraphicContext {
gc := &StackGraphicContext{}
gc.Current = new(ContextStack)
gc.Current.Tr = draw2d.NewIdentityMatrix()
gc.Current.Path = new(draw2d.Path)
gc.Current.LineWidth = 1.0
gc.Current.StrokeColor = image.Black
gc.Current.FillColor = image.White
gc.Current.Cap = draw2d.RoundCap
gc.Current.FillRule = draw2d.FillRuleEvenOdd
gc.Current.Join = draw2d.RoundJoin
gc.Current.FontSize = 10
gc.Current.FontData = DefaultFontData
return gc
}
|
[
"func",
"NewStackGraphicContext",
"(",
")",
"*",
"StackGraphicContext",
"{",
"gc",
":=",
"&",
"StackGraphicContext",
"{",
"}",
"\n",
"gc",
".",
"Current",
"=",
"new",
"(",
"ContextStack",
")",
"\n",
"gc",
".",
"Current",
".",
"Tr",
"=",
"draw2d",
".",
"NewIdentityMatrix",
"(",
")",
"\n",
"gc",
".",
"Current",
".",
"Path",
"=",
"new",
"(",
"draw2d",
".",
"Path",
")",
"\n",
"gc",
".",
"Current",
".",
"LineWidth",
"=",
"1.0",
"\n",
"gc",
".",
"Current",
".",
"StrokeColor",
"=",
"image",
".",
"Black",
"\n",
"gc",
".",
"Current",
".",
"FillColor",
"=",
"image",
".",
"White",
"\n",
"gc",
".",
"Current",
".",
"Cap",
"=",
"draw2d",
".",
"RoundCap",
"\n",
"gc",
".",
"Current",
".",
"FillRule",
"=",
"draw2d",
".",
"FillRuleEvenOdd",
"\n",
"gc",
".",
"Current",
".",
"Join",
"=",
"draw2d",
".",
"RoundJoin",
"\n",
"gc",
".",
"Current",
".",
"FontSize",
"=",
"10",
"\n",
"gc",
".",
"Current",
".",
"FontData",
"=",
"DefaultFontData",
"\n",
"return",
"gc",
"\n",
"}"
] |
/**
* Create a new Graphic context from an image
*/
|
[
"Create",
"a",
"new",
"Graphic",
"context",
"from",
"an",
"image"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/stack_gc.go#L54-L68
|
test
|
llgcode/draw2d
|
font.go
|
NewFolderFontCache
|
func NewFolderFontCache(folder string) *FolderFontCache {
return &FolderFontCache{
fonts: make(map[string]*truetype.Font),
folder: folder,
namer: FontFileName,
}
}
|
go
|
func NewFolderFontCache(folder string) *FolderFontCache {
return &FolderFontCache{
fonts: make(map[string]*truetype.Font),
folder: folder,
namer: FontFileName,
}
}
|
[
"func",
"NewFolderFontCache",
"(",
"folder",
"string",
")",
"*",
"FolderFontCache",
"{",
"return",
"&",
"FolderFontCache",
"{",
"fonts",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"truetype",
".",
"Font",
")",
",",
"folder",
":",
"folder",
",",
"namer",
":",
"FontFileName",
",",
"}",
"\n",
"}"
] |
// NewFolderFontCache creates FolderFontCache
|
[
"NewFolderFontCache",
"creates",
"FolderFontCache"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/font.go#L129-L135
|
test
|
llgcode/draw2d
|
font.go
|
NewSyncFolderFontCache
|
func NewSyncFolderFontCache(folder string) *SyncFolderFontCache {
return &SyncFolderFontCache{
fonts: make(map[string]*truetype.Font),
folder: folder,
namer: FontFileName,
}
}
|
go
|
func NewSyncFolderFontCache(folder string) *SyncFolderFontCache {
return &SyncFolderFontCache{
fonts: make(map[string]*truetype.Font),
folder: folder,
namer: FontFileName,
}
}
|
[
"func",
"NewSyncFolderFontCache",
"(",
"folder",
"string",
")",
"*",
"SyncFolderFontCache",
"{",
"return",
"&",
"SyncFolderFontCache",
"{",
"fonts",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"truetype",
".",
"Font",
")",
",",
"folder",
":",
"folder",
",",
"namer",
":",
"FontFileName",
",",
"}",
"\n",
"}"
] |
// NewSyncFolderFontCache creates SyncFolderFontCache
|
[
"NewSyncFolderFontCache",
"creates",
"SyncFolderFontCache"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/font.go#L172-L178
|
test
|
llgcode/draw2d
|
samples/gopher2/gopher2.go
|
Main
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
gc.SetStrokeColor(image.Black)
gc.SetFillColor(image.White)
gc.Save()
// Draw a (partial) gopher
gc.Translate(-60, 65)
gc.Rotate(-30 * (math.Pi / 180.0))
Draw(gc, 48, 48, 240, 72)
gc.Restore()
// Return the output filename
return samples.Output("gopher2", ext), nil
}
|
go
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
gc.SetStrokeColor(image.Black)
gc.SetFillColor(image.White)
gc.Save()
// Draw a (partial) gopher
gc.Translate(-60, 65)
gc.Rotate(-30 * (math.Pi / 180.0))
Draw(gc, 48, 48, 240, 72)
gc.Restore()
// Return the output filename
return samples.Output("gopher2", ext), nil
}
|
[
"func",
"Main",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"ext",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"gc",
".",
"SetStrokeColor",
"(",
"image",
".",
"Black",
")",
"\n",
"gc",
".",
"SetFillColor",
"(",
"image",
".",
"White",
")",
"\n",
"gc",
".",
"Save",
"(",
")",
"\n",
"gc",
".",
"Translate",
"(",
"-",
"60",
",",
"65",
")",
"\n",
"gc",
".",
"Rotate",
"(",
"-",
"30",
"*",
"(",
"math",
".",
"Pi",
"/",
"180.0",
")",
")",
"\n",
"Draw",
"(",
"gc",
",",
"48",
",",
"48",
",",
"240",
",",
"72",
")",
"\n",
"gc",
".",
"Restore",
"(",
")",
"\n",
"return",
"samples",
".",
"Output",
"(",
"\"gopher2\"",
",",
"ext",
")",
",",
"nil",
"\n",
"}"
] |
// Main draws a rotated face of the gopher. Afterwards it returns
// the filename. This should only be used during testing.
|
[
"Main",
"draws",
"a",
"rotated",
"face",
"of",
"the",
"gopher",
".",
"Afterwards",
"it",
"returns",
"the",
"filename",
".",
"This",
"should",
"only",
"be",
"used",
"during",
"testing",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/gopher2/gopher2.go#L20-L32
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
NewPdf
|
func NewPdf(orientationStr, unitStr, sizeStr string) *gofpdf.Fpdf {
pdf := gofpdf.New(orientationStr, unitStr, sizeStr, draw2d.GetFontFolder())
// to be compatible with draw2d
pdf.SetMargins(0, 0, 0)
pdf.SetDrawColor(0, 0, 0)
pdf.SetFillColor(255, 255, 255)
pdf.SetLineCapStyle("round")
pdf.SetLineJoinStyle("round")
pdf.SetLineWidth(1)
pdf.AddPage()
return pdf
}
|
go
|
func NewPdf(orientationStr, unitStr, sizeStr string) *gofpdf.Fpdf {
pdf := gofpdf.New(orientationStr, unitStr, sizeStr, draw2d.GetFontFolder())
// to be compatible with draw2d
pdf.SetMargins(0, 0, 0)
pdf.SetDrawColor(0, 0, 0)
pdf.SetFillColor(255, 255, 255)
pdf.SetLineCapStyle("round")
pdf.SetLineJoinStyle("round")
pdf.SetLineWidth(1)
pdf.AddPage()
return pdf
}
|
[
"func",
"NewPdf",
"(",
"orientationStr",
",",
"unitStr",
",",
"sizeStr",
"string",
")",
"*",
"gofpdf",
".",
"Fpdf",
"{",
"pdf",
":=",
"gofpdf",
".",
"New",
"(",
"orientationStr",
",",
"unitStr",
",",
"sizeStr",
",",
"draw2d",
".",
"GetFontFolder",
"(",
")",
")",
"\n",
"pdf",
".",
"SetMargins",
"(",
"0",
",",
"0",
",",
"0",
")",
"\n",
"pdf",
".",
"SetDrawColor",
"(",
"0",
",",
"0",
",",
"0",
")",
"\n",
"pdf",
".",
"SetFillColor",
"(",
"255",
",",
"255",
",",
"255",
")",
"\n",
"pdf",
".",
"SetLineCapStyle",
"(",
"\"round\"",
")",
"\n",
"pdf",
".",
"SetLineJoinStyle",
"(",
"\"round\"",
")",
"\n",
"pdf",
".",
"SetLineWidth",
"(",
"1",
")",
"\n",
"pdf",
".",
"AddPage",
"(",
")",
"\n",
"return",
"pdf",
"\n",
"}"
] |
// NewPdf creates a new pdf document with the draw2d fontfolder, adds
// a page and set fill color to white.
|
[
"NewPdf",
"creates",
"a",
"new",
"pdf",
"document",
"with",
"the",
"draw2d",
"fontfolder",
"adds",
"a",
"page",
"and",
"set",
"fill",
"color",
"to",
"white",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L47-L58
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
clearRect
|
func clearRect(gc *GraphicContext, x1, y1, x2, y2 float64) {
// save state
f := gc.Current.FillColor
x, y := gc.pdf.GetXY()
// cover page with white rectangle
gc.SetFillColor(white)
draw2dkit.Rectangle(gc, x1, y1, x2, y2)
gc.Fill()
// restore state
gc.SetFillColor(f)
gc.pdf.MoveTo(x, y)
}
|
go
|
func clearRect(gc *GraphicContext, x1, y1, x2, y2 float64) {
// save state
f := gc.Current.FillColor
x, y := gc.pdf.GetXY()
// cover page with white rectangle
gc.SetFillColor(white)
draw2dkit.Rectangle(gc, x1, y1, x2, y2)
gc.Fill()
// restore state
gc.SetFillColor(f)
gc.pdf.MoveTo(x, y)
}
|
[
"func",
"clearRect",
"(",
"gc",
"*",
"GraphicContext",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"float64",
")",
"{",
"f",
":=",
"gc",
".",
"Current",
".",
"FillColor",
"\n",
"x",
",",
"y",
":=",
"gc",
".",
"pdf",
".",
"GetXY",
"(",
")",
"\n",
"gc",
".",
"SetFillColor",
"(",
"white",
")",
"\n",
"draw2dkit",
".",
"Rectangle",
"(",
"gc",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
"\n",
"gc",
".",
"Fill",
"(",
")",
"\n",
"gc",
".",
"SetFillColor",
"(",
"f",
")",
"\n",
"gc",
".",
"pdf",
".",
"MoveTo",
"(",
"x",
",",
"y",
")",
"\n",
"}"
] |
// clearRect draws a white rectangle
|
[
"clearRect",
"draws",
"a",
"white",
"rectangle"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L67-L78
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
NewGraphicContext
|
func NewGraphicContext(pdf *gofpdf.Fpdf) *GraphicContext {
gc := &GraphicContext{draw2dbase.NewStackGraphicContext(), pdf, DPI}
gc.SetDPI(DPI)
return gc
}
|
go
|
func NewGraphicContext(pdf *gofpdf.Fpdf) *GraphicContext {
gc := &GraphicContext{draw2dbase.NewStackGraphicContext(), pdf, DPI}
gc.SetDPI(DPI)
return gc
}
|
[
"func",
"NewGraphicContext",
"(",
"pdf",
"*",
"gofpdf",
".",
"Fpdf",
")",
"*",
"GraphicContext",
"{",
"gc",
":=",
"&",
"GraphicContext",
"{",
"draw2dbase",
".",
"NewStackGraphicContext",
"(",
")",
",",
"pdf",
",",
"DPI",
"}",
"\n",
"gc",
".",
"SetDPI",
"(",
"DPI",
")",
"\n",
"return",
"gc",
"\n",
"}"
] |
// NewGraphicContext creates a new pdf GraphicContext
|
[
"NewGraphicContext",
"creates",
"a",
"new",
"pdf",
"GraphicContext"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L89-L93
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
Clear
|
func (gc *GraphicContext) Clear() {
width, height := gc.pdf.GetPageSize()
clearRect(gc, 0, 0, width, height)
}
|
go
|
func (gc *GraphicContext) Clear() {
width, height := gc.pdf.GetPageSize()
clearRect(gc, 0, 0, width, height)
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"Clear",
"(",
")",
"{",
"width",
",",
"height",
":=",
"gc",
".",
"pdf",
".",
"GetPageSize",
"(",
")",
"\n",
"clearRect",
"(",
"gc",
",",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
"\n",
"}"
] |
// Clear draws a white rectangle over the whole page
|
[
"Clear",
"draws",
"a",
"white",
"rectangle",
"over",
"the",
"whole",
"page"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L111-L114
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
GetStringBounds
|
func (gc *GraphicContext) GetStringBounds(s string) (left, top, right, bottom float64) {
_, h := gc.pdf.GetFontSize()
d := gc.pdf.GetFontDesc("", "")
if d.Ascent == 0 {
// not defined (standard font?), use average of 81%
top = 0.81 * h
} else {
top = -float64(d.Ascent) * h / float64(d.Ascent-d.Descent)
}
return 0, top, gc.pdf.GetStringWidth(s), top + h
}
|
go
|
func (gc *GraphicContext) GetStringBounds(s string) (left, top, right, bottom float64) {
_, h := gc.pdf.GetFontSize()
d := gc.pdf.GetFontDesc("", "")
if d.Ascent == 0 {
// not defined (standard font?), use average of 81%
top = 0.81 * h
} else {
top = -float64(d.Ascent) * h / float64(d.Ascent-d.Descent)
}
return 0, top, gc.pdf.GetStringWidth(s), top + h
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"GetStringBounds",
"(",
"s",
"string",
")",
"(",
"left",
",",
"top",
",",
"right",
",",
"bottom",
"float64",
")",
"{",
"_",
",",
"h",
":=",
"gc",
".",
"pdf",
".",
"GetFontSize",
"(",
")",
"\n",
"d",
":=",
"gc",
".",
"pdf",
".",
"GetFontDesc",
"(",
"\"\"",
",",
"\"\"",
")",
"\n",
"if",
"d",
".",
"Ascent",
"==",
"0",
"{",
"top",
"=",
"0.81",
"*",
"h",
"\n",
"}",
"else",
"{",
"top",
"=",
"-",
"float64",
"(",
"d",
".",
"Ascent",
")",
"*",
"h",
"/",
"float64",
"(",
"d",
".",
"Ascent",
"-",
"d",
".",
"Descent",
")",
"\n",
"}",
"\n",
"return",
"0",
",",
"top",
",",
"gc",
".",
"pdf",
".",
"GetStringWidth",
"(",
"s",
")",
",",
"top",
"+",
"h",
"\n",
"}"
] |
// GetStringBounds returns the approximate pixel bounds of the string s at x, y.
// The left edge of the em square of the first character of s
// and the baseline intersect at 0, 0 in the returned coordinates.
// Therefore the top and left coordinates may well be negative.
|
[
"GetStringBounds",
"returns",
"the",
"approximate",
"pixel",
"bounds",
"of",
"the",
"string",
"s",
"at",
"x",
"y",
".",
"The",
"left",
"edge",
"of",
"the",
"em",
"square",
"of",
"the",
"first",
"character",
"of",
"s",
"and",
"the",
"baseline",
"intersect",
"at",
"0",
"0",
"in",
"the",
"returned",
"coordinates",
".",
"Therefore",
"the",
"top",
"and",
"left",
"coordinates",
"may",
"well",
"be",
"negative",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L146-L156
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
CreateStringPath
|
func (gc *GraphicContext) CreateStringPath(text string, x, y float64) (cursor float64) {
//fpdf uses the top left corner
left, top, right, bottom := gc.GetStringBounds(text)
w := right - left
h := bottom - top
// gc.pdf.SetXY(x, y-h) do not use this as y-h might be negative
margin := gc.pdf.GetCellMargin()
gc.pdf.MoveTo(x-left-margin, y+top)
gc.pdf.CellFormat(w, h, text, "", 0, "BL", false, 0, "")
return w
}
|
go
|
func (gc *GraphicContext) CreateStringPath(text string, x, y float64) (cursor float64) {
//fpdf uses the top left corner
left, top, right, bottom := gc.GetStringBounds(text)
w := right - left
h := bottom - top
// gc.pdf.SetXY(x, y-h) do not use this as y-h might be negative
margin := gc.pdf.GetCellMargin()
gc.pdf.MoveTo(x-left-margin, y+top)
gc.pdf.CellFormat(w, h, text, "", 0, "BL", false, 0, "")
return w
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"CreateStringPath",
"(",
"text",
"string",
",",
"x",
",",
"y",
"float64",
")",
"(",
"cursor",
"float64",
")",
"{",
"left",
",",
"top",
",",
"right",
",",
"bottom",
":=",
"gc",
".",
"GetStringBounds",
"(",
"text",
")",
"\n",
"w",
":=",
"right",
"-",
"left",
"\n",
"h",
":=",
"bottom",
"-",
"top",
"\n",
"margin",
":=",
"gc",
".",
"pdf",
".",
"GetCellMargin",
"(",
")",
"\n",
"gc",
".",
"pdf",
".",
"MoveTo",
"(",
"x",
"-",
"left",
"-",
"margin",
",",
"y",
"+",
"top",
")",
"\n",
"gc",
".",
"pdf",
".",
"CellFormat",
"(",
"w",
",",
"h",
",",
"text",
",",
"\"\"",
",",
"0",
",",
"\"BL\"",
",",
"false",
",",
"0",
",",
"\"\"",
")",
"\n",
"return",
"w",
"\n",
"}"
] |
// CreateStringPath creates a path from the string s at x, y, and returns the string width.
|
[
"CreateStringPath",
"creates",
"a",
"path",
"from",
"the",
"string",
"s",
"at",
"x",
"y",
"and",
"returns",
"the",
"string",
"width",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L159-L169
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
FillStringAt
|
func (gc *GraphicContext) FillStringAt(text string, x, y float64) (cursor float64) {
return gc.CreateStringPath(text, x, y)
}
|
go
|
func (gc *GraphicContext) FillStringAt(text string, x, y float64) (cursor float64) {
return gc.CreateStringPath(text, x, y)
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"FillStringAt",
"(",
"text",
"string",
",",
"x",
",",
"y",
"float64",
")",
"(",
"cursor",
"float64",
")",
"{",
"return",
"gc",
".",
"CreateStringPath",
"(",
"text",
",",
"x",
",",
"y",
")",
"\n",
"}"
] |
// FillStringAt draws a string at x, y
|
[
"FillStringAt",
"draws",
"a",
"string",
"at",
"x",
"y"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L177-L179
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
SetStrokeColor
|
func (gc *GraphicContext) SetStrokeColor(c color.Color) {
gc.StackGraphicContext.SetStrokeColor(c)
gc.pdf.SetDrawColor(rgb(c))
}
|
go
|
func (gc *GraphicContext) SetStrokeColor(c color.Color) {
gc.StackGraphicContext.SetStrokeColor(c)
gc.pdf.SetDrawColor(rgb(c))
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"SetStrokeColor",
"(",
"c",
"color",
".",
"Color",
")",
"{",
"gc",
".",
"StackGraphicContext",
".",
"SetStrokeColor",
"(",
"c",
")",
"\n",
"gc",
".",
"pdf",
".",
"SetDrawColor",
"(",
"rgb",
"(",
"c",
")",
")",
"\n",
"}"
] |
// overwrite StackGraphicContext methods
// SetStrokeColor sets the stroke color
|
[
"overwrite",
"StackGraphicContext",
"methods",
"SetStrokeColor",
"sets",
"the",
"stroke",
"color"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L249-L252
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
SetFillColor
|
func (gc *GraphicContext) SetFillColor(c color.Color) {
gc.StackGraphicContext.SetFillColor(c)
gc.pdf.SetFillColor(rgb(c))
gc.pdf.SetTextColor(rgb(c))
}
|
go
|
func (gc *GraphicContext) SetFillColor(c color.Color) {
gc.StackGraphicContext.SetFillColor(c)
gc.pdf.SetFillColor(rgb(c))
gc.pdf.SetTextColor(rgb(c))
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"SetFillColor",
"(",
"c",
"color",
".",
"Color",
")",
"{",
"gc",
".",
"StackGraphicContext",
".",
"SetFillColor",
"(",
"c",
")",
"\n",
"gc",
".",
"pdf",
".",
"SetFillColor",
"(",
"rgb",
"(",
"c",
")",
")",
"\n",
"gc",
".",
"pdf",
".",
"SetTextColor",
"(",
"rgb",
"(",
"c",
")",
")",
"\n",
"}"
] |
// SetFillColor sets the fill and text color
|
[
"SetFillColor",
"sets",
"the",
"fill",
"and",
"text",
"color"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L255-L259
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
SetLineDash
|
func (gc *GraphicContext) SetLineDash(Dash []float64, DashOffset float64) {
gc.StackGraphicContext.SetLineDash(Dash, DashOffset)
gc.pdf.SetDashPattern(Dash, DashOffset)
}
|
go
|
func (gc *GraphicContext) SetLineDash(Dash []float64, DashOffset float64) {
gc.StackGraphicContext.SetLineDash(Dash, DashOffset)
gc.pdf.SetDashPattern(Dash, DashOffset)
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"SetLineDash",
"(",
"Dash",
"[",
"]",
"float64",
",",
"DashOffset",
"float64",
")",
"{",
"gc",
".",
"StackGraphicContext",
".",
"SetLineDash",
"(",
"Dash",
",",
"DashOffset",
")",
"\n",
"gc",
".",
"pdf",
".",
"SetDashPattern",
"(",
"Dash",
",",
"DashOffset",
")",
"\n",
"}"
] |
// SetLineDash sets the line dash pattern
|
[
"SetLineDash",
"sets",
"the",
"line",
"dash",
"pattern"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L302-L305
|
test
|
llgcode/draw2d
|
draw2dpdf/gc.go
|
SetLineWidth
|
func (gc *GraphicContext) SetLineWidth(LineWidth float64) {
gc.StackGraphicContext.SetLineWidth(LineWidth)
gc.pdf.SetLineWidth(LineWidth)
}
|
go
|
func (gc *GraphicContext) SetLineWidth(LineWidth float64) {
gc.StackGraphicContext.SetLineWidth(LineWidth)
gc.pdf.SetLineWidth(LineWidth)
}
|
[
"func",
"(",
"gc",
"*",
"GraphicContext",
")",
"SetLineWidth",
"(",
"LineWidth",
"float64",
")",
"{",
"gc",
".",
"StackGraphicContext",
".",
"SetLineWidth",
"(",
"LineWidth",
")",
"\n",
"gc",
".",
"pdf",
".",
"SetLineWidth",
"(",
"LineWidth",
")",
"\n",
"}"
] |
// SetLineWidth sets the line width
|
[
"SetLineWidth",
"sets",
"the",
"line",
"width"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L308-L311
|
test
|
llgcode/draw2d
|
samples/helloworld/helloworld.go
|
Main
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
// Draw hello world
Draw(gc, fmt.Sprintf("Hello World %d dpi", gc.GetDPI()))
// Return the output filename
return samples.Output("helloworld", ext), nil
}
|
go
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
// Draw hello world
Draw(gc, fmt.Sprintf("Hello World %d dpi", gc.GetDPI()))
// Return the output filename
return samples.Output("helloworld", ext), nil
}
|
[
"func",
"Main",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"ext",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"Draw",
"(",
"gc",
",",
"fmt",
".",
"Sprintf",
"(",
"\"Hello World %d dpi\"",
",",
"gc",
".",
"GetDPI",
"(",
")",
")",
")",
"\n",
"return",
"samples",
".",
"Output",
"(",
"\"helloworld\"",
",",
"ext",
")",
",",
"nil",
"\n",
"}"
] |
// Main draws "Hello World" and returns the filename. This should only be
// used during testing.
|
[
"Main",
"draws",
"Hello",
"World",
"and",
"returns",
"the",
"filename",
".",
"This",
"should",
"only",
"be",
"used",
"during",
"testing",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/helloworld/helloworld.go#L19-L25
|
test
|
llgcode/draw2d
|
samples/helloworld/helloworld.go
|
Draw
|
func Draw(gc draw2d.GraphicContext, text string) {
// Draw a rounded rectangle using default colors
draw2dkit.RoundedRectangle(gc, 5, 5, 135, 95, 10, 10)
gc.FillStroke()
// Set the font luximbi.ttf
gc.SetFontData(draw2d.FontData{Name: "luxi", Family: draw2d.FontFamilyMono, Style: draw2d.FontStyleBold | draw2d.FontStyleItalic})
// Set the fill text color to black
gc.SetFillColor(image.Black)
gc.SetFontSize(14)
// Display Hello World
gc.FillStringAt("Hello World", 8, 52)
}
|
go
|
func Draw(gc draw2d.GraphicContext, text string) {
// Draw a rounded rectangle using default colors
draw2dkit.RoundedRectangle(gc, 5, 5, 135, 95, 10, 10)
gc.FillStroke()
// Set the font luximbi.ttf
gc.SetFontData(draw2d.FontData{Name: "luxi", Family: draw2d.FontFamilyMono, Style: draw2d.FontStyleBold | draw2d.FontStyleItalic})
// Set the fill text color to black
gc.SetFillColor(image.Black)
gc.SetFontSize(14)
// Display Hello World
gc.FillStringAt("Hello World", 8, 52)
}
|
[
"func",
"Draw",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"text",
"string",
")",
"{",
"draw2dkit",
".",
"RoundedRectangle",
"(",
"gc",
",",
"5",
",",
"5",
",",
"135",
",",
"95",
",",
"10",
",",
"10",
")",
"\n",
"gc",
".",
"FillStroke",
"(",
")",
"\n",
"gc",
".",
"SetFontData",
"(",
"draw2d",
".",
"FontData",
"{",
"Name",
":",
"\"luxi\"",
",",
"Family",
":",
"draw2d",
".",
"FontFamilyMono",
",",
"Style",
":",
"draw2d",
".",
"FontStyleBold",
"|",
"draw2d",
".",
"FontStyleItalic",
"}",
")",
"\n",
"gc",
".",
"SetFillColor",
"(",
"image",
".",
"Black",
")",
"\n",
"gc",
".",
"SetFontSize",
"(",
"14",
")",
"\n",
"gc",
".",
"FillStringAt",
"(",
"\"Hello World\"",
",",
"8",
",",
"52",
")",
"\n",
"}"
] |
// Draw "Hello World"
|
[
"Draw",
"Hello",
"World"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/helloworld/helloworld.go#L28-L40
|
test
|
llgcode/draw2d
|
draw2dimg/fileutil.go
|
SaveToPngFile
|
func SaveToPngFile(filePath string, m image.Image) error {
// Create the file
f, err := os.Create(filePath)
if err != nil {
return err
}
defer f.Close()
// Create Writer from file
b := bufio.NewWriter(f)
// Write the image into the buffer
err = png.Encode(b, m)
if err != nil {
return err
}
err = b.Flush()
if err != nil {
return err
}
return nil
}
|
go
|
func SaveToPngFile(filePath string, m image.Image) error {
// Create the file
f, err := os.Create(filePath)
if err != nil {
return err
}
defer f.Close()
// Create Writer from file
b := bufio.NewWriter(f)
// Write the image into the buffer
err = png.Encode(b, m)
if err != nil {
return err
}
err = b.Flush()
if err != nil {
return err
}
return nil
}
|
[
"func",
"SaveToPngFile",
"(",
"filePath",
"string",
",",
"m",
"image",
".",
"Image",
")",
"error",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"filePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"b",
":=",
"bufio",
".",
"NewWriter",
"(",
"f",
")",
"\n",
"err",
"=",
"png",
".",
"Encode",
"(",
"b",
",",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"b",
".",
"Flush",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SaveToPngFile create and save an image to a file using PNG format
|
[
"SaveToPngFile",
"create",
"and",
"save",
"an",
"image",
"to",
"a",
"file",
"using",
"PNG",
"format"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dimg/fileutil.go#L11-L30
|
test
|
llgcode/draw2d
|
draw2dimg/fileutil.go
|
LoadFromPngFile
|
func LoadFromPngFile(filePath string) (image.Image, error) {
// Open file
f, err := os.OpenFile(filePath, 0, 0)
if err != nil {
return nil, err
}
defer f.Close()
b := bufio.NewReader(f)
img, err := png.Decode(b)
if err != nil {
return nil, err
}
return img, nil
}
|
go
|
func LoadFromPngFile(filePath string) (image.Image, error) {
// Open file
f, err := os.OpenFile(filePath, 0, 0)
if err != nil {
return nil, err
}
defer f.Close()
b := bufio.NewReader(f)
img, err := png.Decode(b)
if err != nil {
return nil, err
}
return img, nil
}
|
[
"func",
"LoadFromPngFile",
"(",
"filePath",
"string",
")",
"(",
"image",
".",
"Image",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"filePath",
",",
"0",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"b",
":=",
"bufio",
".",
"NewReader",
"(",
"f",
")",
"\n",
"img",
",",
"err",
":=",
"png",
".",
"Decode",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"img",
",",
"nil",
"\n",
"}"
] |
// LoadFromPngFile Open a png file
|
[
"LoadFromPngFile",
"Open",
"a",
"png",
"file"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dimg/fileutil.go#L33-L46
|
test
|
llgcode/draw2d
|
samples/samples.go
|
Resource
|
func Resource(folder, filename, ext string) string {
var root string
if ext == "pdf" || ext == "svg" {
root = "../"
}
return fmt.Sprintf("%sresource/%s/%s", root, folder, filename)
}
|
go
|
func Resource(folder, filename, ext string) string {
var root string
if ext == "pdf" || ext == "svg" {
root = "../"
}
return fmt.Sprintf("%sresource/%s/%s", root, folder, filename)
}
|
[
"func",
"Resource",
"(",
"folder",
",",
"filename",
",",
"ext",
"string",
")",
"string",
"{",
"var",
"root",
"string",
"\n",
"if",
"ext",
"==",
"\"pdf\"",
"||",
"ext",
"==",
"\"svg\"",
"{",
"root",
"=",
"\"../\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%sresource/%s/%s\"",
",",
"root",
",",
"folder",
",",
"filename",
")",
"\n",
"}"
] |
// Resource returns a resource filename for testing.
|
[
"Resource",
"returns",
"a",
"resource",
"filename",
"for",
"testing",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/samples.go#L9-L15
|
test
|
llgcode/draw2d
|
samples/samples.go
|
Output
|
func Output(name, ext string) string {
var root string
if ext == "pdf" || ext == "svg" {
root = "../"
}
return fmt.Sprintf("%soutput/samples/%s.%s", root, name, ext)
}
|
go
|
func Output(name, ext string) string {
var root string
if ext == "pdf" || ext == "svg" {
root = "../"
}
return fmt.Sprintf("%soutput/samples/%s.%s", root, name, ext)
}
|
[
"func",
"Output",
"(",
"name",
",",
"ext",
"string",
")",
"string",
"{",
"var",
"root",
"string",
"\n",
"if",
"ext",
"==",
"\"pdf\"",
"||",
"ext",
"==",
"\"svg\"",
"{",
"root",
"=",
"\"../\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%soutput/samples/%s.%s\"",
",",
"root",
",",
"name",
",",
"ext",
")",
"\n",
"}"
] |
// Output returns the output filename for testing.
|
[
"Output",
"returns",
"the",
"output",
"filename",
"for",
"testing",
"."
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/samples.go#L18-L24
|
test
|
llgcode/draw2d
|
samples/postscript/postscript.go
|
Main
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
gc.Save()
// flip the image
gc.Translate(0, 200)
gc.Scale(0.35, -0.35)
gc.Translate(70, -200)
// Tiger postscript drawing
tiger := samples.Resource("image", "tiger.ps", ext)
// Draw tiger
Draw(gc, tiger)
gc.Restore()
// Return the output filename
return samples.Output("postscript", ext), nil
}
|
go
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
gc.Save()
// flip the image
gc.Translate(0, 200)
gc.Scale(0.35, -0.35)
gc.Translate(70, -200)
// Tiger postscript drawing
tiger := samples.Resource("image", "tiger.ps", ext)
// Draw tiger
Draw(gc, tiger)
gc.Restore()
// Return the output filename
return samples.Output("postscript", ext), nil
}
|
[
"func",
"Main",
"(",
"gc",
"draw2d",
".",
"GraphicContext",
",",
"ext",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"gc",
".",
"Save",
"(",
")",
"\n",
"gc",
".",
"Translate",
"(",
"0",
",",
"200",
")",
"\n",
"gc",
".",
"Scale",
"(",
"0.35",
",",
"-",
"0.35",
")",
"\n",
"gc",
".",
"Translate",
"(",
"70",
",",
"-",
"200",
")",
"\n",
"tiger",
":=",
"samples",
".",
"Resource",
"(",
"\"image\"",
",",
"\"tiger.ps\"",
",",
"ext",
")",
"\n",
"Draw",
"(",
"gc",
",",
"tiger",
")",
"\n",
"gc",
".",
"Restore",
"(",
")",
"\n",
"return",
"samples",
".",
"Output",
"(",
"\"postscript\"",
",",
"ext",
")",
",",
"nil",
"\n",
"}"
] |
// Main draws the tiger
|
[
"Main",
"draws",
"the",
"tiger"
] |
f52c8a71aff06ab8df41843d33ab167b36c971cd
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/postscript/postscript.go#L16-L33
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.