id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
16,800
ArthurHlt/go-eureka-client
eureka/client.go
UnmarshalJSON
func (c *Client) UnmarshalJSON(b []byte) error { temp := struct { Config Config `json:"config"` Cluster *Cluster `json:"cluster"` }{} err := json.Unmarshal(b, &temp) if err != nil { return err } c.Cluster = temp.Cluster c.Config = temp.Config return nil }
go
func (c *Client) UnmarshalJSON(b []byte) error { temp := struct { Config Config `json:"config"` Cluster *Cluster `json:"cluster"` }{} err := json.Unmarshal(b, &temp) if err != nil { return err } c.Cluster = temp.Cluster c.Config = temp.Config return nil }
[ "func", "(", "c", "*", "Client", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "temp", ":=", "struct", "{", "Config", "Config", "`json:\"config\"`", "\n", "Cluster", "*", "Cluster", "`json:\"cluster\"`", "\n", "}", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "temp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "c", ".", "Cluster", "=", "temp", ".", "Cluster", "\n", "c", ".", "Config", "=", "temp", ".", "Config", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON implements the Unmarshaller interface // as defined by the standard JSON package.
[ "UnmarshalJSON", "implements", "the", "Unmarshaller", "interface", "as", "defined", "by", "the", "standard", "JSON", "package", "." ]
2f75174c63cf789d5de665a83b42680dfe2e088f
https://github.com/ArthurHlt/go-eureka-client/blob/2f75174c63cf789d5de665a83b42680dfe2e088f/eureka/client.go#L344-L357
16,801
ArthurHlt/go-eureka-client
eureka/requests.go
Get
func (c *Client) Get(endpoint string) (*RawResponse, error) { return c.getCancelable(endpoint, nil) }
go
func (c *Client) Get(endpoint string) (*RawResponse, error) { return c.getCancelable(endpoint, nil) }
[ "func", "(", "c", "*", "Client", ")", "Get", "(", "endpoint", "string", ")", "(", "*", "RawResponse", ",", "error", ")", "{", "return", "c", ".", "getCancelable", "(", "endpoint", ",", "nil", ")", "\n", "}" ]
// get issues a GET request
[ "get", "issues", "a", "GET", "request" ]
2f75174c63cf789d5de665a83b42680dfe2e088f
https://github.com/ArthurHlt/go-eureka-client/blob/2f75174c63cf789d5de665a83b42680dfe2e088f/eureka/requests.go#L164-L166
16,802
ArthurHlt/go-eureka-client
eureka/requests.go
Put
func (c *Client) Put(endpoint string, body []byte) (*RawResponse, error) { logger.Debug("put %s, %s, [%s]", endpoint, body, c.Cluster.Leader) p := endpoint req := NewRawRequest("PUT", p, body, nil) resp, err := c.SendRequest(req) if err != nil { return nil, err } return resp, nil }
go
func (c *Client) Put(endpoint string, body []byte) (*RawResponse, error) { logger.Debug("put %s, %s, [%s]", endpoint, body, c.Cluster.Leader) p := endpoint req := NewRawRequest("PUT", p, body, nil) resp, err := c.SendRequest(req) if err != nil { return nil, err } return resp, nil }
[ "func", "(", "c", "*", "Client", ")", "Put", "(", "endpoint", "string", ",", "body", "[", "]", "byte", ")", "(", "*", "RawResponse", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"", "\"", ",", "endpoint", ",", "body", ",", "c", ".", "Cluster", ".", "Leader", ")", "\n", "p", ":=", "endpoint", "\n\n", "req", ":=", "NewRawRequest", "(", "\"", "\"", ",", "p", ",", "body", ",", "nil", ")", "\n", "resp", ",", "err", ":=", "c", ".", "SendRequest", "(", "req", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "resp", ",", "nil", "\n", "}" ]
// put issues a PUT request
[ "put", "issues", "a", "PUT", "request" ]
2f75174c63cf789d5de665a83b42680dfe2e088f
https://github.com/ArthurHlt/go-eureka-client/blob/2f75174c63cf789d5de665a83b42680dfe2e088f/eureka/requests.go#L169-L182
16,803
ArthurHlt/go-eureka-client
eureka/requests.go
buildValues
func buildValues(value string, ttl uint64) url.Values { v := url.Values{} if value != "" { v.Set("value", value) } if ttl > 0 { v.Set("ttl", fmt.Sprintf("%v", ttl)) } return v }
go
func buildValues(value string, ttl uint64) url.Values { v := url.Values{} if value != "" { v.Set("value", value) } if ttl > 0 { v.Set("ttl", fmt.Sprintf("%v", ttl)) } return v }
[ "func", "buildValues", "(", "value", "string", ",", "ttl", "uint64", ")", "url", ".", "Values", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "value", "!=", "\"", "\"", "{", "v", ".", "Set", "(", "\"", "\"", ",", "value", ")", "\n", "}", "\n\n", "if", "ttl", ">", "0", "{", "v", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ttl", ")", ")", "\n", "}", "\n\n", "return", "v", "\n", "}" ]
// buildValues builds a url.Values map according to the given value and ttl
[ "buildValues", "builds", "a", "url", ".", "Values", "map", "according", "to", "the", "given", "value", "and", "ttl" ]
2f75174c63cf789d5de665a83b42680dfe2e088f
https://github.com/ArthurHlt/go-eureka-client/blob/2f75174c63cf789d5de665a83b42680dfe2e088f/eureka/requests.go#L427-L439
16,804
fiorix/go-smpp
smpp/pdu/pdutext/latin1.go
Encode
func (s Latin1) Encode() []byte { e := charmap.Windows1252.NewEncoder() es, _, err := transform.Bytes(e, s) if err != nil { return s } return es }
go
func (s Latin1) Encode() []byte { e := charmap.Windows1252.NewEncoder() es, _, err := transform.Bytes(e, s) if err != nil { return s } return es }
[ "func", "(", "s", "Latin1", ")", "Encode", "(", ")", "[", "]", "byte", "{", "e", ":=", "charmap", ".", "Windows1252", ".", "NewEncoder", "(", ")", "\n", "es", ",", "_", ",", "err", ":=", "transform", ".", "Bytes", "(", "e", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "s", "\n", "}", "\n", "return", "es", "\n", "}" ]
// Encode to Latin1.
[ "Encode", "to", "Latin1", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdutext/latin1.go#L21-L28
16,805
fiorix/go-smpp
smpp/pdu/pdutext/latin1.go
Decode
func (s Latin1) Decode() []byte { e := charmap.Windows1252.NewDecoder() es, _, err := transform.Bytes(e, s) if err != nil { return s } return es }
go
func (s Latin1) Decode() []byte { e := charmap.Windows1252.NewDecoder() es, _, err := transform.Bytes(e, s) if err != nil { return s } return es }
[ "func", "(", "s", "Latin1", ")", "Decode", "(", ")", "[", "]", "byte", "{", "e", ":=", "charmap", ".", "Windows1252", ".", "NewDecoder", "(", ")", "\n", "es", ",", "_", ",", "err", ":=", "transform", ".", "Bytes", "(", "e", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "s", "\n", "}", "\n", "return", "es", "\n", "}" ]
// Decode from Latin1.
[ "Decode", "from", "Latin1", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdutext/latin1.go#L31-L38
16,806
fiorix/go-smpp
smpp/pdu/pdufield/body.go
New
func New(n Name, data []byte) Body { switch n { case AddrNPI, AddrTON, DataCoding, DestAddrNPI, DestAddrTON, ESMClass, ErrorCode, InterfaceVersion, MessageState, NumberDests, NoUnsuccess, PriorityFlag, ProtocolID, RegisteredDelivery, ReplaceIfPresentFlag, SMDefaultMsgID, SMLength, SourceAddrNPI, SourceAddrTON, UDHLength: if data == nil { data = []byte{0} } return &Fixed{Data: data[0]} case AddressRange, DestinationAddr, DestinationList, FinalDate, MessageID, Password, ScheduleDeliveryTime, ServiceType, SourceAddr, SystemID, SystemType, UnsuccessSme, ValidityPeriod: if data == nil { data = []byte{} } return &Variable{Data: data} case ShortMessage: if data == nil { data = []byte{} } return &SM{Data: data} case GSMUserData: udhData := []UDH{} if data != nil && len(data) > 2 { for i := 0; i < len(data); { udh := UDH{} udh.IEI = Fixed{Data: data[i]} udh.IELength = Fixed{Data: data[i+1]} udh.IEData = Variable{} l := int(data[i+1]) for j := 2; j < l+2; j++ { udh.IEData.Data = append(udh.IEData.Data, data[i+j]) } udhData = append(udhData, udh) i += l + 3 // Ignore one byte after IEData (which is 0x00) } } return &UDHList{Data: udhData} default: return nil } }
go
func New(n Name, data []byte) Body { switch n { case AddrNPI, AddrTON, DataCoding, DestAddrNPI, DestAddrTON, ESMClass, ErrorCode, InterfaceVersion, MessageState, NumberDests, NoUnsuccess, PriorityFlag, ProtocolID, RegisteredDelivery, ReplaceIfPresentFlag, SMDefaultMsgID, SMLength, SourceAddrNPI, SourceAddrTON, UDHLength: if data == nil { data = []byte{0} } return &Fixed{Data: data[0]} case AddressRange, DestinationAddr, DestinationList, FinalDate, MessageID, Password, ScheduleDeliveryTime, ServiceType, SourceAddr, SystemID, SystemType, UnsuccessSme, ValidityPeriod: if data == nil { data = []byte{} } return &Variable{Data: data} case ShortMessage: if data == nil { data = []byte{} } return &SM{Data: data} case GSMUserData: udhData := []UDH{} if data != nil && len(data) > 2 { for i := 0; i < len(data); { udh := UDH{} udh.IEI = Fixed{Data: data[i]} udh.IELength = Fixed{Data: data[i+1]} udh.IEData = Variable{} l := int(data[i+1]) for j := 2; j < l+2; j++ { udh.IEData.Data = append(udh.IEData.Data, data[i+j]) } udhData = append(udhData, udh) i += l + 3 // Ignore one byte after IEData (which is 0x00) } } return &UDHList{Data: udhData} default: return nil } }
[ "func", "New", "(", "n", "Name", ",", "data", "[", "]", "byte", ")", "Body", "{", "switch", "n", "{", "case", "AddrNPI", ",", "AddrTON", ",", "DataCoding", ",", "DestAddrNPI", ",", "DestAddrTON", ",", "ESMClass", ",", "ErrorCode", ",", "InterfaceVersion", ",", "MessageState", ",", "NumberDests", ",", "NoUnsuccess", ",", "PriorityFlag", ",", "ProtocolID", ",", "RegisteredDelivery", ",", "ReplaceIfPresentFlag", ",", "SMDefaultMsgID", ",", "SMLength", ",", "SourceAddrNPI", ",", "SourceAddrTON", ",", "UDHLength", ":", "if", "data", "==", "nil", "{", "data", "=", "[", "]", "byte", "{", "0", "}", "\n", "}", "\n", "return", "&", "Fixed", "{", "Data", ":", "data", "[", "0", "]", "}", "\n", "case", "AddressRange", ",", "DestinationAddr", ",", "DestinationList", ",", "FinalDate", ",", "MessageID", ",", "Password", ",", "ScheduleDeliveryTime", ",", "ServiceType", ",", "SourceAddr", ",", "SystemID", ",", "SystemType", ",", "UnsuccessSme", ",", "ValidityPeriod", ":", "if", "data", "==", "nil", "{", "data", "=", "[", "]", "byte", "{", "}", "\n", "}", "\n", "return", "&", "Variable", "{", "Data", ":", "data", "}", "\n", "case", "ShortMessage", ":", "if", "data", "==", "nil", "{", "data", "=", "[", "]", "byte", "{", "}", "\n", "}", "\n", "return", "&", "SM", "{", "Data", ":", "data", "}", "\n", "case", "GSMUserData", ":", "udhData", ":=", "[", "]", "UDH", "{", "}", "\n", "if", "data", "!=", "nil", "&&", "len", "(", "data", ")", ">", "2", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "data", ")", ";", "{", "udh", ":=", "UDH", "{", "}", "\n", "udh", ".", "IEI", "=", "Fixed", "{", "Data", ":", "data", "[", "i", "]", "}", "\n", "udh", ".", "IELength", "=", "Fixed", "{", "Data", ":", "data", "[", "i", "+", "1", "]", "}", "\n", "udh", ".", "IEData", "=", "Variable", "{", "}", "\n", "l", ":=", "int", "(", "data", "[", "i", "+", "1", "]", ")", "\n", "for", "j", ":=", "2", ";", "j", "<", "l", "+", "2", ";", "j", "++", "{", "udh", ".", "IEData", ".", "Data", "=", "append", "(", "udh", ".", "IEData", ".", "Data", ",", "data", "[", "i", "+", "j", "]", ")", "\n", "}", "\n", "udhData", "=", "append", "(", "udhData", ",", "udh", ")", "\n", "i", "+=", "l", "+", "3", "// Ignore one byte after IEData (which is 0x00)", "\n", "}", "\n", "}", "\n", "return", "&", "UDHList", "{", "Data", ":", "udhData", "}", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "}" ]
// New parses the given binary data and returns a Data object, // or nil if the field Name is unknown.
[ "New", "parses", "the", "given", "binary", "data", "and", "returns", "a", "Data", "object", "or", "nil", "if", "the", "field", "Name", "is", "unknown", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdufield/body.go#L20-L90
16,807
fiorix/go-smpp
smpp/transmitter.go
handlePDU
func (t *Transmitter) handlePDU(f HandlerFunc) { for { p, err := t.cl.Read() if err != nil || p == nil { break } seq := p.Header().Seq t.tx.Lock() rc := t.tx.inflight[seq] t.tx.Unlock() if rc != nil { rc <- &tx{PDU: p} } else if f != nil { f(p) } if p.Header().ID == pdu.DeliverSMID { // Send DeliverSMResp pResp := pdu.NewDeliverSMRespSeq(p.Header().Seq) t.cl.Write(pResp) } } t.tx.Lock() for _, rc := range t.tx.inflight { rc <- &tx{Err: ErrNotConnected} } t.tx.Unlock() }
go
func (t *Transmitter) handlePDU(f HandlerFunc) { for { p, err := t.cl.Read() if err != nil || p == nil { break } seq := p.Header().Seq t.tx.Lock() rc := t.tx.inflight[seq] t.tx.Unlock() if rc != nil { rc <- &tx{PDU: p} } else if f != nil { f(p) } if p.Header().ID == pdu.DeliverSMID { // Send DeliverSMResp pResp := pdu.NewDeliverSMRespSeq(p.Header().Seq) t.cl.Write(pResp) } } t.tx.Lock() for _, rc := range t.tx.inflight { rc <- &tx{Err: ErrNotConnected} } t.tx.Unlock() }
[ "func", "(", "t", "*", "Transmitter", ")", "handlePDU", "(", "f", "HandlerFunc", ")", "{", "for", "{", "p", ",", "err", ":=", "t", ".", "cl", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "||", "p", "==", "nil", "{", "break", "\n", "}", "\n", "seq", ":=", "p", ".", "Header", "(", ")", ".", "Seq", "\n", "t", ".", "tx", ".", "Lock", "(", ")", "\n", "rc", ":=", "t", ".", "tx", ".", "inflight", "[", "seq", "]", "\n", "t", ".", "tx", ".", "Unlock", "(", ")", "\n", "if", "rc", "!=", "nil", "{", "rc", "<-", "&", "tx", "{", "PDU", ":", "p", "}", "\n", "}", "else", "if", "f", "!=", "nil", "{", "f", "(", "p", ")", "\n", "}", "\n", "if", "p", ".", "Header", "(", ")", ".", "ID", "==", "pdu", ".", "DeliverSMID", "{", "// Send DeliverSMResp", "pResp", ":=", "pdu", ".", "NewDeliverSMRespSeq", "(", "p", ".", "Header", "(", ")", ".", "Seq", ")", "\n", "t", ".", "cl", ".", "Write", "(", "pResp", ")", "\n", "}", "\n", "}", "\n", "t", ".", "tx", ".", "Lock", "(", ")", "\n", "for", "_", ",", "rc", ":=", "range", "t", ".", "tx", ".", "inflight", "{", "rc", "<-", "&", "tx", "{", "Err", ":", "ErrNotConnected", "}", "\n", "}", "\n", "t", ".", "tx", ".", "Unlock", "(", ")", "\n", "}" ]
// f is only set on transceiver.
[ "f", "is", "only", "set", "on", "transceiver", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/transmitter.go#L116-L141
16,808
fiorix/go-smpp
smpp/transmitter.go
newUnsucessDest
func newUnsucessDest(p pdufield.UnSme) UnsucessDest { unDest := UnsucessDest{} unDest.AddrTON, _ = p.Ton.Raw().(uint8) // if there is an error default value will be set unDest.AddrNPI, _ = p.Npi.Raw().(uint8) unDest.Address = string(p.DestAddr.Bytes()) unDest.Error = pdu.Status(binary.BigEndian.Uint32(p.ErrCode.Bytes())) return unDest }
go
func newUnsucessDest(p pdufield.UnSme) UnsucessDest { unDest := UnsucessDest{} unDest.AddrTON, _ = p.Ton.Raw().(uint8) // if there is an error default value will be set unDest.AddrNPI, _ = p.Npi.Raw().(uint8) unDest.Address = string(p.DestAddr.Bytes()) unDest.Error = pdu.Status(binary.BigEndian.Uint32(p.ErrCode.Bytes())) return unDest }
[ "func", "newUnsucessDest", "(", "p", "pdufield", ".", "UnSme", ")", "UnsucessDest", "{", "unDest", ":=", "UnsucessDest", "{", "}", "\n", "unDest", ".", "AddrTON", ",", "_", "=", "p", ".", "Ton", ".", "Raw", "(", ")", ".", "(", "uint8", ")", "// if there is an error default value will be set", "\n", "unDest", ".", "AddrNPI", ",", "_", "=", "p", ".", "Npi", ".", "Raw", "(", ")", ".", "(", "uint8", ")", "\n", "unDest", ".", "Address", "=", "string", "(", "p", ".", "DestAddr", ".", "Bytes", "(", ")", ")", "\n", "unDest", ".", "Error", "=", "pdu", ".", "Status", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "p", ".", "ErrCode", ".", "Bytes", "(", ")", ")", ")", "\n", "return", "unDest", "\n", "}" ]
// newUnsucessDest returns a new UnsucessDest constructed from a UnSme struct
[ "newUnsucessDest", "returns", "a", "new", "UnsucessDest", "constructed", "from", "a", "UnSme", "struct" ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/transmitter.go#L163-L170
16,809
fiorix/go-smpp
smpp/transmitter.go
Resp
func (sm *ShortMessage) Resp() pdu.Body { sm.resp.Lock() defer sm.resp.Unlock() return sm.resp.p }
go
func (sm *ShortMessage) Resp() pdu.Body { sm.resp.Lock() defer sm.resp.Unlock() return sm.resp.p }
[ "func", "(", "sm", "*", "ShortMessage", ")", "Resp", "(", ")", "pdu", ".", "Body", "{", "sm", ".", "resp", ".", "Lock", "(", ")", "\n", "defer", "sm", ".", "resp", ".", "Unlock", "(", ")", "\n", "return", "sm", ".", "resp", ".", "p", "\n", "}" ]
// Resp returns the response PDU, or nil if not set.
[ "Resp", "returns", "the", "response", "PDU", "or", "nil", "if", "not", "set", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/transmitter.go#L206-L210
16,810
fiorix/go-smpp
smpp/transmitter.go
Submit
func (t *Transmitter) Submit(sm *ShortMessage) (*ShortMessage, error) { if len(sm.DstList) > 0 || len(sm.DLs) > 0 { // if we have a single destination address add it to the list if sm.Dst != "" { sm.DstList = append(sm.DstList, sm.Dst) } p := pdu.NewSubmitMulti(sm.TLVFields) return t.submitMsgMulti(sm, p, uint8(sm.Text.Type())) } p := pdu.NewSubmitSM(sm.TLVFields) return t.submitMsg(sm, p, uint8(sm.Text.Type())) }
go
func (t *Transmitter) Submit(sm *ShortMessage) (*ShortMessage, error) { if len(sm.DstList) > 0 || len(sm.DLs) > 0 { // if we have a single destination address add it to the list if sm.Dst != "" { sm.DstList = append(sm.DstList, sm.Dst) } p := pdu.NewSubmitMulti(sm.TLVFields) return t.submitMsgMulti(sm, p, uint8(sm.Text.Type())) } p := pdu.NewSubmitSM(sm.TLVFields) return t.submitMsg(sm, p, uint8(sm.Text.Type())) }
[ "func", "(", "t", "*", "Transmitter", ")", "Submit", "(", "sm", "*", "ShortMessage", ")", "(", "*", "ShortMessage", ",", "error", ")", "{", "if", "len", "(", "sm", ".", "DstList", ")", ">", "0", "||", "len", "(", "sm", ".", "DLs", ")", ">", "0", "{", "// if we have a single destination address add it to the list", "if", "sm", ".", "Dst", "!=", "\"", "\"", "{", "sm", ".", "DstList", "=", "append", "(", "sm", ".", "DstList", ",", "sm", ".", "Dst", ")", "\n", "}", "\n", "p", ":=", "pdu", ".", "NewSubmitMulti", "(", "sm", ".", "TLVFields", ")", "\n", "return", "t", ".", "submitMsgMulti", "(", "sm", ",", "p", ",", "uint8", "(", "sm", ".", "Text", ".", "Type", "(", ")", ")", ")", "\n", "}", "\n", "p", ":=", "pdu", ".", "NewSubmitSM", "(", "sm", ".", "TLVFields", ")", "\n", "return", "t", ".", "submitMsg", "(", "sm", ",", "p", ",", "uint8", "(", "sm", ".", "Text", ".", "Type", "(", ")", ")", ")", "\n", "}" ]
// Submit sends a short message and returns and updates the given // sm with the response status. It returns the same sm object.
[ "Submit", "sends", "a", "short", "message", "and", "returns", "and", "updates", "the", "given", "sm", "with", "the", "response", "status", ".", "It", "returns", "the", "same", "sm", "object", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/transmitter.go#L314-L325
16,811
fiorix/go-smpp
smpp/pdu/pdutlv/tlv_list.go
DecodeTLV
func DecodeTLV(r *bytes.Buffer) (Map, error) { t := make(Map) for r.Len() >= 4 { b := r.Next(4) ft := Tag(binary.BigEndian.Uint16(b[0:2])) fl := binary.BigEndian.Uint16(b[2:4]) if r.Len() < int(fl) { return nil, fmt.Errorf("not enough data for tag %s: want %d, have %d", ft.Hex(), fl, r.Len()) } b = r.Next(int(fl)) t[ft] = &Field{ Tag: ft, Data: b, } } return t, nil }
go
func DecodeTLV(r *bytes.Buffer) (Map, error) { t := make(Map) for r.Len() >= 4 { b := r.Next(4) ft := Tag(binary.BigEndian.Uint16(b[0:2])) fl := binary.BigEndian.Uint16(b[2:4]) if r.Len() < int(fl) { return nil, fmt.Errorf("not enough data for tag %s: want %d, have %d", ft.Hex(), fl, r.Len()) } b = r.Next(int(fl)) t[ft] = &Field{ Tag: ft, Data: b, } } return t, nil }
[ "func", "DecodeTLV", "(", "r", "*", "bytes", ".", "Buffer", ")", "(", "Map", ",", "error", ")", "{", "t", ":=", "make", "(", "Map", ")", "\n", "for", "r", ".", "Len", "(", ")", ">=", "4", "{", "b", ":=", "r", ".", "Next", "(", "4", ")", "\n", "ft", ":=", "Tag", "(", "binary", ".", "BigEndian", ".", "Uint16", "(", "b", "[", "0", ":", "2", "]", ")", ")", "\n", "fl", ":=", "binary", ".", "BigEndian", ".", "Uint16", "(", "b", "[", "2", ":", "4", "]", ")", "\n", "if", "r", ".", "Len", "(", ")", "<", "int", "(", "fl", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ft", ".", "Hex", "(", ")", ",", "fl", ",", "r", ".", "Len", "(", ")", ")", "\n", "}", "\n", "b", "=", "r", ".", "Next", "(", "int", "(", "fl", ")", ")", "\n", "t", "[", "ft", "]", "=", "&", "Field", "{", "Tag", ":", "ft", ",", "Data", ":", "b", ",", "}", "\n", "}", "\n", "return", "t", ",", "nil", "\n", "}" ]
// DecodeTLV scans the given byte slice to build a Map from binary data.
[ "DecodeTLV", "scans", "the", "given", "byte", "slice", "to", "build", "a", "Map", "from", "binary", "data", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdutlv/tlv_list.go#L14-L31
16,812
fiorix/go-smpp
smpp/receiver.go
Bind
func (r *Receiver) Bind() <-chan ConnStatus { r.cl.Lock() defer r.cl.Unlock() r.chanClose = make(chan struct{}) if r.cl.client != nil { return r.cl.Status } c := &client{ Addr: r.Addr, TLS: r.TLS, EnquireLink: r.EnquireLink, EnquireLinkTimeout: r.EnquireLinkTimeout, Status: make(chan ConnStatus, 1), BindFunc: r.bindFunc, BindInterval: r.BindInterval, } r.cl.client = c c.init() go c.Bind() // Set up message merging if requested if r.MergeInterval > 0 { if r.MergeCleanupInterval == 0 { r.MergeCleanupInterval = 1 * time.Second } r.mg.mergeHolders = make(map[int]*MergeHolder) go r.mergeCleaner() } return c.Status }
go
func (r *Receiver) Bind() <-chan ConnStatus { r.cl.Lock() defer r.cl.Unlock() r.chanClose = make(chan struct{}) if r.cl.client != nil { return r.cl.Status } c := &client{ Addr: r.Addr, TLS: r.TLS, EnquireLink: r.EnquireLink, EnquireLinkTimeout: r.EnquireLinkTimeout, Status: make(chan ConnStatus, 1), BindFunc: r.bindFunc, BindInterval: r.BindInterval, } r.cl.client = c c.init() go c.Bind() // Set up message merging if requested if r.MergeInterval > 0 { if r.MergeCleanupInterval == 0 { r.MergeCleanupInterval = 1 * time.Second } r.mg.mergeHolders = make(map[int]*MergeHolder) go r.mergeCleaner() } return c.Status }
[ "func", "(", "r", "*", "Receiver", ")", "Bind", "(", ")", "<-", "chan", "ConnStatus", "{", "r", ".", "cl", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "cl", ".", "Unlock", "(", ")", "\n\n", "r", ".", "chanClose", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "if", "r", ".", "cl", ".", "client", "!=", "nil", "{", "return", "r", ".", "cl", ".", "Status", "\n", "}", "\n\n", "c", ":=", "&", "client", "{", "Addr", ":", "r", ".", "Addr", ",", "TLS", ":", "r", ".", "TLS", ",", "EnquireLink", ":", "r", ".", "EnquireLink", ",", "EnquireLinkTimeout", ":", "r", ".", "EnquireLinkTimeout", ",", "Status", ":", "make", "(", "chan", "ConnStatus", ",", "1", ")", ",", "BindFunc", ":", "r", ".", "bindFunc", ",", "BindInterval", ":", "r", ".", "BindInterval", ",", "}", "\n", "r", ".", "cl", ".", "client", "=", "c", "\n\n", "c", ".", "init", "(", ")", "\n", "go", "c", ".", "Bind", "(", ")", "\n\n", "// Set up message merging if requested", "if", "r", ".", "MergeInterval", ">", "0", "{", "if", "r", ".", "MergeCleanupInterval", "==", "0", "{", "r", ".", "MergeCleanupInterval", "=", "1", "*", "time", ".", "Second", "\n", "}", "\n\n", "r", ".", "mg", ".", "mergeHolders", "=", "make", "(", "map", "[", "int", "]", "*", "MergeHolder", ")", "\n", "go", "r", ".", "mergeCleaner", "(", ")", "\n", "}", "\n\n", "return", "c", ".", "Status", "\n", "}" ]
// Bind starts the Receiver. It creates a persistent connection // to the server, update its status via the returned channel, // and calls the registered Handler when new PDU arrives. // // Bind implements the ClientConn interface.
[ "Bind", "starts", "the", "Receiver", ".", "It", "creates", "a", "persistent", "connection", "to", "the", "server", "update", "its", "status", "via", "the", "returned", "channel", "and", "calls", "the", "registered", "Handler", "when", "new", "PDU", "arrives", ".", "Bind", "implements", "the", "ClientConn", "interface", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/receiver.go#L71-L106
16,813
fiorix/go-smpp
smpp/pdu/header.go
DecodeHeader
func DecodeHeader(r io.Reader) (*Header, error) { b := make([]byte, HeaderLen) _, err := io.ReadFull(r, b) if err != nil { return nil, err } l := binary.BigEndian.Uint32(b[0:4]) if l < HeaderLen { return nil, fmt.Errorf("PDU too small: %d < %d", l, HeaderLen) } if l > MaxSize { return nil, fmt.Errorf("PDU too large: %d > %d", l, MaxSize) } hdr := &Header{ Len: l, ID: ID(binary.BigEndian.Uint32(b[4:8])), Status: Status(binary.BigEndian.Uint32(b[8:12])), Seq: binary.BigEndian.Uint32(b[12:16]), } return hdr, nil }
go
func DecodeHeader(r io.Reader) (*Header, error) { b := make([]byte, HeaderLen) _, err := io.ReadFull(r, b) if err != nil { return nil, err } l := binary.BigEndian.Uint32(b[0:4]) if l < HeaderLen { return nil, fmt.Errorf("PDU too small: %d < %d", l, HeaderLen) } if l > MaxSize { return nil, fmt.Errorf("PDU too large: %d > %d", l, MaxSize) } hdr := &Header{ Len: l, ID: ID(binary.BigEndian.Uint32(b[4:8])), Status: Status(binary.BigEndian.Uint32(b[8:12])), Seq: binary.BigEndian.Uint32(b[12:16]), } return hdr, nil }
[ "func", "DecodeHeader", "(", "r", "io", ".", "Reader", ")", "(", "*", "Header", ",", "error", ")", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "HeaderLen", ")", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "l", ":=", "binary", ".", "BigEndian", ".", "Uint32", "(", "b", "[", "0", ":", "4", "]", ")", "\n", "if", "l", "<", "HeaderLen", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ",", "HeaderLen", ")", "\n", "}", "\n", "if", "l", ">", "MaxSize", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ",", "MaxSize", ")", "\n", "}", "\n", "hdr", ":=", "&", "Header", "{", "Len", ":", "l", ",", "ID", ":", "ID", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "b", "[", "4", ":", "8", "]", ")", ")", ",", "Status", ":", "Status", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "b", "[", "8", ":", "12", "]", ")", ")", ",", "Seq", ":", "binary", ".", "BigEndian", ".", "Uint32", "(", "b", "[", "12", ":", "16", "]", ")", ",", "}", "\n", "return", "hdr", ",", "nil", "\n", "}" ]
// DecodeHeader decodes binary PDU header data.
[ "DecodeHeader", "decodes", "binary", "PDU", "header", "data", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/header.go#L68-L88
16,814
fiorix/go-smpp
smpp/pdu/header.go
SerializeTo
func (h *Header) SerializeTo(w io.Writer) error { b := make([]byte, HeaderLen) binary.BigEndian.PutUint32(b[0:4], h.Len) binary.BigEndian.PutUint32(b[4:8], uint32(h.ID)) binary.BigEndian.PutUint32(b[8:12], uint32(h.Status)) binary.BigEndian.PutUint32(b[12:16], h.Seq) _, err := w.Write(b) return err }
go
func (h *Header) SerializeTo(w io.Writer) error { b := make([]byte, HeaderLen) binary.BigEndian.PutUint32(b[0:4], h.Len) binary.BigEndian.PutUint32(b[4:8], uint32(h.ID)) binary.BigEndian.PutUint32(b[8:12], uint32(h.Status)) binary.BigEndian.PutUint32(b[12:16], h.Seq) _, err := w.Write(b) return err }
[ "func", "(", "h", "*", "Header", ")", "SerializeTo", "(", "w", "io", ".", "Writer", ")", "error", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "HeaderLen", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "b", "[", "0", ":", "4", "]", ",", "h", ".", "Len", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "b", "[", "4", ":", "8", "]", ",", "uint32", "(", "h", ".", "ID", ")", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "b", "[", "8", ":", "12", "]", ",", "uint32", "(", "h", ".", "Status", ")", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "b", "[", "12", ":", "16", "]", ",", "h", ".", "Seq", ")", "\n", "_", ",", "err", ":=", "w", ".", "Write", "(", "b", ")", "\n", "return", "err", "\n", "}" ]
// SerializeTo serializes the Header to its binary form to the given writer.
[ "SerializeTo", "serializes", "the", "Header", "to", "its", "binary", "form", "to", "the", "given", "writer", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/header.go#L91-L99
16,815
fiorix/go-smpp
smpp/pdu/types.go
NewGenericNACK
func NewGenericNACK() Body { b := newGenericNACK(&Header{ID: GenericNACKID}) b.init() return b }
go
func NewGenericNACK() Body { b := newGenericNACK(&Header{ID: GenericNACKID}) b.init() return b }
[ "func", "NewGenericNACK", "(", ")", "Body", "{", "b", ":=", "newGenericNACK", "(", "&", "Header", "{", "ID", ":", "GenericNACKID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewGenericNACK creates and initializes a GenericNACK PDU.
[ "NewGenericNACK", "creates", "and", "initializes", "a", "GenericNACK", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L51-L55
16,816
fiorix/go-smpp
smpp/pdu/types.go
NewBindReceiver
func NewBindReceiver() Body { b := newBind(&Header{ID: BindReceiverID}) b.init() return b }
go
func NewBindReceiver() Body { b := newBind(&Header{ID: BindReceiverID}) b.init() return b }
[ "func", "NewBindReceiver", "(", ")", "Body", "{", "b", ":=", "newBind", "(", "&", "Header", "{", "ID", ":", "BindReceiverID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewBindReceiver creates a new Bind PDU.
[ "NewBindReceiver", "creates", "a", "new", "Bind", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L75-L79
16,817
fiorix/go-smpp
smpp/pdu/types.go
NewBindTransceiver
func NewBindTransceiver() Body { b := newBind(&Header{ID: BindTransceiverID}) b.init() return b }
go
func NewBindTransceiver() Body { b := newBind(&Header{ID: BindTransceiverID}) b.init() return b }
[ "func", "NewBindTransceiver", "(", ")", "Body", "{", "b", ":=", "newBind", "(", "&", "Header", "{", "ID", ":", "BindTransceiverID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewBindTransceiver creates a new Bind PDU.
[ "NewBindTransceiver", "creates", "a", "new", "Bind", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L82-L86
16,818
fiorix/go-smpp
smpp/pdu/types.go
NewBindTransmitter
func NewBindTransmitter() Body { b := newBind(&Header{ID: BindTransmitterID}) b.init() return b }
go
func NewBindTransmitter() Body { b := newBind(&Header{ID: BindTransmitterID}) b.init() return b }
[ "func", "NewBindTransmitter", "(", ")", "Body", "{", "b", ":=", "newBind", "(", "&", "Header", "{", "ID", ":", "BindTransmitterID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewBindTransmitter creates a new Bind PDU.
[ "NewBindTransmitter", "creates", "a", "new", "Bind", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L89-L93
16,819
fiorix/go-smpp
smpp/pdu/types.go
NewBindReceiverResp
func NewBindReceiverResp() Body { b := newBindResp(&Header{ID: BindReceiverRespID}) b.init() return b }
go
func NewBindReceiverResp() Body { b := newBindResp(&Header{ID: BindReceiverRespID}) b.init() return b }
[ "func", "NewBindReceiverResp", "(", ")", "Body", "{", "b", ":=", "newBindResp", "(", "&", "Header", "{", "ID", ":", "BindReceiverRespID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewBindReceiverResp creates and initializes a new BindResp PDU.
[ "NewBindReceiverResp", "creates", "and", "initializes", "a", "new", "BindResp", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L106-L110
16,820
fiorix/go-smpp
smpp/pdu/types.go
NewBindTransceiverResp
func NewBindTransceiverResp() Body { b := newBindResp(&Header{ID: BindTransceiverRespID}) b.init() return b }
go
func NewBindTransceiverResp() Body { b := newBindResp(&Header{ID: BindTransceiverRespID}) b.init() return b }
[ "func", "NewBindTransceiverResp", "(", ")", "Body", "{", "b", ":=", "newBindResp", "(", "&", "Header", "{", "ID", ":", "BindTransceiverRespID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewBindTransceiverResp creates and initializes a new BindResp PDU.
[ "NewBindTransceiverResp", "creates", "and", "initializes", "a", "new", "BindResp", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L113-L117
16,821
fiorix/go-smpp
smpp/pdu/types.go
NewBindTransmitterResp
func NewBindTransmitterResp() Body { b := newBindResp(&Header{ID: BindTransmitterRespID}) b.init() return b }
go
func NewBindTransmitterResp() Body { b := newBindResp(&Header{ID: BindTransmitterRespID}) b.init() return b }
[ "func", "NewBindTransmitterResp", "(", ")", "Body", "{", "b", ":=", "newBindResp", "(", "&", "Header", "{", "ID", ":", "BindTransmitterRespID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewBindTransmitterResp creates and initializes a new BindResp PDU.
[ "NewBindTransmitterResp", "creates", "and", "initializes", "a", "new", "BindResp", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L120-L124
16,822
fiorix/go-smpp
smpp/pdu/types.go
NewQuerySM
func NewQuerySM() Body { b := newQuerySM(&Header{ID: QuerySMID}) b.init() return b }
go
func NewQuerySM() Body { b := newQuerySM(&Header{ID: QuerySMID}) b.init() return b }
[ "func", "NewQuerySM", "(", ")", "Body", "{", "b", ":=", "newQuerySM", "(", "&", "Header", "{", "ID", ":", "QuerySMID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewQuerySM creates and initializes a new QuerySM PDU.
[ "NewQuerySM", "creates", "and", "initializes", "a", "new", "QuerySM", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L142-L146
16,823
fiorix/go-smpp
smpp/pdu/types.go
NewQuerySMResp
func NewQuerySMResp() Body { b := newQuerySMResp(&Header{ID: QuerySMRespID}) b.init() return b }
go
func NewQuerySMResp() Body { b := newQuerySMResp(&Header{ID: QuerySMRespID}) b.init() return b }
[ "func", "NewQuerySMResp", "(", ")", "Body", "{", "b", ":=", "newQuerySMResp", "(", "&", "Header", "{", "ID", ":", "QuerySMRespID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewQuerySMResp creates and initializes a new QuerySMResp PDU.
[ "NewQuerySMResp", "creates", "and", "initializes", "a", "new", "QuerySMResp", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L164-L168
16,824
fiorix/go-smpp
smpp/pdu/types.go
NewSubmitSM
func NewSubmitSM(fields pdutlv.Fields) Body { b := newSubmitSM(&Header{ID: SubmitSMID}) b.init() for tag, value := range fields { b.t.Set(tag, value) } return b }
go
func NewSubmitSM(fields pdutlv.Fields) Body { b := newSubmitSM(&Header{ID: SubmitSMID}) b.init() for tag, value := range fields { b.t.Set(tag, value) } return b }
[ "func", "NewSubmitSM", "(", "fields", "pdutlv", ".", "Fields", ")", "Body", "{", "b", ":=", "newSubmitSM", "(", "&", "Header", "{", "ID", ":", "SubmitSMID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "for", "tag", ",", "value", ":=", "range", "fields", "{", "b", ".", "t", ".", "Set", "(", "tag", ",", "value", ")", "\n", "}", "\n", "return", "b", "\n", "}" ]
// NewSubmitSM creates and initializes a new SubmitSM PDU.
[ "NewSubmitSM", "creates", "and", "initializes", "a", "new", "SubmitSM", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L200-L207
16,825
fiorix/go-smpp
smpp/pdu/types.go
NewSubmitSMResp
func NewSubmitSMResp() Body { b := newSubmitSMResp(&Header{ID: SubmitSMRespID}) b.init() return b }
go
func NewSubmitSMResp() Body { b := newSubmitSMResp(&Header{ID: SubmitSMRespID}) b.init() return b }
[ "func", "NewSubmitSMResp", "(", ")", "Body", "{", "b", ":=", "newSubmitSMResp", "(", "&", "Header", "{", "ID", ":", "SubmitSMRespID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewSubmitSMResp creates and initializes a new SubmitSMResp PDU.
[ "NewSubmitSMResp", "creates", "and", "initializes", "a", "new", "SubmitSMResp", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L222-L226
16,826
fiorix/go-smpp
smpp/pdu/types.go
NewSubmitMulti
func NewSubmitMulti(fields pdutlv.Fields) Body { b := newSubmitMulti(&Header{ID: SubmitMultiID}) b.init() for tag, value := range fields { b.t.Set(tag, value) } return b }
go
func NewSubmitMulti(fields pdutlv.Fields) Body { b := newSubmitMulti(&Header{ID: SubmitMultiID}) b.init() for tag, value := range fields { b.t.Set(tag, value) } return b }
[ "func", "NewSubmitMulti", "(", "fields", "pdutlv", ".", "Fields", ")", "Body", "{", "b", ":=", "newSubmitMulti", "(", "&", "Header", "{", "ID", ":", "SubmitMultiID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "for", "tag", ",", "value", ":=", "range", "fields", "{", "b", ".", "t", ".", "Set", "(", "tag", ",", "value", ")", "\n", "}", "\n", "return", "b", "\n", "}" ]
// NewSubmitMulti creates and initializes a new SubmitMulti PDU.
[ "NewSubmitMulti", "creates", "and", "initializes", "a", "new", "SubmitMulti", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L257-L264
16,827
fiorix/go-smpp
smpp/pdu/types.go
NewSubmitMultiResp
func NewSubmitMultiResp() Body { b := newSubmitMultiResp(&Header{ID: SubmitMultiRespID}) b.init() return b }
go
func NewSubmitMultiResp() Body { b := newSubmitMultiResp(&Header{ID: SubmitMultiRespID}) b.init() return b }
[ "func", "NewSubmitMultiResp", "(", ")", "Body", "{", "b", ":=", "newSubmitMultiResp", "(", "&", "Header", "{", "ID", ":", "SubmitMultiRespID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewSubmitMultiResp creates and initializes a new SubmitMultiResp PDU.
[ "NewSubmitMultiResp", "creates", "and", "initializes", "a", "new", "SubmitMultiResp", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L281-L285
16,828
fiorix/go-smpp
smpp/pdu/types.go
NewDeliverSM
func NewDeliverSM() Body { b := newDeliverSM(&Header{ID: DeliverSMID}) b.init() return b }
go
func NewDeliverSM() Body { b := newDeliverSM(&Header{ID: DeliverSMID}) b.init() return b }
[ "func", "NewDeliverSM", "(", ")", "Body", "{", "b", ":=", "newDeliverSM", "(", "&", "Header", "{", "ID", ":", "DeliverSMID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewDeliverSM creates and initializes a new DeliverSM PDU.
[ "NewDeliverSM", "creates", "and", "initializes", "a", "new", "DeliverSM", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L319-L323
16,829
fiorix/go-smpp
smpp/pdu/types.go
NewDeliverSMResp
func NewDeliverSMResp() Body { b := newDeliverSMResp(&Header{ID: DeliverSMRespID}) b.init() return b }
go
func NewDeliverSMResp() Body { b := newDeliverSMResp(&Header{ID: DeliverSMRespID}) b.init() return b }
[ "func", "NewDeliverSMResp", "(", ")", "Body", "{", "b", ":=", "newDeliverSMResp", "(", "&", "Header", "{", "ID", ":", "DeliverSMRespID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewDeliverSMResp creates and initializes a new DeliverSMResp PDU.
[ "NewDeliverSMResp", "creates", "and", "initializes", "a", "new", "DeliverSMResp", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L338-L342
16,830
fiorix/go-smpp
smpp/pdu/types.go
NewDeliverSMRespSeq
func NewDeliverSMRespSeq(seq uint32) Body { b := newDeliverSMResp(&Header{ID: DeliverSMRespID, Seq: seq}) b.init() return b }
go
func NewDeliverSMRespSeq(seq uint32) Body { b := newDeliverSMResp(&Header{ID: DeliverSMRespID, Seq: seq}) b.init() return b }
[ "func", "NewDeliverSMRespSeq", "(", "seq", "uint32", ")", "Body", "{", "b", ":=", "newDeliverSMResp", "(", "&", "Header", "{", "ID", ":", "DeliverSMRespID", ",", "Seq", ":", "seq", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewDeliverSMRespSeq creates and initializes a new DeliverSMResp PDU for a specific seq.
[ "NewDeliverSMRespSeq", "creates", "and", "initializes", "a", "new", "DeliverSMResp", "PDU", "for", "a", "specific", "seq", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L345-L349
16,831
fiorix/go-smpp
smpp/pdu/types.go
NewUnbind
func NewUnbind() Body { b := newUnbind(&Header{ID: UnbindID}) b.init() return b }
go
func NewUnbind() Body { b := newUnbind(&Header{ID: UnbindID}) b.init() return b }
[ "func", "NewUnbind", "(", ")", "Body", "{", "b", ":=", "newUnbind", "(", "&", "Header", "{", "ID", ":", "UnbindID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewUnbind creates and initializes a Unbind PDU.
[ "NewUnbind", "creates", "and", "initializes", "a", "Unbind", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L359-L363
16,832
fiorix/go-smpp
smpp/pdu/types.go
NewUnbindResp
func NewUnbindResp() Body { b := newUnbindResp(&Header{ID: UnbindRespID}) b.init() return b }
go
func NewUnbindResp() Body { b := newUnbindResp(&Header{ID: UnbindRespID}) b.init() return b }
[ "func", "NewUnbindResp", "(", ")", "Body", "{", "b", ":=", "newUnbindResp", "(", "&", "Header", "{", "ID", ":", "UnbindRespID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewUnbindResp creates and initializes a UnbindResp PDU.
[ "NewUnbindResp", "creates", "and", "initializes", "a", "UnbindResp", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L373-L377
16,833
fiorix/go-smpp
smpp/pdu/types.go
NewEnquireLink
func NewEnquireLink() Body { b := newEnquireLink(&Header{ID: EnquireLinkID}) b.init() return b }
go
func NewEnquireLink() Body { b := newEnquireLink(&Header{ID: EnquireLinkID}) b.init() return b }
[ "func", "NewEnquireLink", "(", ")", "Body", "{", "b", ":=", "newEnquireLink", "(", "&", "Header", "{", "ID", ":", "EnquireLinkID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewEnquireLink creates and initializes a EnquireLink PDU.
[ "NewEnquireLink", "creates", "and", "initializes", "a", "EnquireLink", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L387-L391
16,834
fiorix/go-smpp
smpp/pdu/types.go
NewEnquireLinkResp
func NewEnquireLinkResp() Body { b := newEnquireLinkResp(&Header{ID: EnquireLinkRespID}) b.init() return b }
go
func NewEnquireLinkResp() Body { b := newEnquireLinkResp(&Header{ID: EnquireLinkRespID}) b.init() return b }
[ "func", "NewEnquireLinkResp", "(", ")", "Body", "{", "b", ":=", "newEnquireLinkResp", "(", "&", "Header", "{", "ID", ":", "EnquireLinkRespID", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewEnquireLinkResp creates and initializes a EnquireLinkResp PDU.
[ "NewEnquireLinkResp", "creates", "and", "initializes", "a", "EnquireLinkResp", "PDU", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L401-L405
16,835
fiorix/go-smpp
smpp/pdu/types.go
NewEnquireLinkRespSeq
func NewEnquireLinkRespSeq(seq uint32) Body { b := newEnquireLinkResp(&Header{ID: EnquireLinkRespID, Seq: seq}) b.init() return b }
go
func NewEnquireLinkRespSeq(seq uint32) Body { b := newEnquireLinkResp(&Header{ID: EnquireLinkRespID, Seq: seq}) b.init() return b }
[ "func", "NewEnquireLinkRespSeq", "(", "seq", "uint32", ")", "Body", "{", "b", ":=", "newEnquireLinkResp", "(", "&", "Header", "{", "ID", ":", "EnquireLinkRespID", ",", "Seq", ":", "seq", "}", ")", "\n", "b", ".", "init", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewEnquireLinkRespSeq creates and initializes a EnquireLinkResp PDU for a specific seq.
[ "NewEnquireLinkRespSeq", "creates", "and", "initializes", "a", "EnquireLinkResp", "PDU", "for", "a", "specific", "seq", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/types.go#L408-L412
16,836
fiorix/go-smpp
smpp/pdu/pdutlv/tlv_body.go
NewTLV
func NewTLV(tag Tag, value []byte) Body { return &Field{ Tag: tag, Data: value } }
go
func NewTLV(tag Tag, value []byte) Body { return &Field{ Tag: tag, Data: value } }
[ "func", "NewTLV", "(", "tag", "Tag", ",", "value", "[", "]", "byte", ")", "Body", "{", "return", "&", "Field", "{", "Tag", ":", "tag", ",", "Data", ":", "value", "}", "\n", "}" ]
// NewTLV parses the given binary data and returns a Data object, // or nil if the field Name is unknown.
[ "NewTLV", "parses", "the", "given", "binary", "data", "and", "returns", "a", "Data", "object", "or", "nil", "if", "the", "field", "Name", "is", "unknown", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdutlv/tlv_body.go#L22-L24
16,837
fiorix/go-smpp
smpp/conn.go
Dial
func Dial(addr string, TLS *tls.Config) (Conn, error) { if addr == "" { addr = "localhost:2775" } fd, err := net.Dial("tcp", addr) if err != nil { return nil, err } if TLS != nil { fd = tls.Client(fd, TLS) } c := &conn{ rwc: fd, r: bufio.NewReader(fd), w: bufio.NewWriter(fd), } return c, nil }
go
func Dial(addr string, TLS *tls.Config) (Conn, error) { if addr == "" { addr = "localhost:2775" } fd, err := net.Dial("tcp", addr) if err != nil { return nil, err } if TLS != nil { fd = tls.Client(fd, TLS) } c := &conn{ rwc: fd, r: bufio.NewReader(fd), w: bufio.NewWriter(fd), } return c, nil }
[ "func", "Dial", "(", "addr", "string", ",", "TLS", "*", "tls", ".", "Config", ")", "(", "Conn", ",", "error", ")", "{", "if", "addr", "==", "\"", "\"", "{", "addr", "=", "\"", "\"", "\n", "}", "\n", "fd", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "TLS", "!=", "nil", "{", "fd", "=", "tls", ".", "Client", "(", "fd", ",", "TLS", ")", "\n", "}", "\n", "c", ":=", "&", "conn", "{", "rwc", ":", "fd", ",", "r", ":", "bufio", ".", "NewReader", "(", "fd", ")", ",", "w", ":", "bufio", ".", "NewWriter", "(", "fd", ")", ",", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// Dial dials to the SMPP server and returns a Conn, or error. // TLS is only used if provided.
[ "Dial", "dials", "to", "the", "SMPP", "server", "and", "returns", "a", "Conn", "or", "error", ".", "TLS", "is", "only", "used", "if", "provided", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/conn.go#L58-L75
16,838
fiorix/go-smpp
smpp/conn.go
Set
func (cs *connSwitch) Set(c Conn) { cs.mu.Lock() if cs.c != nil { cs.c.Close() } cs.c = c cs.mu.Unlock() }
go
func (cs *connSwitch) Set(c Conn) { cs.mu.Lock() if cs.c != nil { cs.c.Close() } cs.c = c cs.mu.Unlock() }
[ "func", "(", "cs", "*", "connSwitch", ")", "Set", "(", "c", "Conn", ")", "{", "cs", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "cs", ".", "c", "!=", "nil", "{", "cs", ".", "c", ".", "Close", "(", ")", "\n", "}", "\n", "cs", ".", "c", "=", "c", "\n", "cs", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// Set sets the underlying Conn with the given one. // If we hold a Conn already, it will be closed before switching over.
[ "Set", "sets", "the", "underlying", "Conn", "with", "the", "given", "one", ".", "If", "we", "hold", "a", "Conn", "already", "it", "will", "be", "closed", "before", "switching", "over", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/conn.go#L121-L128
16,839
fiorix/go-smpp
smpp/conn.go
Close
func (cs *connSwitch) Close() error { cs.mu.Lock() defer cs.mu.Unlock() if cs.c == nil { return ErrNotConnected } err := cs.c.Close() cs.c = nil return err }
go
func (cs *connSwitch) Close() error { cs.mu.Lock() defer cs.mu.Unlock() if cs.c == nil { return ErrNotConnected } err := cs.c.Close() cs.c = nil return err }
[ "func", "(", "cs", "*", "connSwitch", ")", "Close", "(", ")", "error", "{", "cs", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "cs", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "cs", ".", "c", "==", "nil", "{", "return", "ErrNotConnected", "\n", "}", "\n", "err", ":=", "cs", ".", "c", ".", "Close", "(", ")", "\n", "cs", ".", "c", "=", "nil", "\n", "return", "err", "\n", "}" ]
// Close implements the Conn interface.
[ "Close", "implements", "the", "Conn", "interface", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/conn.go#L152-L161
16,840
fiorix/go-smpp
smpp/transceiver.go
Bind
func (t *Transceiver) Bind() <-chan ConnStatus { t.r = rand.New(rand.NewSource(time.Now().UnixNano())) t.cl.Lock() defer t.cl.Unlock() if t.cl.client != nil { return t.cl.Status } t.tx.Lock() t.tx.inflight = make(map[uint32]chan *tx) t.tx.Unlock() c := &client{ Addr: t.Addr, TLS: t.TLS, Status: make(chan ConnStatus, 1), BindFunc: t.bindFunc, EnquireLink: t.EnquireLink, EnquireLinkTimeout: t.EnquireLinkTimeout, RespTimeout: t.RespTimeout, WindowSize: t.WindowSize, RateLimiter: t.RateLimiter, BindInterval: t.BindInterval, } t.cl.client = c c.init() go c.Bind() return c.Status }
go
func (t *Transceiver) Bind() <-chan ConnStatus { t.r = rand.New(rand.NewSource(time.Now().UnixNano())) t.cl.Lock() defer t.cl.Unlock() if t.cl.client != nil { return t.cl.Status } t.tx.Lock() t.tx.inflight = make(map[uint32]chan *tx) t.tx.Unlock() c := &client{ Addr: t.Addr, TLS: t.TLS, Status: make(chan ConnStatus, 1), BindFunc: t.bindFunc, EnquireLink: t.EnquireLink, EnquireLinkTimeout: t.EnquireLinkTimeout, RespTimeout: t.RespTimeout, WindowSize: t.WindowSize, RateLimiter: t.RateLimiter, BindInterval: t.BindInterval, } t.cl.client = c c.init() go c.Bind() return c.Status }
[ "func", "(", "t", "*", "Transceiver", ")", "Bind", "(", ")", "<-", "chan", "ConnStatus", "{", "t", ".", "r", "=", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", ")", "\n", "t", ".", "cl", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "cl", ".", "Unlock", "(", ")", "\n", "if", "t", ".", "cl", ".", "client", "!=", "nil", "{", "return", "t", ".", "cl", ".", "Status", "\n", "}", "\n", "t", ".", "tx", ".", "Lock", "(", ")", "\n", "t", ".", "tx", ".", "inflight", "=", "make", "(", "map", "[", "uint32", "]", "chan", "*", "tx", ")", "\n", "t", ".", "tx", ".", "Unlock", "(", ")", "\n", "c", ":=", "&", "client", "{", "Addr", ":", "t", ".", "Addr", ",", "TLS", ":", "t", ".", "TLS", ",", "Status", ":", "make", "(", "chan", "ConnStatus", ",", "1", ")", ",", "BindFunc", ":", "t", ".", "bindFunc", ",", "EnquireLink", ":", "t", ".", "EnquireLink", ",", "EnquireLinkTimeout", ":", "t", ".", "EnquireLinkTimeout", ",", "RespTimeout", ":", "t", ".", "RespTimeout", ",", "WindowSize", ":", "t", ".", "WindowSize", ",", "RateLimiter", ":", "t", ".", "RateLimiter", ",", "BindInterval", ":", "t", ".", "BindInterval", ",", "}", "\n", "t", ".", "cl", ".", "client", "=", "c", "\n", "c", ".", "init", "(", ")", "\n", "go", "c", ".", "Bind", "(", ")", "\n", "return", "c", ".", "Status", "\n", "}" ]
// Bind implements the ClientConn interface.
[ "Bind", "implements", "the", "ClientConn", "interface", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/transceiver.go#L38-L64
16,841
fiorix/go-smpp
smpp/pdu/codec.go
init
func (pdu *codec) init() { if pdu.l == nil { pdu.l = pdufield.List{} } pdu.f = make(pdufield.Map) pdu.t = make(pdutlv.Map) if pdu.h.Seq == 0 { // If Seq not set pdu.h.Seq = atomic.AddUint32(&nextSeq, 1) } }
go
func (pdu *codec) init() { if pdu.l == nil { pdu.l = pdufield.List{} } pdu.f = make(pdufield.Map) pdu.t = make(pdutlv.Map) if pdu.h.Seq == 0 { // If Seq not set pdu.h.Seq = atomic.AddUint32(&nextSeq, 1) } }
[ "func", "(", "pdu", "*", "codec", ")", "init", "(", ")", "{", "if", "pdu", ".", "l", "==", "nil", "{", "pdu", ".", "l", "=", "pdufield", ".", "List", "{", "}", "\n", "}", "\n", "pdu", ".", "f", "=", "make", "(", "pdufield", ".", "Map", ")", "\n", "pdu", ".", "t", "=", "make", "(", "pdutlv", ".", "Map", ")", "\n", "if", "pdu", ".", "h", ".", "Seq", "==", "0", "{", "// If Seq not set", "pdu", ".", "h", ".", "Seq", "=", "atomic", ".", "AddUint32", "(", "&", "nextSeq", ",", "1", ")", "\n", "}", "\n", "}" ]
// init initializes the codec's list and maps and sets the header // sequence number.
[ "init", "initializes", "the", "codec", "s", "list", "and", "maps", "and", "sets", "the", "header", "sequence", "number", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/codec.go#L30-L39
16,842
fiorix/go-smpp
smpp/pdu/codec.go
setup
func (pdu *codec) setup(f pdufield.Map, t pdutlv.Map) { pdu.f, pdu.t = f, t }
go
func (pdu *codec) setup(f pdufield.Map, t pdutlv.Map) { pdu.f, pdu.t = f, t }
[ "func", "(", "pdu", "*", "codec", ")", "setup", "(", "f", "pdufield", ".", "Map", ",", "t", "pdutlv", ".", "Map", ")", "{", "pdu", ".", "f", ",", "pdu", ".", "t", "=", "f", ",", "t", "\n", "}" ]
// setup replaces the codec's current maps with the given ones.
[ "setup", "replaces", "the", "codec", "s", "current", "maps", "with", "the", "given", "ones", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/codec.go#L42-L44
16,843
fiorix/go-smpp
smpp/pdu/codec.go
Len
func (pdu *codec) Len() int { l := HeaderLen for _, f := range pdu.f { l += f.Len() } for _, t := range pdu.t { l += t.Len() } return l }
go
func (pdu *codec) Len() int { l := HeaderLen for _, f := range pdu.f { l += f.Len() } for _, t := range pdu.t { l += t.Len() } return l }
[ "func", "(", "pdu", "*", "codec", ")", "Len", "(", ")", "int", "{", "l", ":=", "HeaderLen", "\n", "for", "_", ",", "f", ":=", "range", "pdu", ".", "f", "{", "l", "+=", "f", ".", "Len", "(", ")", "\n", "}", "\n", "for", "_", ",", "t", ":=", "range", "pdu", ".", "t", "{", "l", "+=", "t", ".", "Len", "(", ")", "\n", "}", "\n", "return", "l", "\n", "}" ]
// Len implements the PDU interface.
[ "Len", "implements", "the", "PDU", "interface", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/codec.go#L52-L61
16,844
fiorix/go-smpp
smpp/pdu/codec.go
SerializeTo
func (pdu *codec) SerializeTo(w io.Writer) error { var b bytes.Buffer for _, k := range pdu.FieldList() { f, ok := pdu.f[k] if !ok { pdu.f.Set(k, nil) f = pdu.f[k] } if err := f.SerializeTo(&b); err != nil { return err } } for _, f := range pdu.TLVFields() { if err := f.SerializeTo(&b); err != nil { return err } } pdu.h.Len = uint32(pdu.Len()) err := pdu.h.SerializeTo(w) if err != nil { return err } _, err = io.Copy(w, &b) return err }
go
func (pdu *codec) SerializeTo(w io.Writer) error { var b bytes.Buffer for _, k := range pdu.FieldList() { f, ok := pdu.f[k] if !ok { pdu.f.Set(k, nil) f = pdu.f[k] } if err := f.SerializeTo(&b); err != nil { return err } } for _, f := range pdu.TLVFields() { if err := f.SerializeTo(&b); err != nil { return err } } pdu.h.Len = uint32(pdu.Len()) err := pdu.h.SerializeTo(w) if err != nil { return err } _, err = io.Copy(w, &b) return err }
[ "func", "(", "pdu", "*", "codec", ")", "SerializeTo", "(", "w", "io", ".", "Writer", ")", "error", "{", "var", "b", "bytes", ".", "Buffer", "\n", "for", "_", ",", "k", ":=", "range", "pdu", ".", "FieldList", "(", ")", "{", "f", ",", "ok", ":=", "pdu", ".", "f", "[", "k", "]", "\n", "if", "!", "ok", "{", "pdu", ".", "f", ".", "Set", "(", "k", ",", "nil", ")", "\n", "f", "=", "pdu", ".", "f", "[", "k", "]", "\n", "}", "\n", "if", "err", ":=", "f", ".", "SerializeTo", "(", "&", "b", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "for", "_", ",", "f", ":=", "range", "pdu", ".", "TLVFields", "(", ")", "{", "if", "err", ":=", "f", ".", "SerializeTo", "(", "&", "b", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "pdu", ".", "h", ".", "Len", "=", "uint32", "(", "pdu", ".", "Len", "(", ")", ")", "\n", "err", ":=", "pdu", ".", "h", ".", "SerializeTo", "(", "w", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "w", ",", "&", "b", ")", "\n", "return", "err", "\n", "}" ]
// SerializeTo implements the PDU interface.
[ "SerializeTo", "implements", "the", "PDU", "interface", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/codec.go#L79-L103
16,845
fiorix/go-smpp
smpp/pdu/pdutext/iso88595.go
Encode
func (s ISO88595) Encode() []byte { e := charmap.ISO8859_5.NewEncoder() es, _, err := transform.Bytes(e, s) if err != nil { return s } return es }
go
func (s ISO88595) Encode() []byte { e := charmap.ISO8859_5.NewEncoder() es, _, err := transform.Bytes(e, s) if err != nil { return s } return es }
[ "func", "(", "s", "ISO88595", ")", "Encode", "(", ")", "[", "]", "byte", "{", "e", ":=", "charmap", ".", "ISO8859_5", ".", "NewEncoder", "(", ")", "\n", "es", ",", "_", ",", "err", ":=", "transform", ".", "Bytes", "(", "e", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "s", "\n", "}", "\n", "return", "es", "\n", "}" ]
// Encode to ISO88595.
[ "Encode", "to", "ISO88595", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdutext/iso88595.go#L21-L28
16,846
fiorix/go-smpp
smpp/pdu/pdutext/iso88595.go
Decode
func (s ISO88595) Decode() []byte { e := charmap.ISO8859_5.NewDecoder() es, _, err := transform.Bytes(e, s) if err != nil { return s } return es }
go
func (s ISO88595) Decode() []byte { e := charmap.ISO8859_5.NewDecoder() es, _, err := transform.Bytes(e, s) if err != nil { return s } return es }
[ "func", "(", "s", "ISO88595", ")", "Decode", "(", ")", "[", "]", "byte", "{", "e", ":=", "charmap", ".", "ISO8859_5", ".", "NewDecoder", "(", ")", "\n", "es", ",", "_", ",", "err", ":=", "transform", ".", "Bytes", "(", "e", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "s", "\n", "}", "\n", "return", "es", "\n", "}" ]
// Decode from ISO88595.
[ "Decode", "from", "ISO88595", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdutext/iso88595.go#L31-L38
16,847
fiorix/go-smpp
smpp/pdu/pdutlv/tlv_types.go
Hex
func (t Tag) Hex() string { bin := make([]byte, 2, 2) binary.BigEndian.PutUint16(bin, uint16(t)) return hex.EncodeToString(bin) }
go
func (t Tag) Hex() string { bin := make([]byte, 2, 2) binary.BigEndian.PutUint16(bin, uint16(t)) return hex.EncodeToString(bin) }
[ "func", "(", "t", "Tag", ")", "Hex", "(", ")", "string", "{", "bin", ":=", "make", "(", "[", "]", "byte", ",", "2", ",", "2", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint16", "(", "bin", ",", "uint16", "(", "t", ")", ")", "\n", "return", "hex", ".", "EncodeToString", "(", "bin", ")", "\n", "}" ]
// Hex returns hexadecimal representation of tag
[ "Hex", "returns", "hexadecimal", "representation", "of", "tag" ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdutlv/tlv_types.go#L26-L30
16,848
fiorix/go-smpp
smpp/pdu/pdutext/ucs2.go
Encode
func (s UCS2) Encode() []byte { e := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) es, _, err := transform.Bytes(e.NewEncoder(), s) if err != nil { return s } return es }
go
func (s UCS2) Encode() []byte { e := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) es, _, err := transform.Bytes(e.NewEncoder(), s) if err != nil { return s } return es }
[ "func", "(", "s", "UCS2", ")", "Encode", "(", ")", "[", "]", "byte", "{", "e", ":=", "unicode", ".", "UTF16", "(", "unicode", ".", "BigEndian", ",", "unicode", ".", "IgnoreBOM", ")", "\n", "es", ",", "_", ",", "err", ":=", "transform", ".", "Bytes", "(", "e", ".", "NewEncoder", "(", ")", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "s", "\n", "}", "\n", "return", "es", "\n", "}" ]
// Encode to UCS2.
[ "Encode", "to", "UCS2", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdutext/ucs2.go#L21-L28
16,849
fiorix/go-smpp
smpp/pdu/pdutext/ucs2.go
Decode
func (s UCS2) Decode() []byte { e := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) es, _, err := transform.Bytes(e.NewDecoder(), s) if err != nil { return s } return es }
go
func (s UCS2) Decode() []byte { e := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) es, _, err := transform.Bytes(e.NewDecoder(), s) if err != nil { return s } return es }
[ "func", "(", "s", "UCS2", ")", "Decode", "(", ")", "[", "]", "byte", "{", "e", ":=", "unicode", ".", "UTF16", "(", "unicode", ".", "BigEndian", ",", "unicode", ".", "IgnoreBOM", ")", "\n", "es", ",", "_", ",", "err", ":=", "transform", ".", "Bytes", "(", "e", ".", "NewDecoder", "(", ")", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "s", "\n", "}", "\n", "return", "es", "\n", "}" ]
// Decode from UCS2.
[ "Decode", "from", "UCS2", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/pdu/pdutext/ucs2.go#L31-L38
16,850
fiorix/go-smpp
smpp/encoding/gsm7.go
ValidateGSM7String
func ValidateGSM7String(text string) []rune { invalidChars := make([]rune, 0, 4) for _, r := range text { if _, ok := forwardLookup[r]; !ok { if _, ok := forwardEscape[r]; !ok { invalidChars = append(invalidChars, r) } } } return invalidChars }
go
func ValidateGSM7String(text string) []rune { invalidChars := make([]rune, 0, 4) for _, r := range text { if _, ok := forwardLookup[r]; !ok { if _, ok := forwardEscape[r]; !ok { invalidChars = append(invalidChars, r) } } } return invalidChars }
[ "func", "ValidateGSM7String", "(", "text", "string", ")", "[", "]", "rune", "{", "invalidChars", ":=", "make", "(", "[", "]", "rune", ",", "0", ",", "4", ")", "\n", "for", "_", ",", "r", ":=", "range", "text", "{", "if", "_", ",", "ok", ":=", "forwardLookup", "[", "r", "]", ";", "!", "ok", "{", "if", "_", ",", "ok", ":=", "forwardEscape", "[", "r", "]", ";", "!", "ok", "{", "invalidChars", "=", "append", "(", "invalidChars", ",", "r", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "invalidChars", "\n", "}" ]
// Returns the characters, in the given text, that can not be represented in GSM 7-bit encoding.
[ "Returns", "the", "characters", "in", "the", "given", "text", "that", "can", "not", "be", "represented", "in", "GSM", "7", "-", "bit", "encoding", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/encoding/gsm7.go#L73-L83
16,851
fiorix/go-smpp
smpp/encoding/gsm7.go
ValidateGSM7Buffer
func ValidateGSM7Buffer(buffer []byte) []byte { invalidBytes := make([]byte, 0, 4) count := 0 for count < len(buffer) { b := buffer[count] if b == escapeSequence { count++ if count >= len(buffer) { invalidBytes = append(invalidBytes, b) break } e := buffer[count] if _, ok := reverseEscape[e]; !ok { invalidBytes = append(invalidBytes, b, e) } } else if _, ok := reverseLookup[b]; !ok { invalidBytes = append(invalidBytes, b) } count++ } return invalidBytes }
go
func ValidateGSM7Buffer(buffer []byte) []byte { invalidBytes := make([]byte, 0, 4) count := 0 for count < len(buffer) { b := buffer[count] if b == escapeSequence { count++ if count >= len(buffer) { invalidBytes = append(invalidBytes, b) break } e := buffer[count] if _, ok := reverseEscape[e]; !ok { invalidBytes = append(invalidBytes, b, e) } } else if _, ok := reverseLookup[b]; !ok { invalidBytes = append(invalidBytes, b) } count++ } return invalidBytes }
[ "func", "ValidateGSM7Buffer", "(", "buffer", "[", "]", "byte", ")", "[", "]", "byte", "{", "invalidBytes", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "4", ")", "\n", "count", ":=", "0", "\n", "for", "count", "<", "len", "(", "buffer", ")", "{", "b", ":=", "buffer", "[", "count", "]", "\n", "if", "b", "==", "escapeSequence", "{", "count", "++", "\n", "if", "count", ">=", "len", "(", "buffer", ")", "{", "invalidBytes", "=", "append", "(", "invalidBytes", ",", "b", ")", "\n", "break", "\n", "}", "\n", "e", ":=", "buffer", "[", "count", "]", "\n", "if", "_", ",", "ok", ":=", "reverseEscape", "[", "e", "]", ";", "!", "ok", "{", "invalidBytes", "=", "append", "(", "invalidBytes", ",", "b", ",", "e", ")", "\n", "}", "\n", "}", "else", "if", "_", ",", "ok", ":=", "reverseLookup", "[", "b", "]", ";", "!", "ok", "{", "invalidBytes", "=", "append", "(", "invalidBytes", ",", "b", ")", "\n", "}", "\n", "count", "++", "\n", "}", "\n", "return", "invalidBytes", "\n", "}" ]
// Returns the bytes, in the given buffer, that are outside of the GSM 7-bit encoding range.
[ "Returns", "the", "bytes", "in", "the", "given", "buffer", "that", "are", "outside", "of", "the", "GSM", "7", "-", "bit", "encoding", "range", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/encoding/gsm7.go#L86-L107
16,852
fiorix/go-smpp
smpp/client.go
Bind
func (c *client) Bind() { delay := 1.0 const maxdelay = 120.0 for !c.closed() { eli := make(chan struct{}) c.inbox = make(chan pdu.Body) conn, err := Dial(c.Addr, c.TLS) if err != nil { c.notify(&connStatus{ s: ConnectionFailed, err: err, }) goto retry } c.conn.Set(conn) if err = c.BindFunc(c.conn); err != nil { c.notify(&connStatus{s: BindFailed, err: err}) goto retry } go c.enquireLink(eli) c.notify(&connStatus{s: Connected}) delay = 1 for { p, err := c.conn.Read() if err != nil { c.notify(&connStatus{ s: Disconnected, err: err, }) break } switch p.Header().ID { case pdu.EnquireLinkID: pResp := pdu.NewEnquireLinkRespSeq(p.Header().Seq) err := c.conn.Write(pResp) if err != nil { break } case pdu.EnquireLinkRespID: c.updateEliTime() default: c.inbox <- p } } retry: close(eli) c.conn.Close() close(c.inbox) delayDuration := c.BindInterval if delayDuration == 0 { delay = math.Min(delay*math.E, maxdelay) delayDuration = time.Duration(delay) * time.Second } c.trysleep(delayDuration) } close(c.Status) }
go
func (c *client) Bind() { delay := 1.0 const maxdelay = 120.0 for !c.closed() { eli := make(chan struct{}) c.inbox = make(chan pdu.Body) conn, err := Dial(c.Addr, c.TLS) if err != nil { c.notify(&connStatus{ s: ConnectionFailed, err: err, }) goto retry } c.conn.Set(conn) if err = c.BindFunc(c.conn); err != nil { c.notify(&connStatus{s: BindFailed, err: err}) goto retry } go c.enquireLink(eli) c.notify(&connStatus{s: Connected}) delay = 1 for { p, err := c.conn.Read() if err != nil { c.notify(&connStatus{ s: Disconnected, err: err, }) break } switch p.Header().ID { case pdu.EnquireLinkID: pResp := pdu.NewEnquireLinkRespSeq(p.Header().Seq) err := c.conn.Write(pResp) if err != nil { break } case pdu.EnquireLinkRespID: c.updateEliTime() default: c.inbox <- p } } retry: close(eli) c.conn.Close() close(c.inbox) delayDuration := c.BindInterval if delayDuration == 0 { delay = math.Min(delay*math.E, maxdelay) delayDuration = time.Duration(delay) * time.Second } c.trysleep(delayDuration) } close(c.Status) }
[ "func", "(", "c", "*", "client", ")", "Bind", "(", ")", "{", "delay", ":=", "1.0", "\n", "const", "maxdelay", "=", "120.0", "\n", "for", "!", "c", ".", "closed", "(", ")", "{", "eli", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "c", ".", "inbox", "=", "make", "(", "chan", "pdu", ".", "Body", ")", "\n", "conn", ",", "err", ":=", "Dial", "(", "c", ".", "Addr", ",", "c", ".", "TLS", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "notify", "(", "&", "connStatus", "{", "s", ":", "ConnectionFailed", ",", "err", ":", "err", ",", "}", ")", "\n", "goto", "retry", "\n", "}", "\n", "c", ".", "conn", ".", "Set", "(", "conn", ")", "\n", "if", "err", "=", "c", ".", "BindFunc", "(", "c", ".", "conn", ")", ";", "err", "!=", "nil", "{", "c", ".", "notify", "(", "&", "connStatus", "{", "s", ":", "BindFailed", ",", "err", ":", "err", "}", ")", "\n", "goto", "retry", "\n", "}", "\n", "go", "c", ".", "enquireLink", "(", "eli", ")", "\n", "c", ".", "notify", "(", "&", "connStatus", "{", "s", ":", "Connected", "}", ")", "\n", "delay", "=", "1", "\n", "for", "{", "p", ",", "err", ":=", "c", ".", "conn", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "notify", "(", "&", "connStatus", "{", "s", ":", "Disconnected", ",", "err", ":", "err", ",", "}", ")", "\n", "break", "\n", "}", "\n", "switch", "p", ".", "Header", "(", ")", ".", "ID", "{", "case", "pdu", ".", "EnquireLinkID", ":", "pResp", ":=", "pdu", ".", "NewEnquireLinkRespSeq", "(", "p", ".", "Header", "(", ")", ".", "Seq", ")", "\n", "err", ":=", "c", ".", "conn", ".", "Write", "(", "pResp", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "case", "pdu", ".", "EnquireLinkRespID", ":", "c", ".", "updateEliTime", "(", ")", "\n", "default", ":", "c", ".", "inbox", "<-", "p", "\n", "}", "\n", "}", "\n", "retry", ":", "close", "(", "eli", ")", "\n", "c", ".", "conn", ".", "Close", "(", ")", "\n", "close", "(", "c", ".", "inbox", ")", "\n", "delayDuration", ":=", "c", ".", "BindInterval", "\n", "if", "delayDuration", "==", "0", "{", "delay", "=", "math", ".", "Min", "(", "delay", "*", "math", ".", "E", ",", "maxdelay", ")", "\n", "delayDuration", "=", "time", ".", "Duration", "(", "delay", ")", "*", "time", ".", "Second", "\n", "}", "\n", "c", ".", "trysleep", "(", "delayDuration", ")", "\n", "}", "\n", "close", "(", "c", ".", "Status", ")", "\n", "}" ]
// Bind starts the connection manager and blocks until Close is called. // It must be called in a goroutine.
[ "Bind", "starts", "the", "connection", "manager", "and", "blocks", "until", "Close", "is", "called", ".", "It", "must", "be", "called", "in", "a", "goroutine", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/client.go#L124-L180
16,853
fiorix/go-smpp
smpp/client.go
Read
func (c *client) Read() (pdu.Body, error) { select { case pdu := <-c.inbox: return pdu, nil case <-c.stop: return nil, io.EOF } }
go
func (c *client) Read() (pdu.Body, error) { select { case pdu := <-c.inbox: return pdu, nil case <-c.stop: return nil, io.EOF } }
[ "func", "(", "c", "*", "client", ")", "Read", "(", ")", "(", "pdu", ".", "Body", ",", "error", ")", "{", "select", "{", "case", "pdu", ":=", "<-", "c", ".", "inbox", ":", "return", "pdu", ",", "nil", "\n", "case", "<-", "c", ".", "stop", ":", "return", "nil", ",", "io", ".", "EOF", "\n", "}", "\n", "}" ]
// Read reads PDU binary data off the wire and returns it.
[ "Read", "reads", "PDU", "binary", "data", "off", "the", "wire", "and", "returns", "it", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/client.go#L224-L231
16,854
fiorix/go-smpp
smpp/client.go
Write
func (c *client) Write(w pdu.Body) error { if c.RateLimiter != nil { c.RateLimiter.Wait(c.lmctx) } return c.conn.Write(w) }
go
func (c *client) Write(w pdu.Body) error { if c.RateLimiter != nil { c.RateLimiter.Wait(c.lmctx) } return c.conn.Write(w) }
[ "func", "(", "c", "*", "client", ")", "Write", "(", "w", "pdu", ".", "Body", ")", "error", "{", "if", "c", ".", "RateLimiter", "!=", "nil", "{", "c", ".", "RateLimiter", ".", "Wait", "(", "c", ".", "lmctx", ")", "\n", "}", "\n", "return", "c", ".", "conn", ".", "Write", "(", "w", ")", "\n", "}" ]
// Write serializes the given PDU and writes to the connection.
[ "Write", "serializes", "the", "given", "PDU", "and", "writes", "to", "the", "connection", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/client.go#L234-L239
16,855
fiorix/go-smpp
smpp/client.go
Close
func (c *client) Close() error { c.once.Do(func() { close(c.stop) if err := c.conn.Write(pdu.NewUnbind()); err == nil { select { case <-c.inbox: // TODO: validate UnbindResp case <-time.After(time.Second): } } c.conn.Close() }) return nil }
go
func (c *client) Close() error { c.once.Do(func() { close(c.stop) if err := c.conn.Write(pdu.NewUnbind()); err == nil { select { case <-c.inbox: // TODO: validate UnbindResp case <-time.After(time.Second): } } c.conn.Close() }) return nil }
[ "func", "(", "c", "*", "client", ")", "Close", "(", ")", "error", "{", "c", ".", "once", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "c", ".", "stop", ")", "\n", "if", "err", ":=", "c", ".", "conn", ".", "Write", "(", "pdu", ".", "NewUnbind", "(", ")", ")", ";", "err", "==", "nil", "{", "select", "{", "case", "<-", "c", ".", "inbox", ":", "// TODO: validate UnbindResp", "case", "<-", "time", ".", "After", "(", "time", ".", "Second", ")", ":", "}", "\n", "}", "\n", "c", ".", "conn", ".", "Close", "(", ")", "\n", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Close terminates the current connection and stop any further attempts.
[ "Close", "terminates", "the", "current", "connection", "and", "stop", "any", "further", "attempts", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/client.go#L242-L254
16,856
fiorix/go-smpp
smpp/client.go
trysleep
func (c *client) trysleep(d time.Duration) { select { case <-time.After(d): case <-c.stop: } }
go
func (c *client) trysleep(d time.Duration) { select { case <-time.After(d): case <-c.stop: } }
[ "func", "(", "c", "*", "client", ")", "trysleep", "(", "d", "time", ".", "Duration", ")", "{", "select", "{", "case", "<-", "time", ".", "After", "(", "d", ")", ":", "case", "<-", "c", ".", "stop", ":", "}", "\n", "}" ]
// trysleep for the given duration, or return if Close is called.
[ "trysleep", "for", "the", "given", "duration", "or", "return", "if", "Close", "is", "called", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/client.go#L257-L262
16,857
fiorix/go-smpp
smpp/client.go
respTimeout
func (c *client) respTimeout() <-chan time.Time { if c.RespTimeout == 0 { return time.After(time.Second) } return time.After(c.RespTimeout) }
go
func (c *client) respTimeout() <-chan time.Time { if c.RespTimeout == 0 { return time.After(time.Second) } return time.After(c.RespTimeout) }
[ "func", "(", "c", "*", "client", ")", "respTimeout", "(", ")", "<-", "chan", "time", ".", "Time", "{", "if", "c", ".", "RespTimeout", "==", "0", "{", "return", "time", ".", "After", "(", "time", ".", "Second", ")", "\n", "}", "\n", "return", "time", ".", "After", "(", "c", ".", "RespTimeout", ")", "\n", "}" ]
// respTimeout returns a channel that fires based on the configured // response timeout, or the default 1s.
[ "respTimeout", "returns", "a", "channel", "that", "fires", "based", "on", "the", "configured", "response", "timeout", "or", "the", "default", "1s", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/client.go#L276-L281
16,858
fiorix/go-smpp
smpp/client.go
bind
func bind(c Conn, p pdu.Body) (pdu.Body, error) { f := p.Fields() f.Set(pdufield.InterfaceVersion, 0x34) err := c.Write(p) if err != nil { return nil, err } resp, err := c.Read() if err != nil { return nil, err } h := resp.Header() if h.Status != 0 { return nil, h.Status } return resp, nil }
go
func bind(c Conn, p pdu.Body) (pdu.Body, error) { f := p.Fields() f.Set(pdufield.InterfaceVersion, 0x34) err := c.Write(p) if err != nil { return nil, err } resp, err := c.Read() if err != nil { return nil, err } h := resp.Header() if h.Status != 0 { return nil, h.Status } return resp, nil }
[ "func", "bind", "(", "c", "Conn", ",", "p", "pdu", ".", "Body", ")", "(", "pdu", ".", "Body", ",", "error", ")", "{", "f", ":=", "p", ".", "Fields", "(", ")", "\n", "f", ".", "Set", "(", "pdufield", ".", "InterfaceVersion", ",", "0x34", ")", "\n", "err", ":=", "c", ".", "Write", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "h", ":=", "resp", ".", "Header", "(", ")", "\n", "if", "h", ".", "Status", "!=", "0", "{", "return", "nil", ",", "h", ".", "Status", "\n", "}", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// bind attempts to bind the connection.
[ "bind", "attempts", "to", "bind", "the", "connection", "." ]
6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7
https://github.com/fiorix/go-smpp/blob/6dbf72b9bcea72cea4a035e3a2fc434c4dabaae7/smpp/client.go#L284-L300
16,859
dedis/protobuf
encode.go
Encode
func Encode(structPtr interface{}) (bytes []byte, err error) { defer func() { if e := recover(); e != nil { err = errors.New(e.(string)) bytes = nil } }() if structPtr == nil { return nil, nil } if bu, ok := structPtr.(encoding.BinaryMarshaler); ok { return bu.MarshalBinary() } en := encoder{} val := reflect.ValueOf(structPtr) if val.Kind() != reflect.Ptr { return nil, errors.New("encode takes a pointer to struct") } en.message(val.Elem()) return en.Bytes(), nil }
go
func Encode(structPtr interface{}) (bytes []byte, err error) { defer func() { if e := recover(); e != nil { err = errors.New(e.(string)) bytes = nil } }() if structPtr == nil { return nil, nil } if bu, ok := structPtr.(encoding.BinaryMarshaler); ok { return bu.MarshalBinary() } en := encoder{} val := reflect.ValueOf(structPtr) if val.Kind() != reflect.Ptr { return nil, errors.New("encode takes a pointer to struct") } en.message(val.Elem()) return en.Bytes(), nil }
[ "func", "Encode", "(", "structPtr", "interface", "{", "}", ")", "(", "bytes", "[", "]", "byte", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "e", ":=", "recover", "(", ")", ";", "e", "!=", "nil", "{", "err", "=", "errors", ".", "New", "(", "e", ".", "(", "string", ")", ")", "\n", "bytes", "=", "nil", "\n", "}", "\n", "}", "(", ")", "\n", "if", "structPtr", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "bu", ",", "ok", ":=", "structPtr", ".", "(", "encoding", ".", "BinaryMarshaler", ")", ";", "ok", "{", "return", "bu", ".", "MarshalBinary", "(", ")", "\n", "}", "\n\n", "en", ":=", "encoder", "{", "}", "\n", "val", ":=", "reflect", ".", "ValueOf", "(", "structPtr", ")", "\n", "if", "val", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "en", ".", "message", "(", "val", ".", "Elem", "(", ")", ")", "\n", "return", "en", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// Encode a Go struct into protocol buffer format. // The caller must pass a pointer to the struct to encode.
[ "Encode", "a", "Go", "struct", "into", "protocol", "buffer", "format", ".", "The", "caller", "must", "pass", "a", "pointer", "to", "the", "struct", "to", "encode", "." ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/encode.go#L41-L63
16,860
dedis/protobuf
generate.go
GenerateProtobufDefinition
func GenerateProtobufDefinition(w io.Writer, types []interface{}, enumMap EnumMap, renamer GeneratorNamer) (err error) { defer func() { if e := recover(); e != nil { err = errors.New(e.(string)) } }() enums := enumTypeMap{} for name, value := range enumMap { v := reflect.ValueOf(value) t := v.Type() if t.Kind() != reflect.Uint32 { return fmt.Errorf("enum type aliases must be uint32") } if t.Name() == "uint32" { return fmt.Errorf("enum value must be a type alias, but got uint32") } enums[t.Name()] = append(enums[t.Name()], enumValue{name, Enum(v.Uint())}) } for _, values := range enums { sort.Sort(values) } rt := reflectedTypes{} for _, t := range types { typ := reflect.Indirect(reflect.ValueOf(t)).Type() if typ.Kind() != reflect.Struct { continue } rt = append(rt, typ) } sort.Sort(rt) if renamer == nil { renamer = &DefaultGeneratorNamer{} } t := template.Must(template.New("protobuf").Funcs(template.FuncMap{ "Fields": ProtoFields, "TypeName": func(f ProtoField) string { return typeName(f, enums, renamer) }, "Options": options, }).Delims("[[", "]]").Parse(protoTemplate)) return t.Execute(w, map[string]interface{}{ "Renamer": renamer, "Enums": enums, "Types": rt, "Ptr": reflect.Ptr, "Slice": reflect.Slice, "Map": reflect.Map, }) }
go
func GenerateProtobufDefinition(w io.Writer, types []interface{}, enumMap EnumMap, renamer GeneratorNamer) (err error) { defer func() { if e := recover(); e != nil { err = errors.New(e.(string)) } }() enums := enumTypeMap{} for name, value := range enumMap { v := reflect.ValueOf(value) t := v.Type() if t.Kind() != reflect.Uint32 { return fmt.Errorf("enum type aliases must be uint32") } if t.Name() == "uint32" { return fmt.Errorf("enum value must be a type alias, but got uint32") } enums[t.Name()] = append(enums[t.Name()], enumValue{name, Enum(v.Uint())}) } for _, values := range enums { sort.Sort(values) } rt := reflectedTypes{} for _, t := range types { typ := reflect.Indirect(reflect.ValueOf(t)).Type() if typ.Kind() != reflect.Struct { continue } rt = append(rt, typ) } sort.Sort(rt) if renamer == nil { renamer = &DefaultGeneratorNamer{} } t := template.Must(template.New("protobuf").Funcs(template.FuncMap{ "Fields": ProtoFields, "TypeName": func(f ProtoField) string { return typeName(f, enums, renamer) }, "Options": options, }).Delims("[[", "]]").Parse(protoTemplate)) return t.Execute(w, map[string]interface{}{ "Renamer": renamer, "Enums": enums, "Types": rt, "Ptr": reflect.Ptr, "Slice": reflect.Slice, "Map": reflect.Map, }) }
[ "func", "GenerateProtobufDefinition", "(", "w", "io", ".", "Writer", ",", "types", "[", "]", "interface", "{", "}", ",", "enumMap", "EnumMap", ",", "renamer", "GeneratorNamer", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "e", ":=", "recover", "(", ")", ";", "e", "!=", "nil", "{", "err", "=", "errors", ".", "New", "(", "e", ".", "(", "string", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "enums", ":=", "enumTypeMap", "{", "}", "\n", "for", "name", ",", "value", ":=", "range", "enumMap", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "value", ")", "\n", "t", ":=", "v", ".", "Type", "(", ")", "\n", "if", "t", ".", "Kind", "(", ")", "!=", "reflect", ".", "Uint32", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "t", ".", "Name", "(", ")", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "enums", "[", "t", ".", "Name", "(", ")", "]", "=", "append", "(", "enums", "[", "t", ".", "Name", "(", ")", "]", ",", "enumValue", "{", "name", ",", "Enum", "(", "v", ".", "Uint", "(", ")", ")", "}", ")", "\n", "}", "\n", "for", "_", ",", "values", ":=", "range", "enums", "{", "sort", ".", "Sort", "(", "values", ")", "\n", "}", "\n", "rt", ":=", "reflectedTypes", "{", "}", "\n", "for", "_", ",", "t", ":=", "range", "types", "{", "typ", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "t", ")", ")", ".", "Type", "(", ")", "\n", "if", "typ", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "continue", "\n", "}", "\n", "rt", "=", "append", "(", "rt", ",", "typ", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "rt", ")", "\n", "if", "renamer", "==", "nil", "{", "renamer", "=", "&", "DefaultGeneratorNamer", "{", "}", "\n", "}", "\n", "t", ":=", "template", ".", "Must", "(", "template", ".", "New", "(", "\"", "\"", ")", ".", "Funcs", "(", "template", ".", "FuncMap", "{", "\"", "\"", ":", "ProtoFields", ",", "\"", "\"", ":", "func", "(", "f", "ProtoField", ")", "string", "{", "return", "typeName", "(", "f", ",", "enums", ",", "renamer", ")", "}", ",", "\"", "\"", ":", "options", ",", "}", ")", ".", "Delims", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Parse", "(", "protoTemplate", ")", ")", "\n", "return", "t", ".", "Execute", "(", "w", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "renamer", ",", "\"", "\"", ":", "enums", ",", "\"", "\"", ":", "rt", ",", "\"", "\"", ":", "reflect", ".", "Ptr", ",", "\"", "\"", ":", "reflect", ".", "Slice", ",", "\"", "\"", ":", "reflect", ".", "Map", ",", "}", ")", "\n", "}" ]
// GenerateProtobufDefinition generates a .proto file from a list of structs via reflection. // fieldNamer is a function that maps ProtoField types to generated protobuf field names.
[ "GenerateProtobufDefinition", "generates", "a", ".", "proto", "file", "from", "a", "list", "of", "structs", "via", "reflection", ".", "fieldNamer", "is", "a", "function", "that", "maps", "ProtoField", "types", "to", "generated", "protobuf", "field", "names", "." ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/generate.go#L214-L260
16,861
dedis/protobuf
decode.go
String
func (c *Constructors) String() string { var s string for k := range *c { s += k.String() + "=>" + "(func() interface {})" + "\t" } return s }
go
func (c *Constructors) String() string { var s string for k := range *c { s += k.String() + "=>" + "(func() interface {})" + "\t" } return s }
[ "func", "(", "c", "*", "Constructors", ")", "String", "(", ")", "string", "{", "var", "s", "string", "\n", "for", "k", ":=", "range", "*", "c", "{", "s", "+=", "k", ".", "String", "(", ")", "+", "\"", "\"", "+", "\"", "\"", "+", "\"", "\\t", "\"", "\n", "}", "\n", "return", "s", "\n", "}" ]
// String returns an easy way to visualize what you have in your constructors.
[ "String", "returns", "an", "easy", "way", "to", "visualize", "what", "you", "have", "in", "your", "constructors", "." ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/decode.go#L24-L30
16,862
dedis/protobuf
decode.go
DecodeWithConstructors
func DecodeWithConstructors(buf []byte, structPtr interface{}, cons Constructors) (err error) { defer func() { if r := recover(); r != nil { switch e := r.(type) { case string: err = errors.New(e) case error: err = e default: err = errors.New("Failed to decode the field") } } }() if structPtr == nil { return nil } if bu, ok := structPtr.(encoding.BinaryUnmarshaler); ok { return bu.UnmarshalBinary(buf) } de := decoder{cons} val := reflect.ValueOf(structPtr) // if its NOT a pointer, it is bad return an error if val.Kind() != reflect.Ptr { return errors.New("Decode has been given a non pointer type") } return de.message(buf, val.Elem()) }
go
func DecodeWithConstructors(buf []byte, structPtr interface{}, cons Constructors) (err error) { defer func() { if r := recover(); r != nil { switch e := r.(type) { case string: err = errors.New(e) case error: err = e default: err = errors.New("Failed to decode the field") } } }() if structPtr == nil { return nil } if bu, ok := structPtr.(encoding.BinaryUnmarshaler); ok { return bu.UnmarshalBinary(buf) } de := decoder{cons} val := reflect.ValueOf(structPtr) // if its NOT a pointer, it is bad return an error if val.Kind() != reflect.Ptr { return errors.New("Decode has been given a non pointer type") } return de.message(buf, val.Elem()) }
[ "func", "DecodeWithConstructors", "(", "buf", "[", "]", "byte", ",", "structPtr", "interface", "{", "}", ",", "cons", "Constructors", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "switch", "e", ":=", "r", ".", "(", "type", ")", "{", "case", "string", ":", "err", "=", "errors", ".", "New", "(", "e", ")", "\n", "case", "error", ":", "err", "=", "e", "\n", "default", ":", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "if", "structPtr", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "bu", ",", "ok", ":=", "structPtr", ".", "(", "encoding", ".", "BinaryUnmarshaler", ")", ";", "ok", "{", "return", "bu", ".", "UnmarshalBinary", "(", "buf", ")", "\n", "}", "\n\n", "de", ":=", "decoder", "{", "cons", "}", "\n", "val", ":=", "reflect", ".", "ValueOf", "(", "structPtr", ")", "\n", "// if its NOT a pointer, it is bad return an error", "if", "val", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "de", ".", "message", "(", "buf", ",", "val", ".", "Elem", "(", ")", ")", "\n", "}" ]
// DecodeWithConstructors is like Decode, but you can pass a map of // constructors with which to instantiate interface types.
[ "DecodeWithConstructors", "is", "like", "Decode", "but", "you", "can", "pass", "a", "map", "of", "constructors", "with", "which", "to", "instantiate", "interface", "types", "." ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/decode.go#L51-L79
16,863
dedis/protobuf
decode.go
message
func (de *decoder) message(buf []byte, sval reflect.Value) error { if sval.Kind() != reflect.Struct { return errors.New("not a struct") } // Decode all the fields fields := ProtoFields(sval.Type()) fieldi := 0 for len(buf) > 0 { // Parse the key key, n := binary.Uvarint(buf) if n <= 0 { return errors.New("bad protobuf field key") } buf = buf[n:] wiretype := int(key & 7) fieldnum := key >> 3 // Lookup the corresponding struct field. // Leave field with a zero Value if fieldnum is out-of-range. // In this case, as well as for blank fields, // value() will just skip over and discard the field content. var field reflect.Value for fieldi < len(fields) && fields[fieldi].ID < int64(fieldnum) { fieldi++ } if fieldi < len(fields) && fields[fieldi].ID == int64(fieldnum) { // For fields within embedded structs, ensure the embedded values aren't nil. index := fields[fieldi].Index path := make([]int, 0, len(index)) for _, id := range index { path = append(path, id) field = sval.FieldByIndex(path) if field.Kind() == reflect.Ptr && field.IsNil() { field.Set(reflect.New(field.Type().Elem())) } } } // For more debugging output, uncomment the following three lines. // if fieldi < len(fields){ // fmt.Printf("Decoding FieldName %+v\n", fields[fieldi].Field) // } // Decode the field's value rem, err := de.value(wiretype, buf, field) if err != nil { if fieldi < len(fields) && fields[fieldi] != nil { return fmt.Errorf("Error while decoding field %+v: %v", fields[fieldi].Field, err) } return err } buf = rem } return nil }
go
func (de *decoder) message(buf []byte, sval reflect.Value) error { if sval.Kind() != reflect.Struct { return errors.New("not a struct") } // Decode all the fields fields := ProtoFields(sval.Type()) fieldi := 0 for len(buf) > 0 { // Parse the key key, n := binary.Uvarint(buf) if n <= 0 { return errors.New("bad protobuf field key") } buf = buf[n:] wiretype := int(key & 7) fieldnum := key >> 3 // Lookup the corresponding struct field. // Leave field with a zero Value if fieldnum is out-of-range. // In this case, as well as for blank fields, // value() will just skip over and discard the field content. var field reflect.Value for fieldi < len(fields) && fields[fieldi].ID < int64(fieldnum) { fieldi++ } if fieldi < len(fields) && fields[fieldi].ID == int64(fieldnum) { // For fields within embedded structs, ensure the embedded values aren't nil. index := fields[fieldi].Index path := make([]int, 0, len(index)) for _, id := range index { path = append(path, id) field = sval.FieldByIndex(path) if field.Kind() == reflect.Ptr && field.IsNil() { field.Set(reflect.New(field.Type().Elem())) } } } // For more debugging output, uncomment the following three lines. // if fieldi < len(fields){ // fmt.Printf("Decoding FieldName %+v\n", fields[fieldi].Field) // } // Decode the field's value rem, err := de.value(wiretype, buf, field) if err != nil { if fieldi < len(fields) && fields[fieldi] != nil { return fmt.Errorf("Error while decoding field %+v: %v", fields[fieldi].Field, err) } return err } buf = rem } return nil }
[ "func", "(", "de", "*", "decoder", ")", "message", "(", "buf", "[", "]", "byte", ",", "sval", "reflect", ".", "Value", ")", "error", "{", "if", "sval", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "// Decode all the fields", "fields", ":=", "ProtoFields", "(", "sval", ".", "Type", "(", ")", ")", "\n", "fieldi", ":=", "0", "\n", "for", "len", "(", "buf", ")", ">", "0", "{", "// Parse the key", "key", ",", "n", ":=", "binary", ".", "Uvarint", "(", "buf", ")", "\n", "if", "n", "<=", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "buf", "=", "buf", "[", "n", ":", "]", "\n", "wiretype", ":=", "int", "(", "key", "&", "7", ")", "\n", "fieldnum", ":=", "key", ">>", "3", "\n\n", "// Lookup the corresponding struct field.", "// Leave field with a zero Value if fieldnum is out-of-range.", "// In this case, as well as for blank fields,", "// value() will just skip over and discard the field content.", "var", "field", "reflect", ".", "Value", "\n", "for", "fieldi", "<", "len", "(", "fields", ")", "&&", "fields", "[", "fieldi", "]", ".", "ID", "<", "int64", "(", "fieldnum", ")", "{", "fieldi", "++", "\n", "}", "\n\n", "if", "fieldi", "<", "len", "(", "fields", ")", "&&", "fields", "[", "fieldi", "]", ".", "ID", "==", "int64", "(", "fieldnum", ")", "{", "// For fields within embedded structs, ensure the embedded values aren't nil.", "index", ":=", "fields", "[", "fieldi", "]", ".", "Index", "\n", "path", ":=", "make", "(", "[", "]", "int", ",", "0", ",", "len", "(", "index", ")", ")", "\n", "for", "_", ",", "id", ":=", "range", "index", "{", "path", "=", "append", "(", "path", ",", "id", ")", "\n", "field", "=", "sval", ".", "FieldByIndex", "(", "path", ")", "\n", "if", "field", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "&&", "field", ".", "IsNil", "(", ")", "{", "field", ".", "Set", "(", "reflect", ".", "New", "(", "field", ".", "Type", "(", ")", ".", "Elem", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// For more debugging output, uncomment the following three lines.", "// if fieldi < len(fields){", "// fmt.Printf(\"Decoding FieldName %+v\\n\", fields[fieldi].Field)", "// }", "// Decode the field's value", "rem", ",", "err", ":=", "de", ".", "value", "(", "wiretype", ",", "buf", ",", "field", ")", "\n", "if", "err", "!=", "nil", "{", "if", "fieldi", "<", "len", "(", "fields", ")", "&&", "fields", "[", "fieldi", "]", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fields", "[", "fieldi", "]", ".", "Field", ",", "err", ")", "\n", "}", "\n\n", "return", "err", "\n", "}", "\n", "buf", "=", "rem", "\n\n", "}", "\n", "return", "nil", "\n", "}" ]
// Decode a Protocol Buffers message into a Go struct. // The Kind of the passed value v must be Struct.
[ "Decode", "a", "Protocol", "Buffers", "message", "into", "a", "Go", "struct", ".", "The", "Kind", "of", "the", "passed", "value", "v", "must", "be", "Struct", "." ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/decode.go#L83-L139
16,864
dedis/protobuf
decode.go
value
func (de *decoder) value(wiretype int, buf []byte, val reflect.Value) ([]byte, error) { // Break out the value from the buffer based on the wire type var v uint64 var n int var vb []byte switch wiretype { case 0: // varint v, n = binary.Uvarint(buf) if n <= 0 { return nil, errors.New("bad protobuf varint value") } buf = buf[n:] case 5: // 32-bit if len(buf) < 4 { return nil, errors.New("bad protobuf 32-bit value") } v = uint64(buf[0]) | uint64(buf[1])<<8 | uint64(buf[2])<<16 | uint64(buf[3])<<24 buf = buf[4:] case 1: // 64-bit if len(buf) < 8 { return nil, errors.New("bad protobuf 64-bit value") } v = uint64(buf[0]) | uint64(buf[1])<<8 | uint64(buf[2])<<16 | uint64(buf[3])<<24 | uint64(buf[4])<<32 | uint64(buf[5])<<40 | uint64(buf[6])<<48 | uint64(buf[7])<<56 buf = buf[8:] case 2: // length-delimited v, n = binary.Uvarint(buf) if n <= 0 || v > uint64(len(buf)-n) { return nil, errors.New( "bad protobuf length-delimited value") } vb = buf[n : n+int(v) : n+int(v)] buf = buf[n+int(v):] default: return nil, errors.New("unknown protobuf wire-type") } // We've gotten the value out of the buffer, // now put it into the appropriate reflective Value. if err := de.putvalue(wiretype, val, v, vb); err != nil { return nil, err } return buf, nil }
go
func (de *decoder) value(wiretype int, buf []byte, val reflect.Value) ([]byte, error) { // Break out the value from the buffer based on the wire type var v uint64 var n int var vb []byte switch wiretype { case 0: // varint v, n = binary.Uvarint(buf) if n <= 0 { return nil, errors.New("bad protobuf varint value") } buf = buf[n:] case 5: // 32-bit if len(buf) < 4 { return nil, errors.New("bad protobuf 32-bit value") } v = uint64(buf[0]) | uint64(buf[1])<<8 | uint64(buf[2])<<16 | uint64(buf[3])<<24 buf = buf[4:] case 1: // 64-bit if len(buf) < 8 { return nil, errors.New("bad protobuf 64-bit value") } v = uint64(buf[0]) | uint64(buf[1])<<8 | uint64(buf[2])<<16 | uint64(buf[3])<<24 | uint64(buf[4])<<32 | uint64(buf[5])<<40 | uint64(buf[6])<<48 | uint64(buf[7])<<56 buf = buf[8:] case 2: // length-delimited v, n = binary.Uvarint(buf) if n <= 0 || v > uint64(len(buf)-n) { return nil, errors.New( "bad protobuf length-delimited value") } vb = buf[n : n+int(v) : n+int(v)] buf = buf[n+int(v):] default: return nil, errors.New("unknown protobuf wire-type") } // We've gotten the value out of the buffer, // now put it into the appropriate reflective Value. if err := de.putvalue(wiretype, val, v, vb); err != nil { return nil, err } return buf, nil }
[ "func", "(", "de", "*", "decoder", ")", "value", "(", "wiretype", "int", ",", "buf", "[", "]", "byte", ",", "val", "reflect", ".", "Value", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Break out the value from the buffer based on the wire type", "var", "v", "uint64", "\n", "var", "n", "int", "\n", "var", "vb", "[", "]", "byte", "\n", "switch", "wiretype", "{", "case", "0", ":", "// varint", "v", ",", "n", "=", "binary", ".", "Uvarint", "(", "buf", ")", "\n", "if", "n", "<=", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "buf", "=", "buf", "[", "n", ":", "]", "\n\n", "case", "5", ":", "// 32-bit", "if", "len", "(", "buf", ")", "<", "4", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "v", "=", "uint64", "(", "buf", "[", "0", "]", ")", "|", "uint64", "(", "buf", "[", "1", "]", ")", "<<", "8", "|", "uint64", "(", "buf", "[", "2", "]", ")", "<<", "16", "|", "uint64", "(", "buf", "[", "3", "]", ")", "<<", "24", "\n", "buf", "=", "buf", "[", "4", ":", "]", "\n\n", "case", "1", ":", "// 64-bit", "if", "len", "(", "buf", ")", "<", "8", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "v", "=", "uint64", "(", "buf", "[", "0", "]", ")", "|", "uint64", "(", "buf", "[", "1", "]", ")", "<<", "8", "|", "uint64", "(", "buf", "[", "2", "]", ")", "<<", "16", "|", "uint64", "(", "buf", "[", "3", "]", ")", "<<", "24", "|", "uint64", "(", "buf", "[", "4", "]", ")", "<<", "32", "|", "uint64", "(", "buf", "[", "5", "]", ")", "<<", "40", "|", "uint64", "(", "buf", "[", "6", "]", ")", "<<", "48", "|", "uint64", "(", "buf", "[", "7", "]", ")", "<<", "56", "\n", "buf", "=", "buf", "[", "8", ":", "]", "\n\n", "case", "2", ":", "// length-delimited", "v", ",", "n", "=", "binary", ".", "Uvarint", "(", "buf", ")", "\n", "if", "n", "<=", "0", "||", "v", ">", "uint64", "(", "len", "(", "buf", ")", "-", "n", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "vb", "=", "buf", "[", "n", ":", "n", "+", "int", "(", "v", ")", ":", "n", "+", "int", "(", "v", ")", "]", "\n", "buf", "=", "buf", "[", "n", "+", "int", "(", "v", ")", ":", "]", "\n\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// We've gotten the value out of the buffer,", "// now put it into the appropriate reflective Value.", "if", "err", ":=", "de", ".", "putvalue", "(", "wiretype", ",", "val", ",", "v", ",", "vb", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ",", "nil", "\n", "}" ]
// Pull a value from the buffer and put it into a reflective Value.
[ "Pull", "a", "value", "from", "the", "buffer", "and", "put", "it", "into", "a", "reflective", "Value", "." ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/decode.go#L142-L200
16,865
dedis/protobuf
decode.go
instantiate
func (de *decoder) instantiate(t reflect.Type) reflect.Value { // If it's an interface type, lookup a dynamic constructor for it. if t.Kind() == reflect.Interface { newfunc, ok := de.nm[t] if !ok { panic("no constructor for interface " + t.String()) } return reflect.ValueOf(newfunc()) } // Otherwise, for all concrete types, just instantiate directly. return reflect.New(t) }
go
func (de *decoder) instantiate(t reflect.Type) reflect.Value { // If it's an interface type, lookup a dynamic constructor for it. if t.Kind() == reflect.Interface { newfunc, ok := de.nm[t] if !ok { panic("no constructor for interface " + t.String()) } return reflect.ValueOf(newfunc()) } // Otherwise, for all concrete types, just instantiate directly. return reflect.New(t) }
[ "func", "(", "de", "*", "decoder", ")", "instantiate", "(", "t", "reflect", ".", "Type", ")", "reflect", ".", "Value", "{", "// If it's an interface type, lookup a dynamic constructor for it.", "if", "t", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "{", "newfunc", ",", "ok", ":=", "de", ".", "nm", "[", "t", "]", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", "+", "t", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "reflect", ".", "ValueOf", "(", "newfunc", "(", ")", ")", "\n", "}", "\n\n", "// Otherwise, for all concrete types, just instantiate directly.", "return", "reflect", ".", "New", "(", "t", ")", "\n", "}" ]
// Instantiate an arbitrary type, handling dynamic interface types. // Returns a Ptr value.
[ "Instantiate", "an", "arbitrary", "type", "handling", "dynamic", "interface", "types", ".", "Returns", "a", "Ptr", "value", "." ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/decode.go#L369-L382
16,866
dedis/protobuf
decode.go
slice
func (de *decoder) slice(slval reflect.Value, vb []byte) error { // Find the element type, and create a temporary instance of it. eltype := slval.Type().Elem() val := reflect.New(eltype).Elem() // Decide on the wiretype to use for decoding. var wiretype int switch eltype.Kind() { case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Int, reflect.Uint32, reflect.Uint64, reflect.Uint: if (eltype.Kind() == reflect.Int || eltype.Kind() == reflect.Uint) && eltype.Size() < 8 { return errors.New("detected a 32bit machine, please either use (u)int64 or (u)int32") } switch eltype { case sfixed32type: wiretype = 5 // Packed 32-bit representation case sfixed64type: wiretype = 1 // Packed 64-bit representation case ufixed32type: wiretype = 5 // Packed 32-bit representation case ufixed64type: wiretype = 1 // Packed 64-bit representation default: wiretype = 0 // Packed varint representation } case reflect.Float32: wiretype = 5 // Packed 32-bit representation case reflect.Float64: wiretype = 1 // Packed 64-bit representation case reflect.Uint8: // Unpacked byte-slice if slval.Kind() == reflect.Array { if slval.Len() != len(vb) { return errors.New("array length and buffer length differ") } for i := 0; i < slval.Len(); i++ { // no SetByte method in reflect so has to pass down by uint64 slval.Index(i).SetUint(uint64(vb[i])) } } else { slval.SetBytes(vb) } return nil default: // Other unpacked repeated types // Just unpack and append one value from vb. if err := de.putvalue(2, val, 0, vb); err != nil { return err } if slval.Kind() != reflect.Slice { return errors.New("append to non-slice") } slval.Set(reflect.Append(slval, val)) return nil } // Decode packed values from the buffer and append them to the slice. for len(vb) > 0 { rem, err := de.value(wiretype, vb, val) if err != nil { return err } slval.Set(reflect.Append(slval, val)) vb = rem } return nil }
go
func (de *decoder) slice(slval reflect.Value, vb []byte) error { // Find the element type, and create a temporary instance of it. eltype := slval.Type().Elem() val := reflect.New(eltype).Elem() // Decide on the wiretype to use for decoding. var wiretype int switch eltype.Kind() { case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Int, reflect.Uint32, reflect.Uint64, reflect.Uint: if (eltype.Kind() == reflect.Int || eltype.Kind() == reflect.Uint) && eltype.Size() < 8 { return errors.New("detected a 32bit machine, please either use (u)int64 or (u)int32") } switch eltype { case sfixed32type: wiretype = 5 // Packed 32-bit representation case sfixed64type: wiretype = 1 // Packed 64-bit representation case ufixed32type: wiretype = 5 // Packed 32-bit representation case ufixed64type: wiretype = 1 // Packed 64-bit representation default: wiretype = 0 // Packed varint representation } case reflect.Float32: wiretype = 5 // Packed 32-bit representation case reflect.Float64: wiretype = 1 // Packed 64-bit representation case reflect.Uint8: // Unpacked byte-slice if slval.Kind() == reflect.Array { if slval.Len() != len(vb) { return errors.New("array length and buffer length differ") } for i := 0; i < slval.Len(); i++ { // no SetByte method in reflect so has to pass down by uint64 slval.Index(i).SetUint(uint64(vb[i])) } } else { slval.SetBytes(vb) } return nil default: // Other unpacked repeated types // Just unpack and append one value from vb. if err := de.putvalue(2, val, 0, vb); err != nil { return err } if slval.Kind() != reflect.Slice { return errors.New("append to non-slice") } slval.Set(reflect.Append(slval, val)) return nil } // Decode packed values from the buffer and append them to the slice. for len(vb) > 0 { rem, err := de.value(wiretype, vb, val) if err != nil { return err } slval.Set(reflect.Append(slval, val)) vb = rem } return nil }
[ "func", "(", "de", "*", "decoder", ")", "slice", "(", "slval", "reflect", ".", "Value", ",", "vb", "[", "]", "byte", ")", "error", "{", "// Find the element type, and create a temporary instance of it.", "eltype", ":=", "slval", ".", "Type", "(", ")", ".", "Elem", "(", ")", "\n", "val", ":=", "reflect", ".", "New", "(", "eltype", ")", ".", "Elem", "(", ")", "\n\n", "// Decide on the wiretype to use for decoding.", "var", "wiretype", "int", "\n", "switch", "eltype", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Bool", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", ",", "reflect", ".", "Int", ",", "reflect", ".", "Uint32", ",", "reflect", ".", "Uint64", ",", "reflect", ".", "Uint", ":", "if", "(", "eltype", ".", "Kind", "(", ")", "==", "reflect", ".", "Int", "||", "eltype", ".", "Kind", "(", ")", "==", "reflect", ".", "Uint", ")", "&&", "eltype", ".", "Size", "(", ")", "<", "8", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "switch", "eltype", "{", "case", "sfixed32type", ":", "wiretype", "=", "5", "// Packed 32-bit representation", "\n", "case", "sfixed64type", ":", "wiretype", "=", "1", "// Packed 64-bit representation", "\n", "case", "ufixed32type", ":", "wiretype", "=", "5", "// Packed 32-bit representation", "\n", "case", "ufixed64type", ":", "wiretype", "=", "1", "// Packed 64-bit representation", "\n", "default", ":", "wiretype", "=", "0", "// Packed varint representation", "\n", "}", "\n\n", "case", "reflect", ".", "Float32", ":", "wiretype", "=", "5", "// Packed 32-bit representation", "\n\n", "case", "reflect", ".", "Float64", ":", "wiretype", "=", "1", "// Packed 64-bit representation", "\n\n", "case", "reflect", ".", "Uint8", ":", "// Unpacked byte-slice", "if", "slval", ".", "Kind", "(", ")", "==", "reflect", ".", "Array", "{", "if", "slval", ".", "Len", "(", ")", "!=", "len", "(", "vb", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "slval", ".", "Len", "(", ")", ";", "i", "++", "{", "// no SetByte method in reflect so has to pass down by uint64", "slval", ".", "Index", "(", "i", ")", ".", "SetUint", "(", "uint64", "(", "vb", "[", "i", "]", ")", ")", "\n", "}", "\n", "}", "else", "{", "slval", ".", "SetBytes", "(", "vb", ")", "\n", "}", "\n", "return", "nil", "\n\n", "default", ":", "// Other unpacked repeated types", "// Just unpack and append one value from vb.", "if", "err", ":=", "de", ".", "putvalue", "(", "2", ",", "val", ",", "0", ",", "vb", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "slval", ".", "Kind", "(", ")", "!=", "reflect", ".", "Slice", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "slval", ".", "Set", "(", "reflect", ".", "Append", "(", "slval", ",", "val", ")", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Decode packed values from the buffer and append them to the slice.", "for", "len", "(", "vb", ")", ">", "0", "{", "rem", ",", "err", ":=", "de", ".", "value", "(", "wiretype", ",", "vb", ",", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "slval", ".", "Set", "(", "reflect", ".", "Append", "(", "slval", ",", "val", ")", ")", "\n", "vb", "=", "rem", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Handle decoding of slices
[ "Handle", "decoding", "of", "slices" ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/decode.go#L390-L459
16,867
dedis/protobuf
interface.go
register
func (ir *generatorRegistry) register(g InterfaceGeneratorFunc) { val, ok := g().(InterfaceMarshaler) if !ok { panic("Implementation of the interface must fulfilled InterfaceMarshaler") } key := val.MarshalID() ir.generators[key] = g }
go
func (ir *generatorRegistry) register(g InterfaceGeneratorFunc) { val, ok := g().(InterfaceMarshaler) if !ok { panic("Implementation of the interface must fulfilled InterfaceMarshaler") } key := val.MarshalID() ir.generators[key] = g }
[ "func", "(", "ir", "*", "generatorRegistry", ")", "register", "(", "g", "InterfaceGeneratorFunc", ")", "{", "val", ",", "ok", ":=", "g", "(", ")", ".", "(", "InterfaceMarshaler", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "key", ":=", "val", ".", "MarshalID", "(", ")", "\n\n", "ir", ".", "generators", "[", "key", "]", "=", "g", "\n", "}" ]
// register gets the type tag and map it to the generator function
[ "register", "gets", "the", "type", "tag", "and", "map", "it", "to", "the", "generator", "function" ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/interface.go#L34-L42
16,868
dedis/protobuf
interface.go
get
func (ir *generatorRegistry) get(key GeneratorID) InterfaceGeneratorFunc { g, _ := ir.generators[key] return g }
go
func (ir *generatorRegistry) get(key GeneratorID) InterfaceGeneratorFunc { g, _ := ir.generators[key] return g }
[ "func", "(", "ir", "*", "generatorRegistry", ")", "get", "(", "key", "GeneratorID", ")", "InterfaceGeneratorFunc", "{", "g", ",", "_", ":=", "ir", ".", "generators", "[", "key", "]", "\n", "return", "g", "\n", "}" ]
// get returns the generator associated with the tag
[ "get", "returns", "the", "generator", "associated", "with", "the", "tag" ]
aaafc048527b821ddbe59e5a81fe5c05a61166b4
https://github.com/dedis/protobuf/blob/aaafc048527b821ddbe59e5a81fe5c05a61166b4/interface.go#L45-L48
16,869
coreos/coreos-cloudinit
system/file.go
WriteFile
func WriteFile(f *File, root string) (string, error) { if f.Encoding != "" { return "", fmt.Errorf("Unable to write file with encoding %s", f.Encoding) } fullpath := path.Join(root, f.Path) dir := path.Dir(fullpath) log.Printf("Writing file to %q", fullpath) if err := EnsureDirectoryExists(dir); err != nil { return "", err } perm, err := f.Permissions() if err != nil { return "", err } var tmp *os.File // Create a temporary file in the same directory to ensure it's on the same filesystem if tmp, err = ioutil.TempFile(dir, "cloudinit-temp"); err != nil { return "", err } if err := ioutil.WriteFile(tmp.Name(), []byte(f.Content), perm); err != nil { return "", err } if err := tmp.Close(); err != nil { return "", err } // Ensure the permissions are as requested (since WriteFile can be affected by sticky bit) if err := os.Chmod(tmp.Name(), perm); err != nil { return "", err } if f.Owner != "" { // We shell out since we don't have a way to look up unix groups natively cmd := exec.Command("chown", f.Owner, tmp.Name()) if err := cmd.Run(); err != nil { return "", err } } if err := os.Rename(tmp.Name(), fullpath); err != nil { return "", err } log.Printf("Wrote file to %q", fullpath) return fullpath, nil }
go
func WriteFile(f *File, root string) (string, error) { if f.Encoding != "" { return "", fmt.Errorf("Unable to write file with encoding %s", f.Encoding) } fullpath := path.Join(root, f.Path) dir := path.Dir(fullpath) log.Printf("Writing file to %q", fullpath) if err := EnsureDirectoryExists(dir); err != nil { return "", err } perm, err := f.Permissions() if err != nil { return "", err } var tmp *os.File // Create a temporary file in the same directory to ensure it's on the same filesystem if tmp, err = ioutil.TempFile(dir, "cloudinit-temp"); err != nil { return "", err } if err := ioutil.WriteFile(tmp.Name(), []byte(f.Content), perm); err != nil { return "", err } if err := tmp.Close(); err != nil { return "", err } // Ensure the permissions are as requested (since WriteFile can be affected by sticky bit) if err := os.Chmod(tmp.Name(), perm); err != nil { return "", err } if f.Owner != "" { // We shell out since we don't have a way to look up unix groups natively cmd := exec.Command("chown", f.Owner, tmp.Name()) if err := cmd.Run(); err != nil { return "", err } } if err := os.Rename(tmp.Name(), fullpath); err != nil { return "", err } log.Printf("Wrote file to %q", fullpath) return fullpath, nil }
[ "func", "WriteFile", "(", "f", "*", "File", ",", "root", "string", ")", "(", "string", ",", "error", ")", "{", "if", "f", ".", "Encoding", "!=", "\"", "\"", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Encoding", ")", "\n", "}", "\n\n", "fullpath", ":=", "path", ".", "Join", "(", "root", ",", "f", ".", "Path", ")", "\n", "dir", ":=", "path", ".", "Dir", "(", "fullpath", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "fullpath", ")", "\n\n", "if", "err", ":=", "EnsureDirectoryExists", "(", "dir", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "perm", ",", "err", ":=", "f", ".", "Permissions", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "var", "tmp", "*", "os", ".", "File", "\n", "// Create a temporary file in the same directory to ensure it's on the same filesystem", "if", "tmp", ",", "err", "=", "ioutil", ".", "TempFile", "(", "dir", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "tmp", ".", "Name", "(", ")", ",", "[", "]", "byte", "(", "f", ".", "Content", ")", ",", "perm", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "tmp", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Ensure the permissions are as requested (since WriteFile can be affected by sticky bit)", "if", "err", ":=", "os", ".", "Chmod", "(", "tmp", ".", "Name", "(", ")", ",", "perm", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "f", ".", "Owner", "!=", "\"", "\"", "{", "// We shell out since we don't have a way to look up unix groups natively", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "f", ".", "Owner", ",", "tmp", ".", "Name", "(", ")", ")", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "os", ".", "Rename", "(", "tmp", ".", "Name", "(", ")", ",", "fullpath", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ",", "fullpath", ")", "\n", "return", "fullpath", ",", "nil", "\n", "}" ]
// WriteFile writes given endecoded file to the filesystem
[ "WriteFile", "writes", "given", "endecoded", "file", "to", "the", "filesystem" ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/system/file.go#L49-L100
16,870
coreos/coreos-cloudinit
system/ssh_key.go
AuthorizeSSHKeys
func AuthorizeSSHKeys(user string, keysName string, keys []string) error { for i, key := range keys { keys[i] = strings.TrimSpace(key) } // join all keys with newlines, ensuring the resulting string // also ends with a newline joined := fmt.Sprintf("%s\n", strings.Join(keys, "\n")) cmd := exec.Command("update-ssh-keys", "-u", user, "-a", keysName) stdin, err := cmd.StdinPipe() if err != nil { return err } stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } err = cmd.Start() if err != nil { stdin.Close() return err } _, err = io.WriteString(stdin, joined) if err != nil { return err } stdin.Close() stdoutBytes, _ := ioutil.ReadAll(stdout) stderrBytes, _ := ioutil.ReadAll(stderr) err = cmd.Wait() if err != nil { return fmt.Errorf("Call to update-ssh-keys failed with %v: %s %s", err, string(stdoutBytes), string(stderrBytes)) } return nil }
go
func AuthorizeSSHKeys(user string, keysName string, keys []string) error { for i, key := range keys { keys[i] = strings.TrimSpace(key) } // join all keys with newlines, ensuring the resulting string // also ends with a newline joined := fmt.Sprintf("%s\n", strings.Join(keys, "\n")) cmd := exec.Command("update-ssh-keys", "-u", user, "-a", keysName) stdin, err := cmd.StdinPipe() if err != nil { return err } stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } err = cmd.Start() if err != nil { stdin.Close() return err } _, err = io.WriteString(stdin, joined) if err != nil { return err } stdin.Close() stdoutBytes, _ := ioutil.ReadAll(stdout) stderrBytes, _ := ioutil.ReadAll(stderr) err = cmd.Wait() if err != nil { return fmt.Errorf("Call to update-ssh-keys failed with %v: %s %s", err, string(stdoutBytes), string(stderrBytes)) } return nil }
[ "func", "AuthorizeSSHKeys", "(", "user", "string", ",", "keysName", "string", ",", "keys", "[", "]", "string", ")", "error", "{", "for", "i", ",", "key", ":=", "range", "keys", "{", "keys", "[", "i", "]", "=", "strings", ".", "TrimSpace", "(", "key", ")", "\n", "}", "\n\n", "// join all keys with newlines, ensuring the resulting string", "// also ends with a newline", "joined", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "strings", ".", "Join", "(", "keys", ",", "\"", "\\n", "\"", ")", ")", "\n\n", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "user", ",", "\"", "\"", ",", "keysName", ")", "\n", "stdin", ",", "err", ":=", "cmd", ".", "StdinPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "stdout", ",", "err", ":=", "cmd", ".", "StdoutPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "stderr", ",", "err", ":=", "cmd", ".", "StderrPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "cmd", ".", "Start", "(", ")", "\n", "if", "err", "!=", "nil", "{", "stdin", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "io", ".", "WriteString", "(", "stdin", ",", "joined", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "stdin", ".", "Close", "(", ")", "\n", "stdoutBytes", ",", "_", ":=", "ioutil", ".", "ReadAll", "(", "stdout", ")", "\n", "stderrBytes", ",", "_", ":=", "ioutil", ".", "ReadAll", "(", "stderr", ")", "\n\n", "err", "=", "cmd", ".", "Wait", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "string", "(", "stdoutBytes", ")", ",", "string", "(", "stderrBytes", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Add the provide SSH public key to the core user's list of // authorized keys
[ "Add", "the", "provide", "SSH", "public", "key", "to", "the", "core", "user", "s", "list", "of", "authorized", "keys" ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/system/ssh_key.go#L27-L73
16,871
coreos/coreos-cloudinit
config/validate/report.go
Error
func (r *Report) Error(line int, message string) { r.entries = append(r.entries, Entry{entryError, message, line}) }
go
func (r *Report) Error(line int, message string) { r.entries = append(r.entries, Entry{entryError, message, line}) }
[ "func", "(", "r", "*", "Report", ")", "Error", "(", "line", "int", ",", "message", "string", ")", "{", "r", ".", "entries", "=", "append", "(", "r", ".", "entries", ",", "Entry", "{", "entryError", ",", "message", ",", "line", "}", ")", "\n", "}" ]
// Error adds an error entry to the report.
[ "Error", "adds", "an", "error", "entry", "to", "the", "report", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/report.go#L28-L30
16,872
coreos/coreos-cloudinit
config/validate/report.go
Warning
func (r *Report) Warning(line int, message string) { r.entries = append(r.entries, Entry{entryWarning, message, line}) }
go
func (r *Report) Warning(line int, message string) { r.entries = append(r.entries, Entry{entryWarning, message, line}) }
[ "func", "(", "r", "*", "Report", ")", "Warning", "(", "line", "int", ",", "message", "string", ")", "{", "r", ".", "entries", "=", "append", "(", "r", ".", "entries", ",", "Entry", "{", "entryWarning", ",", "message", ",", "line", "}", ")", "\n", "}" ]
// Warning adds a warning entry to the report.
[ "Warning", "adds", "a", "warning", "entry", "to", "the", "report", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/report.go#L33-L35
16,873
coreos/coreos-cloudinit
config/validate/report.go
Info
func (r *Report) Info(line int, message string) { r.entries = append(r.entries, Entry{entryInfo, message, line}) }
go
func (r *Report) Info(line int, message string) { r.entries = append(r.entries, Entry{entryInfo, message, line}) }
[ "func", "(", "r", "*", "Report", ")", "Info", "(", "line", "int", ",", "message", "string", ")", "{", "r", ".", "entries", "=", "append", "(", "r", ".", "entries", ",", "Entry", "{", "entryInfo", ",", "message", ",", "line", "}", ")", "\n", "}" ]
// Info adds an info entry to the report.
[ "Info", "adds", "an", "info", "entry", "to", "the", "report", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/report.go#L38-L40
16,874
coreos/coreos-cloudinit
config/validate/report.go
String
func (e Entry) String() string { return fmt.Sprintf("line %d: %s: %s", e.line, e.kind, e.message) }
go
func (e Entry) String() string { return fmt.Sprintf("line %d: %s: %s", e.line, e.kind, e.message) }
[ "func", "(", "e", "Entry", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "line", ",", "e", ".", "kind", ",", "e", ".", "message", ")", "\n", "}" ]
// String returns a human-readable representation of the entry.
[ "String", "returns", "a", "human", "-", "readable", "representation", "of", "the", "entry", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/report.go#L55-L57
16,875
coreos/coreos-cloudinit
config/validate/report.go
MarshalJSON
func (e Entry) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ "kind": e.kind.String(), "message": e.message, "line": e.line, }) }
go
func (e Entry) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ "kind": e.kind.String(), "message": e.message, "line": e.line, }) }
[ "func", "(", "e", "Entry", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "e", ".", "kind", ".", "String", "(", ")", ",", "\"", "\"", ":", "e", ".", "message", ",", "\"", "\"", ":", "e", ".", "line", ",", "}", ")", "\n", "}" ]
// MarshalJSON satisfies the json.Marshaler interface, returning the entry // encoded as a JSON object.
[ "MarshalJSON", "satisfies", "the", "json", ".", "Marshaler", "interface", "returning", "the", "entry", "encoded", "as", "a", "JSON", "object", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/report.go#L61-L67
16,876
coreos/coreos-cloudinit
system/systemd.go
PlaceUnit
func (s *systemd) PlaceUnit(u Unit) error { file := File{config.File{ Path: u.Destination(s.root), Content: u.Content, RawFilePermissions: "0644", }} _, err := WriteFile(&file, "/") return err }
go
func (s *systemd) PlaceUnit(u Unit) error { file := File{config.File{ Path: u.Destination(s.root), Content: u.Content, RawFilePermissions: "0644", }} _, err := WriteFile(&file, "/") return err }
[ "func", "(", "s", "*", "systemd", ")", "PlaceUnit", "(", "u", "Unit", ")", "error", "{", "file", ":=", "File", "{", "config", ".", "File", "{", "Path", ":", "u", ".", "Destination", "(", "s", ".", "root", ")", ",", "Content", ":", "u", ".", "Content", ",", "RawFilePermissions", ":", "\"", "\"", ",", "}", "}", "\n\n", "_", ",", "err", ":=", "WriteFile", "(", "&", "file", ",", "\"", "\"", ")", "\n", "return", "err", "\n", "}" ]
// PlaceUnit writes a unit file at its desired destination, creating parent // directories as necessary.
[ "PlaceUnit", "writes", "a", "unit", "file", "at", "its", "desired", "destination", "creating", "parent", "directories", "as", "necessary", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/system/systemd.go#L44-L53
16,877
coreos/coreos-cloudinit
system/systemd.go
PlaceUnitDropIn
func (s *systemd) PlaceUnitDropIn(u Unit, d config.UnitDropIn) error { file := File{config.File{ Path: u.DropInDestination(s.root, d), Content: d.Content, RawFilePermissions: "0644", }} _, err := WriteFile(&file, "/") return err }
go
func (s *systemd) PlaceUnitDropIn(u Unit, d config.UnitDropIn) error { file := File{config.File{ Path: u.DropInDestination(s.root, d), Content: d.Content, RawFilePermissions: "0644", }} _, err := WriteFile(&file, "/") return err }
[ "func", "(", "s", "*", "systemd", ")", "PlaceUnitDropIn", "(", "u", "Unit", ",", "d", "config", ".", "UnitDropIn", ")", "error", "{", "file", ":=", "File", "{", "config", ".", "File", "{", "Path", ":", "u", ".", "DropInDestination", "(", "s", ".", "root", ",", "d", ")", ",", "Content", ":", "d", ".", "Content", ",", "RawFilePermissions", ":", "\"", "\"", ",", "}", "}", "\n\n", "_", ",", "err", ":=", "WriteFile", "(", "&", "file", ",", "\"", "\"", ")", "\n", "return", "err", "\n", "}" ]
// PlaceUnitDropIn writes a unit drop-in file at its desired destination, // creating parent directories as necessary.
[ "PlaceUnitDropIn", "writes", "a", "unit", "drop", "-", "in", "file", "at", "its", "desired", "destination", "creating", "parent", "directories", "as", "necessary", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/system/systemd.go#L57-L66
16,878
coreos/coreos-cloudinit
config/validate/node.go
Child
func (n node) Child(name string) node { for _, c := range n.children { if c.name == name { return c } } return node{} }
go
func (n node) Child(name string) node { for _, c := range n.children { if c.name == name { return c } } return node{} }
[ "func", "(", "n", "node", ")", "Child", "(", "name", "string", ")", "node", "{", "for", "_", ",", "c", ":=", "range", "n", ".", "children", "{", "if", "c", ".", "name", "==", "name", "{", "return", "c", "\n", "}", "\n", "}", "\n", "return", "node", "{", "}", "\n", "}" ]
// Child attempts to find the child with the given name in the node's list of // children. If no such child is found, an invalid node is returned.
[ "Child", "attempts", "to", "find", "the", "child", "with", "the", "given", "name", "in", "the", "node", "s", "list", "of", "children", ".", "If", "no", "such", "child", "is", "found", "an", "invalid", "node", "is", "returned", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/node.go#L38-L45
16,879
coreos/coreos-cloudinit
config/validate/node.go
HumanType
func (n node) HumanType() string { switch k := n.Kind(); k { case reflect.Slice: c := n.Type().Elem() return "[]" + node{Value: reflect.New(c).Elem()}.HumanType() default: return k.String() } }
go
func (n node) HumanType() string { switch k := n.Kind(); k { case reflect.Slice: c := n.Type().Elem() return "[]" + node{Value: reflect.New(c).Elem()}.HumanType() default: return k.String() } }
[ "func", "(", "n", "node", ")", "HumanType", "(", ")", "string", "{", "switch", "k", ":=", "n", ".", "Kind", "(", ")", ";", "k", "{", "case", "reflect", ".", "Slice", ":", "c", ":=", "n", ".", "Type", "(", ")", ".", "Elem", "(", ")", "\n", "return", "\"", "\"", "+", "node", "{", "Value", ":", "reflect", ".", "New", "(", "c", ")", ".", "Elem", "(", ")", "}", ".", "HumanType", "(", ")", "\n", "default", ":", "return", "k", ".", "String", "(", ")", "\n", "}", "\n", "}" ]
// HumanType returns the human-consumable string representation of the type of // the node.
[ "HumanType", "returns", "the", "human", "-", "consumable", "string", "representation", "of", "the", "type", "of", "the", "node", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/node.go#L49-L57
16,880
coreos/coreos-cloudinit
config/validate/node.go
NewNode
func NewNode(value interface{}, context context) node { var n node toNode(value, context, &n) return n }
go
func NewNode(value interface{}, context context) node { var n node toNode(value, context, &n) return n }
[ "func", "NewNode", "(", "value", "interface", "{", "}", ",", "context", "context", ")", "node", "{", "var", "n", "node", "\n", "toNode", "(", "value", ",", "context", ",", "&", "n", ")", "\n", "return", "n", "\n", "}" ]
// NewNode returns the node representation of the given value. The context // will be used in an attempt to determine line numbers for the given value.
[ "NewNode", "returns", "the", "node", "representation", "of", "the", "given", "value", ".", "The", "context", "will", "be", "used", "in", "an", "attempt", "to", "determine", "line", "numbers", "for", "the", "given", "value", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/node.go#L61-L65
16,881
coreos/coreos-cloudinit
config/validate/node.go
findKey
func findKey(key string, context context) (context, bool) { return find(yamlKey, key, context) }
go
func findKey(key string, context context) (context, bool) { return find(yamlKey, key, context) }
[ "func", "findKey", "(", "key", "string", ",", "context", "context", ")", "(", "context", ",", "bool", ")", "{", "return", "find", "(", "yamlKey", ",", "key", ",", "context", ")", "\n", "}" ]
// findKey attempts to find the requested key within the provided context. // A modified copy of the context is returned with every line up to the key // incremented past. A boolean, true if the key was found, is also returned.
[ "findKey", "attempts", "to", "find", "the", "requested", "key", "within", "the", "provided", "context", ".", "A", "modified", "copy", "of", "the", "context", "is", "returned", "with", "every", "line", "up", "to", "the", "key", "incremented", "past", ".", "A", "boolean", "true", "if", "the", "key", "was", "found", "is", "also", "returned", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/node.go#L135-L137
16,882
coreos/coreos-cloudinit
system/env_file.go
WriteEnvFile
func WriteEnvFile(ef *EnvFile, root string) error { // validate new keys, mergeEnvContents uses pending to track writes pending := make(map[string]string, len(ef.Vars)) for key, value := range ef.Vars { if !validKey.MatchString(key) { return fmt.Errorf("Invalid name %q for %s", key, ef.Path) } pending[key] = value } if len(pending) == 0 { return nil } oldContent, err := ioutil.ReadFile(path.Join(root, ef.Path)) if err != nil { if os.IsNotExist(err) { oldContent = []byte{} } else { return err } } newContent := mergeEnvContents(oldContent, pending) if bytes.Equal(oldContent, newContent) { return nil } ef.File.Content = string(newContent) _, err = WriteFile(ef.File, root) return err }
go
func WriteEnvFile(ef *EnvFile, root string) error { // validate new keys, mergeEnvContents uses pending to track writes pending := make(map[string]string, len(ef.Vars)) for key, value := range ef.Vars { if !validKey.MatchString(key) { return fmt.Errorf("Invalid name %q for %s", key, ef.Path) } pending[key] = value } if len(pending) == 0 { return nil } oldContent, err := ioutil.ReadFile(path.Join(root, ef.Path)) if err != nil { if os.IsNotExist(err) { oldContent = []byte{} } else { return err } } newContent := mergeEnvContents(oldContent, pending) if bytes.Equal(oldContent, newContent) { return nil } ef.File.Content = string(newContent) _, err = WriteFile(ef.File, root) return err }
[ "func", "WriteEnvFile", "(", "ef", "*", "EnvFile", ",", "root", "string", ")", "error", "{", "// validate new keys, mergeEnvContents uses pending to track writes", "pending", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "ef", ".", "Vars", ")", ")", "\n", "for", "key", ",", "value", ":=", "range", "ef", ".", "Vars", "{", "if", "!", "validKey", ".", "MatchString", "(", "key", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ",", "ef", ".", "Path", ")", "\n", "}", "\n", "pending", "[", "key", "]", "=", "value", "\n", "}", "\n\n", "if", "len", "(", "pending", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "oldContent", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ".", "Join", "(", "root", ",", "ef", ".", "Path", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "oldContent", "=", "[", "]", "byte", "{", "}", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "newContent", ":=", "mergeEnvContents", "(", "oldContent", ",", "pending", ")", "\n", "if", "bytes", ".", "Equal", "(", "oldContent", ",", "newContent", ")", "{", "return", "nil", "\n", "}", "\n\n", "ef", ".", "File", ".", "Content", "=", "string", "(", "newContent", ")", "\n", "_", ",", "err", "=", "WriteFile", "(", "ef", ".", "File", ",", "root", ")", "\n", "return", "err", "\n", "}" ]
// WriteEnvFile updates an existing env `KEY=value` formated file with // new values provided in EnvFile.Vars; File.Content is ignored. // Existing ordering and any unknown formatting such as comments are // preserved. If no changes are required the file is untouched.
[ "WriteEnvFile", "updates", "an", "existing", "env", "KEY", "=", "value", "formated", "file", "with", "new", "values", "provided", "in", "EnvFile", ".", "Vars", ";", "File", ".", "Content", "is", "ignored", ".", "Existing", "ordering", "and", "any", "unknown", "formatting", "such", "as", "comments", "are", "preserved", ".", "If", "no", "changes", "are", "required", "the", "file", "is", "untouched", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/system/env_file.go#L74-L105
16,883
coreos/coreos-cloudinit
system/env_file.go
keys
func keys(m map[string]string) (s []string) { for k := range m { s = append(s, k) } sort.Strings(s) return }
go
func keys(m map[string]string) (s []string) { for k := range m { s = append(s, k) } sort.Strings(s) return }
[ "func", "keys", "(", "m", "map", "[", "string", "]", "string", ")", "(", "s", "[", "]", "string", ")", "{", "for", "k", ":=", "range", "m", "{", "s", "=", "append", "(", "s", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "s", ")", "\n", "return", "\n", "}" ]
// keys returns the keys of a map in sorted order
[ "keys", "returns", "the", "keys", "of", "a", "map", "in", "sorted", "order" ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/system/env_file.go#L108-L114
16,884
coreos/coreos-cloudinit
system/fleet.go
Units
func (fe Fleet) Units() []Unit { return []Unit{{config.Unit{ Name: "fleet.service", Runtime: true, DropIns: []config.UnitDropIn{{ Name: "20-cloudinit.conf", Content: serviceContents(fe.Fleet), }}, }}} }
go
func (fe Fleet) Units() []Unit { return []Unit{{config.Unit{ Name: "fleet.service", Runtime: true, DropIns: []config.UnitDropIn{{ Name: "20-cloudinit.conf", Content: serviceContents(fe.Fleet), }}, }}} }
[ "func", "(", "fe", "Fleet", ")", "Units", "(", ")", "[", "]", "Unit", "{", "return", "[", "]", "Unit", "{", "{", "config", ".", "Unit", "{", "Name", ":", "\"", "\"", ",", "Runtime", ":", "true", ",", "DropIns", ":", "[", "]", "config", ".", "UnitDropIn", "{", "{", "Name", ":", "\"", "\"", ",", "Content", ":", "serviceContents", "(", "fe", ".", "Fleet", ")", ",", "}", "}", ",", "}", "}", "}", "\n", "}" ]
// Units generates a Unit file drop-in for fleet, if any fleet options were // configured in cloud-config
[ "Units", "generates", "a", "Unit", "file", "drop", "-", "in", "for", "fleet", "if", "any", "fleet", "options", "were", "configured", "in", "cloud", "-", "config" ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/system/fleet.go#L29-L38
16,885
coreos/coreos-cloudinit
system/env.go
serviceContents
func serviceContents(e interface{}) string { vars := getEnvVars(e) if len(vars) == 0 { return "" } out := "[Service]\n" for _, v := range vars { out += fmt.Sprintf("Environment=\"%s\"\n", v) } return out }
go
func serviceContents(e interface{}) string { vars := getEnvVars(e) if len(vars) == 0 { return "" } out := "[Service]\n" for _, v := range vars { out += fmt.Sprintf("Environment=\"%s\"\n", v) } return out }
[ "func", "serviceContents", "(", "e", "interface", "{", "}", ")", "string", "{", "vars", ":=", "getEnvVars", "(", "e", ")", "\n", "if", "len", "(", "vars", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "out", ":=", "\"", "\\n", "\"", "\n", "for", "_", ",", "v", ":=", "range", "vars", "{", "out", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\n", "\"", ",", "v", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// serviceContents generates the contents for a drop-in unit given the config. // The argument must be a struct from the 'config' package.
[ "serviceContents", "generates", "the", "contents", "for", "a", "drop", "-", "in", "unit", "given", "the", "config", ".", "The", "argument", "must", "be", "a", "struct", "from", "the", "config", "package", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/system/env.go#L26-L37
16,886
coreos/coreos-cloudinit
system/locksmith.go
Units
func (ee Locksmith) Units() []Unit { return []Unit{{config.Unit{ Name: "locksmithd.service", Runtime: true, DropIns: []config.UnitDropIn{{ Name: "20-cloudinit.conf", Content: serviceContents(ee.Locksmith), }}, }}} }
go
func (ee Locksmith) Units() []Unit { return []Unit{{config.Unit{ Name: "locksmithd.service", Runtime: true, DropIns: []config.UnitDropIn{{ Name: "20-cloudinit.conf", Content: serviceContents(ee.Locksmith), }}, }}} }
[ "func", "(", "ee", "Locksmith", ")", "Units", "(", ")", "[", "]", "Unit", "{", "return", "[", "]", "Unit", "{", "{", "config", ".", "Unit", "{", "Name", ":", "\"", "\"", ",", "Runtime", ":", "true", ",", "DropIns", ":", "[", "]", "config", ".", "UnitDropIn", "{", "{", "Name", ":", "\"", "\"", ",", "Content", ":", "serviceContents", "(", "ee", ".", "Locksmith", ")", ",", "}", "}", ",", "}", "}", "}", "\n", "}" ]
// Units creates a Unit file drop-in for etcd, using any configured options.
[ "Units", "creates", "a", "Unit", "file", "drop", "-", "in", "for", "etcd", "using", "any", "configured", "options", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/system/locksmith.go#L28-L37
16,887
coreos/coreos-cloudinit
pkg/http_client.go
GetRetry
func (h *HttpClient) GetRetry(rawurl string) ([]byte, error) { if rawurl == "" { return nil, ErrInvalid{errors.New("URL is empty. Skipping.")} } url, err := neturl.Parse(rawurl) if err != nil { return nil, ErrInvalid{err} } // Unfortunately, url.Parse is too generic to throw errors if a URL does not // have a valid HTTP scheme. So, we have to do this extra validation if !strings.HasPrefix(url.Scheme, "http") { return nil, ErrInvalid{fmt.Errorf("URL %s does not have a valid HTTP scheme. Skipping.", rawurl)} } dataURL := url.String() duration := h.InitialBackoff for retry := 1; retry <= h.MaxRetries; retry++ { log.Printf("Fetching data from %s. Attempt #%d", dataURL, retry) data, err := h.Get(dataURL) switch err.(type) { case ErrNetwork: log.Printf(err.Error()) case ErrServer: log.Printf(err.Error()) case ErrNotFound: return data, err default: return data, err } duration = ExpBackoff(duration, h.MaxBackoff) log.Printf("Sleeping for %v...", duration) time.Sleep(duration) } return nil, ErrTimeout{fmt.Errorf("Unable to fetch data. Maximum retries reached: %d", h.MaxRetries)} }
go
func (h *HttpClient) GetRetry(rawurl string) ([]byte, error) { if rawurl == "" { return nil, ErrInvalid{errors.New("URL is empty. Skipping.")} } url, err := neturl.Parse(rawurl) if err != nil { return nil, ErrInvalid{err} } // Unfortunately, url.Parse is too generic to throw errors if a URL does not // have a valid HTTP scheme. So, we have to do this extra validation if !strings.HasPrefix(url.Scheme, "http") { return nil, ErrInvalid{fmt.Errorf("URL %s does not have a valid HTTP scheme. Skipping.", rawurl)} } dataURL := url.String() duration := h.InitialBackoff for retry := 1; retry <= h.MaxRetries; retry++ { log.Printf("Fetching data from %s. Attempt #%d", dataURL, retry) data, err := h.Get(dataURL) switch err.(type) { case ErrNetwork: log.Printf(err.Error()) case ErrServer: log.Printf(err.Error()) case ErrNotFound: return data, err default: return data, err } duration = ExpBackoff(duration, h.MaxBackoff) log.Printf("Sleeping for %v...", duration) time.Sleep(duration) } return nil, ErrTimeout{fmt.Errorf("Unable to fetch data. Maximum retries reached: %d", h.MaxRetries)} }
[ "func", "(", "h", "*", "HttpClient", ")", "GetRetry", "(", "rawurl", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "rawurl", "==", "\"", "\"", "{", "return", "nil", ",", "ErrInvalid", "{", "errors", ".", "New", "(", "\"", "\"", ")", "}", "\n", "}", "\n\n", "url", ",", "err", ":=", "neturl", ".", "Parse", "(", "rawurl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ErrInvalid", "{", "err", "}", "\n", "}", "\n\n", "// Unfortunately, url.Parse is too generic to throw errors if a URL does not", "// have a valid HTTP scheme. So, we have to do this extra validation", "if", "!", "strings", ".", "HasPrefix", "(", "url", ".", "Scheme", ",", "\"", "\"", ")", "{", "return", "nil", ",", "ErrInvalid", "{", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rawurl", ")", "}", "\n", "}", "\n\n", "dataURL", ":=", "url", ".", "String", "(", ")", "\n\n", "duration", ":=", "h", ".", "InitialBackoff", "\n", "for", "retry", ":=", "1", ";", "retry", "<=", "h", ".", "MaxRetries", ";", "retry", "++", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "dataURL", ",", "retry", ")", "\n\n", "data", ",", "err", ":=", "h", ".", "Get", "(", "dataURL", ")", "\n", "switch", "err", ".", "(", "type", ")", "{", "case", "ErrNetwork", ":", "log", ".", "Printf", "(", "err", ".", "Error", "(", ")", ")", "\n", "case", "ErrServer", ":", "log", ".", "Printf", "(", "err", ".", "Error", "(", ")", ")", "\n", "case", "ErrNotFound", ":", "return", "data", ",", "err", "\n", "default", ":", "return", "data", ",", "err", "\n", "}", "\n\n", "duration", "=", "ExpBackoff", "(", "duration", ",", "h", ".", "MaxBackoff", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "duration", ")", "\n", "time", ".", "Sleep", "(", "duration", ")", "\n", "}", "\n\n", "return", "nil", ",", "ErrTimeout", "{", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "h", ".", "MaxRetries", ")", "}", "\n", "}" ]
// GetRetry fetches a given URL with support for exponential backoff and maximum retries
[ "GetRetry", "fetches", "a", "given", "URL", "with", "support", "for", "exponential", "backoff", "and", "maximum", "retries" ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/pkg/http_client.go#L103-L143
16,888
coreos/coreos-cloudinit
initialize/env.go
Apply
func (e *Environment) Apply(data string) string { for key, val := range e.substitutions { matchKey := strings.Replace(key, `$`, `\$`, -1) replKey := strings.Replace(key, `$`, `$$`, -1) // "key" -> "val" data = regexp.MustCompile(`([^\\]|^)`+matchKey).ReplaceAllString(data, `${1}`+val) // "\key" -> "key" data = regexp.MustCompile(`\\`+matchKey).ReplaceAllString(data, replKey) } return data }
go
func (e *Environment) Apply(data string) string { for key, val := range e.substitutions { matchKey := strings.Replace(key, `$`, `\$`, -1) replKey := strings.Replace(key, `$`, `$$`, -1) // "key" -> "val" data = regexp.MustCompile(`([^\\]|^)`+matchKey).ReplaceAllString(data, `${1}`+val) // "\key" -> "key" data = regexp.MustCompile(`\\`+matchKey).ReplaceAllString(data, replKey) } return data }
[ "func", "(", "e", "*", "Environment", ")", "Apply", "(", "data", "string", ")", "string", "{", "for", "key", ",", "val", ":=", "range", "e", ".", "substitutions", "{", "matchKey", ":=", "strings", ".", "Replace", "(", "key", ",", "`$`", ",", "`\\$`", ",", "-", "1", ")", "\n", "replKey", ":=", "strings", ".", "Replace", "(", "key", ",", "`$`", ",", "`$$`", ",", "-", "1", ")", "\n\n", "// \"key\" -> \"val\"", "data", "=", "regexp", ".", "MustCompile", "(", "`([^\\\\]|^)`", "+", "matchKey", ")", ".", "ReplaceAllString", "(", "data", ",", "`${1}`", "+", "val", ")", "\n", "// \"\\key\" -> \"key\"", "data", "=", "regexp", ".", "MustCompile", "(", "`\\\\`", "+", "matchKey", ")", ".", "ReplaceAllString", "(", "data", ",", "replKey", ")", "\n", "}", "\n", "return", "data", "\n", "}" ]
// Apply goes through the map of substitutions and replaces all instances of // the keys with their respective values. It supports escaping substitutions // with a leading '\'.
[ "Apply", "goes", "through", "the", "map", "of", "substitutions", "and", "replaces", "all", "instances", "of", "the", "keys", "with", "their", "respective", "values", ".", "It", "supports", "escaping", "substitutions", "with", "a", "leading", "\\", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/initialize/env.go#L79-L90
16,889
coreos/coreos-cloudinit
config/validate/rules.go
checkDiscoveryUrl
func checkDiscoveryUrl(cfg node, report *Report) { c := cfg.Child("coreos").Child("etcd").Child("discovery") if !c.IsValid() { return } if _, err := url.ParseRequestURI(c.String()); err != nil { report.Warning(c.line, "discovery URL is not valid") } }
go
func checkDiscoveryUrl(cfg node, report *Report) { c := cfg.Child("coreos").Child("etcd").Child("discovery") if !c.IsValid() { return } if _, err := url.ParseRequestURI(c.String()); err != nil { report.Warning(c.line, "discovery URL is not valid") } }
[ "func", "checkDiscoveryUrl", "(", "cfg", "node", ",", "report", "*", "Report", ")", "{", "c", ":=", "cfg", ".", "Child", "(", "\"", "\"", ")", ".", "Child", "(", "\"", "\"", ")", ".", "Child", "(", "\"", "\"", ")", "\n", "if", "!", "c", ".", "IsValid", "(", ")", "{", "return", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "c", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "report", ".", "Warning", "(", "c", ".", "line", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// checkDiscoveryUrl verifies that the string is a valid url.
[ "checkDiscoveryUrl", "verifies", "that", "the", "string", "is", "a", "valid", "url", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/rules.go#L40-L49
16,890
coreos/coreos-cloudinit
config/validate/rules.go
checkEncoding
func checkEncoding(cfg node, report *Report) { for _, f := range cfg.Child("write_files").children { e := f.Child("encoding") if !e.IsValid() { continue } c := f.Child("content") if _, err := config.DecodeContent(c.String(), e.String()); err != nil { report.Error(c.line, fmt.Sprintf("content cannot be decoded as %q", e.String())) } } }
go
func checkEncoding(cfg node, report *Report) { for _, f := range cfg.Child("write_files").children { e := f.Child("encoding") if !e.IsValid() { continue } c := f.Child("content") if _, err := config.DecodeContent(c.String(), e.String()); err != nil { report.Error(c.line, fmt.Sprintf("content cannot be decoded as %q", e.String())) } } }
[ "func", "checkEncoding", "(", "cfg", "node", ",", "report", "*", "Report", ")", "{", "for", "_", ",", "f", ":=", "range", "cfg", ".", "Child", "(", "\"", "\"", ")", ".", "children", "{", "e", ":=", "f", ".", "Child", "(", "\"", "\"", ")", "\n", "if", "!", "e", ".", "IsValid", "(", ")", "{", "continue", "\n", "}", "\n\n", "c", ":=", "f", ".", "Child", "(", "\"", "\"", ")", "\n", "if", "_", ",", "err", ":=", "config", ".", "DecodeContent", "(", "c", ".", "String", "(", ")", ",", "e", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "report", ".", "Error", "(", "c", ".", "line", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "String", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// checkEncoding validates that, for each file under 'write_files', the // content can be decoded given the specified encoding.
[ "checkEncoding", "validates", "that", "for", "each", "file", "under", "write_files", "the", "content", "can", "be", "decoded", "given", "the", "specified", "encoding", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/rules.go#L53-L65
16,891
coreos/coreos-cloudinit
config/validate/rules.go
checkStructure
func checkStructure(cfg node, report *Report) { g := NewNode(config.CloudConfig{}, NewContext([]byte{})) checkNodeStructure(cfg, g, report) }
go
func checkStructure(cfg node, report *Report) { g := NewNode(config.CloudConfig{}, NewContext([]byte{})) checkNodeStructure(cfg, g, report) }
[ "func", "checkStructure", "(", "cfg", "node", ",", "report", "*", "Report", ")", "{", "g", ":=", "NewNode", "(", "config", ".", "CloudConfig", "{", "}", ",", "NewContext", "(", "[", "]", "byte", "{", "}", ")", ")", "\n", "checkNodeStructure", "(", "cfg", ",", "g", ",", "report", ")", "\n", "}" ]
// checkStructure compares the provided config to the empty config.CloudConfig // structure. Each node is checked to make sure that it exists in the known // structure and that its type is compatible.
[ "checkStructure", "compares", "the", "provided", "config", "to", "the", "empty", "config", ".", "CloudConfig", "structure", ".", "Each", "node", "is", "checked", "to", "make", "sure", "that", "it", "exists", "in", "the", "known", "structure", "and", "that", "its", "type", "is", "compatible", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/rules.go#L70-L73
16,892
coreos/coreos-cloudinit
config/validate/rules.go
isCompatible
func isCompatible(n, g reflect.Kind) bool { switch g { case reflect.String: return n == reflect.String || n == reflect.Int || n == reflect.Float64 || n == reflect.Bool case reflect.Struct: return n == reflect.Struct || n == reflect.Map case reflect.Float64: return n == reflect.Float64 || n == reflect.Int case reflect.Bool, reflect.Slice, reflect.Int: return n == g default: panic(fmt.Sprintf("isCompatible(): unhandled kind %s", g)) } }
go
func isCompatible(n, g reflect.Kind) bool { switch g { case reflect.String: return n == reflect.String || n == reflect.Int || n == reflect.Float64 || n == reflect.Bool case reflect.Struct: return n == reflect.Struct || n == reflect.Map case reflect.Float64: return n == reflect.Float64 || n == reflect.Int case reflect.Bool, reflect.Slice, reflect.Int: return n == g default: panic(fmt.Sprintf("isCompatible(): unhandled kind %s", g)) } }
[ "func", "isCompatible", "(", "n", ",", "g", "reflect", ".", "Kind", ")", "bool", "{", "switch", "g", "{", "case", "reflect", ".", "String", ":", "return", "n", "==", "reflect", ".", "String", "||", "n", "==", "reflect", ".", "Int", "||", "n", "==", "reflect", ".", "Float64", "||", "n", "==", "reflect", ".", "Bool", "\n", "case", "reflect", ".", "Struct", ":", "return", "n", "==", "reflect", ".", "Struct", "||", "n", "==", "reflect", ".", "Map", "\n", "case", "reflect", ".", "Float64", ":", "return", "n", "==", "reflect", ".", "Float64", "||", "n", "==", "reflect", ".", "Int", "\n", "case", "reflect", ".", "Bool", ",", "reflect", ".", "Slice", ",", "reflect", ".", "Int", ":", "return", "n", "==", "g", "\n", "default", ":", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "g", ")", ")", "\n", "}", "\n", "}" ]
// isCompatible determines if the type of kind n can be converted to the type // of kind g in the context of YAML. This is not an exhaustive list, but its // enough for the purposes of cloud-config validation.
[ "isCompatible", "determines", "if", "the", "type", "of", "kind", "n", "can", "be", "converted", "to", "the", "type", "of", "kind", "g", "in", "the", "context", "of", "YAML", ".", "This", "is", "not", "an", "exhaustive", "list", "but", "its", "enough", "for", "the", "purposes", "of", "cloud", "-", "config", "validation", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/rules.go#L109-L122
16,893
coreos/coreos-cloudinit
coreos-cloudinit.go
getDatasources
func getDatasources() []datasource.Datasource { dss := make([]datasource.Datasource, 0, 5) if flags.sources.file != "" { dss = append(dss, file.NewDatasource(flags.sources.file)) } if flags.sources.url != "" { dss = append(dss, url.NewDatasource(flags.sources.url)) } if flags.sources.configDrive != "" { dss = append(dss, configdrive.NewDatasource(flags.sources.configDrive)) } if flags.sources.metadataService { dss = append(dss, ec2.NewDatasource(ec2.DefaultAddress)) } if flags.sources.ec2MetadataService != "" { dss = append(dss, ec2.NewDatasource(flags.sources.ec2MetadataService)) } if flags.sources.gceMetadataService != "" { dss = append(dss, gce.NewDatasource(flags.sources.gceMetadataService)) } if flags.sources.cloudSigmaMetadataService { dss = append(dss, cloudsigma.NewServerContextService()) } if flags.sources.digitalOceanMetadataService != "" { dss = append(dss, digitalocean.NewDatasource(flags.sources.digitalOceanMetadataService)) } if flags.sources.waagent != "" { dss = append(dss, waagent.NewDatasource(flags.sources.waagent)) } if flags.sources.packetMetadataService != "" { dss = append(dss, packet.NewDatasource(flags.sources.packetMetadataService)) } if flags.sources.procCmdLine { dss = append(dss, proc_cmdline.NewDatasource()) } if flags.sources.vmware { dss = append(dss, vmware.NewDatasource("")) } if flags.sources.ovfEnv != "" { dss = append(dss, vmware.NewDatasource(flags.sources.ovfEnv)) } return dss }
go
func getDatasources() []datasource.Datasource { dss := make([]datasource.Datasource, 0, 5) if flags.sources.file != "" { dss = append(dss, file.NewDatasource(flags.sources.file)) } if flags.sources.url != "" { dss = append(dss, url.NewDatasource(flags.sources.url)) } if flags.sources.configDrive != "" { dss = append(dss, configdrive.NewDatasource(flags.sources.configDrive)) } if flags.sources.metadataService { dss = append(dss, ec2.NewDatasource(ec2.DefaultAddress)) } if flags.sources.ec2MetadataService != "" { dss = append(dss, ec2.NewDatasource(flags.sources.ec2MetadataService)) } if flags.sources.gceMetadataService != "" { dss = append(dss, gce.NewDatasource(flags.sources.gceMetadataService)) } if flags.sources.cloudSigmaMetadataService { dss = append(dss, cloudsigma.NewServerContextService()) } if flags.sources.digitalOceanMetadataService != "" { dss = append(dss, digitalocean.NewDatasource(flags.sources.digitalOceanMetadataService)) } if flags.sources.waagent != "" { dss = append(dss, waagent.NewDatasource(flags.sources.waagent)) } if flags.sources.packetMetadataService != "" { dss = append(dss, packet.NewDatasource(flags.sources.packetMetadataService)) } if flags.sources.procCmdLine { dss = append(dss, proc_cmdline.NewDatasource()) } if flags.sources.vmware { dss = append(dss, vmware.NewDatasource("")) } if flags.sources.ovfEnv != "" { dss = append(dss, vmware.NewDatasource(flags.sources.ovfEnv)) } return dss }
[ "func", "getDatasources", "(", ")", "[", "]", "datasource", ".", "Datasource", "{", "dss", ":=", "make", "(", "[", "]", "datasource", ".", "Datasource", ",", "0", ",", "5", ")", "\n", "if", "flags", ".", "sources", ".", "file", "!=", "\"", "\"", "{", "dss", "=", "append", "(", "dss", ",", "file", ".", "NewDatasource", "(", "flags", ".", "sources", ".", "file", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "url", "!=", "\"", "\"", "{", "dss", "=", "append", "(", "dss", ",", "url", ".", "NewDatasource", "(", "flags", ".", "sources", ".", "url", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "configDrive", "!=", "\"", "\"", "{", "dss", "=", "append", "(", "dss", ",", "configdrive", ".", "NewDatasource", "(", "flags", ".", "sources", ".", "configDrive", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "metadataService", "{", "dss", "=", "append", "(", "dss", ",", "ec2", ".", "NewDatasource", "(", "ec2", ".", "DefaultAddress", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "ec2MetadataService", "!=", "\"", "\"", "{", "dss", "=", "append", "(", "dss", ",", "ec2", ".", "NewDatasource", "(", "flags", ".", "sources", ".", "ec2MetadataService", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "gceMetadataService", "!=", "\"", "\"", "{", "dss", "=", "append", "(", "dss", ",", "gce", ".", "NewDatasource", "(", "flags", ".", "sources", ".", "gceMetadataService", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "cloudSigmaMetadataService", "{", "dss", "=", "append", "(", "dss", ",", "cloudsigma", ".", "NewServerContextService", "(", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "digitalOceanMetadataService", "!=", "\"", "\"", "{", "dss", "=", "append", "(", "dss", ",", "digitalocean", ".", "NewDatasource", "(", "flags", ".", "sources", ".", "digitalOceanMetadataService", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "waagent", "!=", "\"", "\"", "{", "dss", "=", "append", "(", "dss", ",", "waagent", ".", "NewDatasource", "(", "flags", ".", "sources", ".", "waagent", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "packetMetadataService", "!=", "\"", "\"", "{", "dss", "=", "append", "(", "dss", ",", "packet", ".", "NewDatasource", "(", "flags", ".", "sources", ".", "packetMetadataService", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "procCmdLine", "{", "dss", "=", "append", "(", "dss", ",", "proc_cmdline", ".", "NewDatasource", "(", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "vmware", "{", "dss", "=", "append", "(", "dss", ",", "vmware", ".", "NewDatasource", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "flags", ".", "sources", ".", "ovfEnv", "!=", "\"", "\"", "{", "dss", "=", "append", "(", "dss", ",", "vmware", ".", "NewDatasource", "(", "flags", ".", "sources", ".", "ovfEnv", ")", ")", "\n", "}", "\n", "return", "dss", "\n", "}" ]
// getDatasources creates a slice of possible Datasources for cloudinit based // on the different source command-line flags.
[ "getDatasources", "creates", "a", "slice", "of", "possible", "Datasources", "for", "cloudinit", "based", "on", "the", "different", "source", "command", "-", "line", "flags", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/coreos-cloudinit.go#L310-L352
16,894
coreos/coreos-cloudinit
coreos-cloudinit.go
selectDatasource
func selectDatasource(sources []datasource.Datasource) datasource.Datasource { ds := make(chan datasource.Datasource) stop := make(chan struct{}) var wg sync.WaitGroup for _, s := range sources { wg.Add(1) go func(s datasource.Datasource) { defer wg.Done() duration := datasourceInterval for { log.Printf("Checking availability of %q\n", s.Type()) if s.IsAvailable() { ds <- s return } else if !s.AvailabilityChanges() { return } select { case <-stop: return case <-time.After(duration): duration = pkg.ExpBackoff(duration, datasourceMaxInterval) } } }(s) } done := make(chan struct{}) go func() { wg.Wait() close(done) }() var s datasource.Datasource select { case s = <-ds: case <-done: case <-time.After(datasourceTimeout): } close(stop) return s }
go
func selectDatasource(sources []datasource.Datasource) datasource.Datasource { ds := make(chan datasource.Datasource) stop := make(chan struct{}) var wg sync.WaitGroup for _, s := range sources { wg.Add(1) go func(s datasource.Datasource) { defer wg.Done() duration := datasourceInterval for { log.Printf("Checking availability of %q\n", s.Type()) if s.IsAvailable() { ds <- s return } else if !s.AvailabilityChanges() { return } select { case <-stop: return case <-time.After(duration): duration = pkg.ExpBackoff(duration, datasourceMaxInterval) } } }(s) } done := make(chan struct{}) go func() { wg.Wait() close(done) }() var s datasource.Datasource select { case s = <-ds: case <-done: case <-time.After(datasourceTimeout): } close(stop) return s }
[ "func", "selectDatasource", "(", "sources", "[", "]", "datasource", ".", "Datasource", ")", "datasource", ".", "Datasource", "{", "ds", ":=", "make", "(", "chan", "datasource", ".", "Datasource", ")", "\n", "stop", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n\n", "for", "_", ",", "s", ":=", "range", "sources", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "s", "datasource", ".", "Datasource", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n\n", "duration", ":=", "datasourceInterval", "\n", "for", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "s", ".", "Type", "(", ")", ")", "\n", "if", "s", ".", "IsAvailable", "(", ")", "{", "ds", "<-", "s", "\n", "return", "\n", "}", "else", "if", "!", "s", ".", "AvailabilityChanges", "(", ")", "{", "return", "\n", "}", "\n", "select", "{", "case", "<-", "stop", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "duration", ")", ":", "duration", "=", "pkg", ".", "ExpBackoff", "(", "duration", ",", "datasourceMaxInterval", ")", "\n", "}", "\n", "}", "\n", "}", "(", "s", ")", "\n", "}", "\n\n", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "done", ")", "\n", "}", "(", ")", "\n\n", "var", "s", "datasource", ".", "Datasource", "\n", "select", "{", "case", "s", "=", "<-", "ds", ":", "case", "<-", "done", ":", "case", "<-", "time", ".", "After", "(", "datasourceTimeout", ")", ":", "}", "\n\n", "close", "(", "stop", ")", "\n", "return", "s", "\n", "}" ]
// selectDatasource attempts to choose a valid Datasource to use based on its // current availability. The first Datasource to report to be available is // returned. Datasources will be retried if possible if they are not // immediately available. If all Datasources are permanently unavailable or // datasourceTimeout is reached before one becomes available, nil is returned.
[ "selectDatasource", "attempts", "to", "choose", "a", "valid", "Datasource", "to", "use", "based", "on", "its", "current", "availability", ".", "The", "first", "Datasource", "to", "report", "to", "be", "available", "is", "returned", ".", "Datasources", "will", "be", "retried", "if", "possible", "if", "they", "are", "not", "immediately", "available", ".", "If", "all", "Datasources", "are", "permanently", "unavailable", "or", "datasourceTimeout", "is", "reached", "before", "one", "becomes", "available", "nil", "is", "returned", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/coreos-cloudinit.go#L359-L403
16,895
coreos/coreos-cloudinit
config/config.go
Decode
func (cc *CloudConfig) Decode() error { for i, file := range cc.WriteFiles { content, err := DecodeContent(file.Content, file.Encoding) if err != nil { return err } cc.WriteFiles[i].Content = string(content) cc.WriteFiles[i].Encoding = "" } return nil }
go
func (cc *CloudConfig) Decode() error { for i, file := range cc.WriteFiles { content, err := DecodeContent(file.Content, file.Encoding) if err != nil { return err } cc.WriteFiles[i].Content = string(content) cc.WriteFiles[i].Encoding = "" } return nil }
[ "func", "(", "cc", "*", "CloudConfig", ")", "Decode", "(", ")", "error", "{", "for", "i", ",", "file", ":=", "range", "cc", ".", "WriteFiles", "{", "content", ",", "err", ":=", "DecodeContent", "(", "file", ".", "Content", ",", "file", ".", "Encoding", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cc", ".", "WriteFiles", "[", "i", "]", ".", "Content", "=", "string", "(", "content", ")", "\n", "cc", ".", "WriteFiles", "[", "i", "]", ".", "Encoding", "=", "\"", "\"", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Decode decodes the content of cloud config. Currently only WriteFiles section // supports several types of encoding and all of them are supported. After // decode operation, Encoding type is unset.
[ "Decode", "decodes", "the", "content", "of", "cloud", "config", ".", "Currently", "only", "WriteFiles", "section", "supports", "several", "types", "of", "encoding", "and", "all", "of", "them", "are", "supported", ".", "After", "decode", "operation", "Encoding", "type", "is", "unset", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/config.go#L74-L86
16,896
coreos/coreos-cloudinit
config/config.go
AssertStructValid
func AssertStructValid(c interface{}) error { ct := reflect.TypeOf(c) cv := reflect.ValueOf(c) for i := 0; i < ct.NumField(); i++ { ft := ct.Field(i) if !isFieldExported(ft) { continue } if err := AssertValid(cv.Field(i), ft.Tag.Get("valid")); err != nil { err.Field = ft.Name return err } } return nil }
go
func AssertStructValid(c interface{}) error { ct := reflect.TypeOf(c) cv := reflect.ValueOf(c) for i := 0; i < ct.NumField(); i++ { ft := ct.Field(i) if !isFieldExported(ft) { continue } if err := AssertValid(cv.Field(i), ft.Tag.Get("valid")); err != nil { err.Field = ft.Name return err } } return nil }
[ "func", "AssertStructValid", "(", "c", "interface", "{", "}", ")", "error", "{", "ct", ":=", "reflect", ".", "TypeOf", "(", "c", ")", "\n", "cv", ":=", "reflect", ".", "ValueOf", "(", "c", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "ct", ".", "NumField", "(", ")", ";", "i", "++", "{", "ft", ":=", "ct", ".", "Field", "(", "i", ")", "\n", "if", "!", "isFieldExported", "(", "ft", ")", "{", "continue", "\n", "}", "\n\n", "if", "err", ":=", "AssertValid", "(", "cv", ".", "Field", "(", "i", ")", ",", "ft", ".", "Tag", ".", "Get", "(", "\"", "\"", ")", ")", ";", "err", "!=", "nil", "{", "err", ".", "Field", "=", "ft", ".", "Name", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AssertStructValid checks the fields in the structure and makes sure that // they contain valid values as specified by the 'valid' flag. Empty fields are // implicitly valid.
[ "AssertStructValid", "checks", "the", "fields", "in", "the", "structure", "and", "makes", "sure", "that", "they", "contain", "valid", "values", "as", "specified", "by", "the", "valid", "flag", ".", "Empty", "fields", "are", "implicitly", "valid", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/config.go#L118-L133
16,897
coreos/coreos-cloudinit
config/config.go
AssertValid
func AssertValid(value reflect.Value, valid string) *ErrorValid { if valid == "" || isZero(value) { return nil } vs := fmt.Sprintf("%v", value.Interface()) if m, _ := regexp.MatchString(valid, vs); m { return nil } return &ErrorValid{ Value: vs, Valid: valid, } }
go
func AssertValid(value reflect.Value, valid string) *ErrorValid { if valid == "" || isZero(value) { return nil } vs := fmt.Sprintf("%v", value.Interface()) if m, _ := regexp.MatchString(valid, vs); m { return nil } return &ErrorValid{ Value: vs, Valid: valid, } }
[ "func", "AssertValid", "(", "value", "reflect", ".", "Value", ",", "valid", "string", ")", "*", "ErrorValid", "{", "if", "valid", "==", "\"", "\"", "||", "isZero", "(", "value", ")", "{", "return", "nil", "\n", "}", "\n\n", "vs", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "value", ".", "Interface", "(", ")", ")", "\n", "if", "m", ",", "_", ":=", "regexp", ".", "MatchString", "(", "valid", ",", "vs", ")", ";", "m", "{", "return", "nil", "\n", "}", "\n\n", "return", "&", "ErrorValid", "{", "Value", ":", "vs", ",", "Valid", ":", "valid", ",", "}", "\n", "}" ]
// AssertValid checks to make sure that the given value is in the list of // valid values. Zero values are implicitly valid.
[ "AssertValid", "checks", "to", "make", "sure", "that", "the", "given", "value", "is", "in", "the", "list", "of", "valid", "values", ".", "Zero", "values", "are", "implicitly", "valid", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/config.go#L137-L151
16,898
coreos/coreos-cloudinit
config/validate/validate.go
Validate
func Validate(userdataBytes []byte) (Report, error) { switch { case len(userdataBytes) == 0: return Report{}, nil case config.IsScript(string(userdataBytes)): return Report{}, nil case config.IsIgnitionConfig(string(userdataBytes)): return Report{}, nil case config.IsCloudConfig(string(userdataBytes)): return validateCloudConfig(userdataBytes, Rules) default: return Report{entries: []Entry{ {kind: entryError, message: `must be "#cloud-config" or begin with "#!"`, line: 1}, }}, nil } }
go
func Validate(userdataBytes []byte) (Report, error) { switch { case len(userdataBytes) == 0: return Report{}, nil case config.IsScript(string(userdataBytes)): return Report{}, nil case config.IsIgnitionConfig(string(userdataBytes)): return Report{}, nil case config.IsCloudConfig(string(userdataBytes)): return validateCloudConfig(userdataBytes, Rules) default: return Report{entries: []Entry{ {kind: entryError, message: `must be "#cloud-config" or begin with "#!"`, line: 1}, }}, nil } }
[ "func", "Validate", "(", "userdataBytes", "[", "]", "byte", ")", "(", "Report", ",", "error", ")", "{", "switch", "{", "case", "len", "(", "userdataBytes", ")", "==", "0", ":", "return", "Report", "{", "}", ",", "nil", "\n", "case", "config", ".", "IsScript", "(", "string", "(", "userdataBytes", ")", ")", ":", "return", "Report", "{", "}", ",", "nil", "\n", "case", "config", ".", "IsIgnitionConfig", "(", "string", "(", "userdataBytes", ")", ")", ":", "return", "Report", "{", "}", ",", "nil", "\n", "case", "config", ".", "IsCloudConfig", "(", "string", "(", "userdataBytes", ")", ")", ":", "return", "validateCloudConfig", "(", "userdataBytes", ",", "Rules", ")", "\n", "default", ":", "return", "Report", "{", "entries", ":", "[", "]", "Entry", "{", "{", "kind", ":", "entryError", ",", "message", ":", "`must be \"#cloud-config\" or begin with \"#!\"`", ",", "line", ":", "1", "}", ",", "}", "}", ",", "nil", "\n", "}", "\n", "}" ]
// Validate runs a series of validation tests against the given userdata and // returns a report detailing all of the issues. Presently, only cloud-configs // can be validated.
[ "Validate", "runs", "a", "series", "of", "validation", "tests", "against", "the", "given", "userdata", "and", "returns", "a", "report", "detailing", "all", "of", "the", "issues", ".", "Presently", "only", "cloud", "-", "configs", "can", "be", "validated", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/validate.go#L37-L52
16,899
coreos/coreos-cloudinit
config/validate/validate.go
validateCloudConfig
func validateCloudConfig(config []byte, rules []rule) (report Report, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("%v", r) } }() c, err := parseCloudConfig(config, &report) if err != nil { return report, err } for _, r := range rules { r(c, &report) } return report, nil }
go
func validateCloudConfig(config []byte, rules []rule) (report Report, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("%v", r) } }() c, err := parseCloudConfig(config, &report) if err != nil { return report, err } for _, r := range rules { r(c, &report) } return report, nil }
[ "func", "validateCloudConfig", "(", "config", "[", "]", "byte", ",", "rules", "[", "]", "rule", ")", "(", "report", "Report", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "c", ",", "err", ":=", "parseCloudConfig", "(", "config", ",", "&", "report", ")", "\n", "if", "err", "!=", "nil", "{", "return", "report", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "r", ":=", "range", "rules", "{", "r", "(", "c", ",", "&", "report", ")", "\n", "}", "\n", "return", "report", ",", "nil", "\n", "}" ]
// validateCloudConfig runs all of the validation rules in Rules and returns // the resulting report and any errors encountered.
[ "validateCloudConfig", "runs", "all", "of", "the", "validation", "rules", "in", "Rules", "and", "returns", "the", "resulting", "report", "and", "any", "errors", "encountered", "." ]
f1f0405491dfd073bbf074f7e374c9ef85600691
https://github.com/coreos/coreos-cloudinit/blob/f1f0405491dfd073bbf074f7e374c9ef85600691/config/validate/validate.go#L56-L72