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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
400
iotaledger/iota.go
bundle/bundle.go
AddEntry
func AddEntry(txs Bundle, bndlEntry BundleEntry) Bundle { bndlEntry = getBundleEntryWithDefaults(bndlEntry) prevLastIndex := uint64(len(txs)) lastIndex := uint64(len(txs)-1) + bndlEntry.Length tag := PadTag(bndlEntry.Tag) // set new last index on existing txs for i := range txs { txs[i].LastIndex = lastIndex } var i uint64 for ; i < bndlEntry.Length; i++ { var v int64 if i == 0 { v = bndlEntry.Value } txs = append(txs, transaction.Transaction{ Address: bndlEntry.Address, Value: v, Tag: tag, ObsoleteTag: tag, CurrentIndex: prevLastIndex + i, LastIndex: lastIndex, Timestamp: bndlEntry.Timestamp, SignatureMessageFragment: bndlEntry.SignatureMessageFragments[i], TrunkTransaction: NullHashTrytes, BranchTransaction: NullHashTrytes, Bundle: NullHashTrytes, Nonce: NullNonceTrytes, Hash: NullHashTrytes, }) } return txs }
go
func AddEntry(txs Bundle, bndlEntry BundleEntry) Bundle { bndlEntry = getBundleEntryWithDefaults(bndlEntry) prevLastIndex := uint64(len(txs)) lastIndex := uint64(len(txs)-1) + bndlEntry.Length tag := PadTag(bndlEntry.Tag) // set new last index on existing txs for i := range txs { txs[i].LastIndex = lastIndex } var i uint64 for ; i < bndlEntry.Length; i++ { var v int64 if i == 0 { v = bndlEntry.Value } txs = append(txs, transaction.Transaction{ Address: bndlEntry.Address, Value: v, Tag: tag, ObsoleteTag: tag, CurrentIndex: prevLastIndex + i, LastIndex: lastIndex, Timestamp: bndlEntry.Timestamp, SignatureMessageFragment: bndlEntry.SignatureMessageFragments[i], TrunkTransaction: NullHashTrytes, BranchTransaction: NullHashTrytes, Bundle: NullHashTrytes, Nonce: NullNonceTrytes, Hash: NullHashTrytes, }) } return txs }
[ "func", "AddEntry", "(", "txs", "Bundle", ",", "bndlEntry", "BundleEntry", ")", "Bundle", "{", "bndlEntry", "=", "getBundleEntryWithDefaults", "(", "bndlEntry", ")", "\n", "prevLastIndex", ":=", "uint64", "(", "len", "(", "txs", ")", ")", "\n", "lastIndex", ":=", "uint64", "(", "len", "(", "txs", ")", "-", "1", ")", "+", "bndlEntry", ".", "Length", "\n", "tag", ":=", "PadTag", "(", "bndlEntry", ".", "Tag", ")", "\n\n", "// set new last index on existing txs", "for", "i", ":=", "range", "txs", "{", "txs", "[", "i", "]", ".", "LastIndex", "=", "lastIndex", "\n", "}", "\n\n", "var", "i", "uint64", "\n", "for", ";", "i", "<", "bndlEntry", ".", "Length", ";", "i", "++", "{", "var", "v", "int64", "\n", "if", "i", "==", "0", "{", "v", "=", "bndlEntry", ".", "Value", "\n", "}", "\n", "txs", "=", "append", "(", "txs", ",", "transaction", ".", "Transaction", "{", "Address", ":", "bndlEntry", ".", "Address", ",", "Value", ":", "v", ",", "Tag", ":", "tag", ",", "ObsoleteTag", ":", "tag", ",", "CurrentIndex", ":", "prevLastIndex", "+", "i", ",", "LastIndex", ":", "lastIndex", ",", "Timestamp", ":", "bndlEntry", ".", "Timestamp", ",", "SignatureMessageFragment", ":", "bndlEntry", ".", "SignatureMessageFragments", "[", "i", "]", ",", "TrunkTransaction", ":", "NullHashTrytes", ",", "BranchTransaction", ":", "NullHashTrytes", ",", "Bundle", ":", "NullHashTrytes", ",", "Nonce", ":", "NullNonceTrytes", ",", "Hash", ":", "NullHashTrytes", ",", "}", ")", "\n", "}", "\n\n", "return", "txs", "\n", "}" ]
// AddEntry adds a new entry to the bundle. It automatically adds additional transactions if the signature // message fragments don't fit into one transaction.
[ "AddEntry", "adds", "a", "new", "entry", "to", "the", "bundle", ".", "It", "automatically", "adds", "additional", "transactions", "if", "the", "signature", "message", "fragments", "don", "t", "fit", "into", "one", "transaction", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/bundle/bundle.go#L118-L147
401
iotaledger/iota.go
bundle/bundle.go
Finalize
func Finalize(bundle Bundle) (Bundle, error) { var valueTrits = make([]Trits, len(bundle)) var timestampTrits = make([]Trits, len(bundle)) var currentIndexTrits = make([]Trits, len(bundle)) var obsoleteTagTrits = make([]Trits, len(bundle)) var lastIndexTrits = PadTrits(IntToTrits(int64(bundle[0].LastIndex)), 27) for i := range bundle { valueTrits[i] = PadTrits(IntToTrits(bundle[i].Value), 81) timestampTrits[i] = PadTrits(IntToTrits(int64(bundle[i].Timestamp)), 27) currentIndexTrits[i] = PadTrits(IntToTrits(int64(bundle[i].CurrentIndex)), 27) obsoleteTagTrits[i] = PadTrits(MustTrytesToTrits(bundle[i].ObsoleteTag), 81) } var bundleHash Hash for { k := kerl.NewKerl() for i := 0; i < len(bundle); i++ { relevantTritsForBundleHash := MustTrytesToTrits( bundle[i].Address + MustTritsToTrytes(valueTrits[i]) + MustTritsToTrytes(obsoleteTagTrits[i]) + MustTritsToTrytes(timestampTrits[i]) + MustTritsToTrytes(currentIndexTrits[i]) + MustTritsToTrytes(lastIndexTrits), ) k.Absorb(relevantTritsForBundleHash) } bundleHashTrits, err := k.Squeeze(HashTrinarySize) if err != nil { return nil, err } bundleHash = MustTritsToTrytes(bundleHashTrits) // check whether normalized bundle hash can be computed normalizedBundleHash := signing.NormalizedBundleHash(bundleHash) ok := true for i := range normalizedBundleHash { if normalizedBundleHash[i] == 13 { ok = false break } } if ok { break } obsoleteTagTrits[0] = AddTrits(obsoleteTagTrits[0], Trits{1}) } // set the computed bundle hash on each tx in the bundle for i := range bundle { tx := &bundle[i] if i == 0 { tx.ObsoleteTag = MustTritsToTrytes(obsoleteTagTrits[0]) } tx.Bundle = bundleHash } return bundle, nil }
go
func Finalize(bundle Bundle) (Bundle, error) { var valueTrits = make([]Trits, len(bundle)) var timestampTrits = make([]Trits, len(bundle)) var currentIndexTrits = make([]Trits, len(bundle)) var obsoleteTagTrits = make([]Trits, len(bundle)) var lastIndexTrits = PadTrits(IntToTrits(int64(bundle[0].LastIndex)), 27) for i := range bundle { valueTrits[i] = PadTrits(IntToTrits(bundle[i].Value), 81) timestampTrits[i] = PadTrits(IntToTrits(int64(bundle[i].Timestamp)), 27) currentIndexTrits[i] = PadTrits(IntToTrits(int64(bundle[i].CurrentIndex)), 27) obsoleteTagTrits[i] = PadTrits(MustTrytesToTrits(bundle[i].ObsoleteTag), 81) } var bundleHash Hash for { k := kerl.NewKerl() for i := 0; i < len(bundle); i++ { relevantTritsForBundleHash := MustTrytesToTrits( bundle[i].Address + MustTritsToTrytes(valueTrits[i]) + MustTritsToTrytes(obsoleteTagTrits[i]) + MustTritsToTrytes(timestampTrits[i]) + MustTritsToTrytes(currentIndexTrits[i]) + MustTritsToTrytes(lastIndexTrits), ) k.Absorb(relevantTritsForBundleHash) } bundleHashTrits, err := k.Squeeze(HashTrinarySize) if err != nil { return nil, err } bundleHash = MustTritsToTrytes(bundleHashTrits) // check whether normalized bundle hash can be computed normalizedBundleHash := signing.NormalizedBundleHash(bundleHash) ok := true for i := range normalizedBundleHash { if normalizedBundleHash[i] == 13 { ok = false break } } if ok { break } obsoleteTagTrits[0] = AddTrits(obsoleteTagTrits[0], Trits{1}) } // set the computed bundle hash on each tx in the bundle for i := range bundle { tx := &bundle[i] if i == 0 { tx.ObsoleteTag = MustTritsToTrytes(obsoleteTagTrits[0]) } tx.Bundle = bundleHash } return bundle, nil }
[ "func", "Finalize", "(", "bundle", "Bundle", ")", "(", "Bundle", ",", "error", ")", "{", "var", "valueTrits", "=", "make", "(", "[", "]", "Trits", ",", "len", "(", "bundle", ")", ")", "\n", "var", "timestampTrits", "=", "make", "(", "[", "]", "Trits", ",", "len", "(", "bundle", ")", ")", "\n", "var", "currentIndexTrits", "=", "make", "(", "[", "]", "Trits", ",", "len", "(", "bundle", ")", ")", "\n", "var", "obsoleteTagTrits", "=", "make", "(", "[", "]", "Trits", ",", "len", "(", "bundle", ")", ")", "\n", "var", "lastIndexTrits", "=", "PadTrits", "(", "IntToTrits", "(", "int64", "(", "bundle", "[", "0", "]", ".", "LastIndex", ")", ")", ",", "27", ")", "\n\n", "for", "i", ":=", "range", "bundle", "{", "valueTrits", "[", "i", "]", "=", "PadTrits", "(", "IntToTrits", "(", "bundle", "[", "i", "]", ".", "Value", ")", ",", "81", ")", "\n", "timestampTrits", "[", "i", "]", "=", "PadTrits", "(", "IntToTrits", "(", "int64", "(", "bundle", "[", "i", "]", ".", "Timestamp", ")", ")", ",", "27", ")", "\n", "currentIndexTrits", "[", "i", "]", "=", "PadTrits", "(", "IntToTrits", "(", "int64", "(", "bundle", "[", "i", "]", ".", "CurrentIndex", ")", ")", ",", "27", ")", "\n", "obsoleteTagTrits", "[", "i", "]", "=", "PadTrits", "(", "MustTrytesToTrits", "(", "bundle", "[", "i", "]", ".", "ObsoleteTag", ")", ",", "81", ")", "\n", "}", "\n\n", "var", "bundleHash", "Hash", "\n", "for", "{", "k", ":=", "kerl", ".", "NewKerl", "(", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "bundle", ")", ";", "i", "++", "{", "relevantTritsForBundleHash", ":=", "MustTrytesToTrits", "(", "bundle", "[", "i", "]", ".", "Address", "+", "MustTritsToTrytes", "(", "valueTrits", "[", "i", "]", ")", "+", "MustTritsToTrytes", "(", "obsoleteTagTrits", "[", "i", "]", ")", "+", "MustTritsToTrytes", "(", "timestampTrits", "[", "i", "]", ")", "+", "MustTritsToTrytes", "(", "currentIndexTrits", "[", "i", "]", ")", "+", "MustTritsToTrytes", "(", "lastIndexTrits", ")", ",", ")", "\n", "k", ".", "Absorb", "(", "relevantTritsForBundleHash", ")", "\n", "}", "\n\n", "bundleHashTrits", ",", "err", ":=", "k", ".", "Squeeze", "(", "HashTrinarySize", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "bundleHash", "=", "MustTritsToTrytes", "(", "bundleHashTrits", ")", "\n\n", "// check whether normalized bundle hash can be computed", "normalizedBundleHash", ":=", "signing", ".", "NormalizedBundleHash", "(", "bundleHash", ")", "\n", "ok", ":=", "true", "\n", "for", "i", ":=", "range", "normalizedBundleHash", "{", "if", "normalizedBundleHash", "[", "i", "]", "==", "13", "{", "ok", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "ok", "{", "break", "\n", "}", "\n", "obsoleteTagTrits", "[", "0", "]", "=", "AddTrits", "(", "obsoleteTagTrits", "[", "0", "]", ",", "Trits", "{", "1", "}", ")", "\n", "}", "\n\n", "// set the computed bundle hash on each tx in the bundle", "for", "i", ":=", "range", "bundle", "{", "tx", ":=", "&", "bundle", "[", "i", "]", "\n", "if", "i", "==", "0", "{", "tx", ".", "ObsoleteTag", "=", "MustTritsToTrytes", "(", "obsoleteTagTrits", "[", "0", "]", ")", "\n", "}", "\n", "tx", ".", "Bundle", "=", "bundleHash", "\n", "}", "\n\n", "return", "bundle", ",", "nil", "\n", "}" ]
// Finalize finalizes the bundle by calculating the bundle hash and setting it on each transaction // bundle hash field.
[ "Finalize", "finalizes", "the", "bundle", "by", "calculating", "the", "bundle", "hash", "and", "setting", "it", "on", "each", "transaction", "bundle", "hash", "field", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/bundle/bundle.go#L180-L241
402
iotaledger/iota.go
bundle/bundle.go
AddTrytes
func AddTrytes(bndl Bundle, fragments []Trytes, offset int) Bundle { for i := range bndl { if i >= offset && i < offset+len(fragments) { bndl[i].SignatureMessageFragment = Pad(fragments[i-offset], 27*81) } } return bndl }
go
func AddTrytes(bndl Bundle, fragments []Trytes, offset int) Bundle { for i := range bndl { if i >= offset && i < offset+len(fragments) { bndl[i].SignatureMessageFragment = Pad(fragments[i-offset], 27*81) } } return bndl }
[ "func", "AddTrytes", "(", "bndl", "Bundle", ",", "fragments", "[", "]", "Trytes", ",", "offset", "int", ")", "Bundle", "{", "for", "i", ":=", "range", "bndl", "{", "if", "i", ">=", "offset", "&&", "i", "<", "offset", "+", "len", "(", "fragments", ")", "{", "bndl", "[", "i", "]", ".", "SignatureMessageFragment", "=", "Pad", "(", "fragments", "[", "i", "-", "offset", "]", ",", "27", "*", "81", ")", "\n", "}", "\n", "}", "\n", "return", "bndl", "\n", "}" ]
// AddTrytes adds the given fragments to the txs in the bundle starting // from the specified offset.
[ "AddTrytes", "adds", "the", "given", "fragments", "to", "the", "txs", "in", "the", "bundle", "starting", "from", "the", "specified", "offset", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/bundle/bundle.go#L245-L252
403
iotaledger/iota.go
bundle/bundle.go
ValidBundle
func ValidBundle(bundle Bundle) error { var totalSum int64 sigs := make(map[Hash][]Trytes) k := kerl.NewKerl() lastIndex := uint64(len(bundle) - 1) for i := range bundle { tx := &bundle[i] totalSum += tx.Value if tx.CurrentIndex != uint64(i) { return errors.Wrapf(ErrInvalidBundle, "expected tx at index %d to have current index %d but got %d", i, i, tx.CurrentIndex) } if tx.LastIndex != lastIndex { return errors.Wrapf(ErrInvalidBundle, "expected tx at index %d to have last index %d but got %d", i, lastIndex, tx.LastIndex) } txTrits := MustTrytesToTrits(transaction.MustTransactionToTrytes(tx)[2187 : 2187+162]) k.Absorb(txTrits) // continue if output or signature txbundle bundle if tx.Value >= 0 { continue } // here we have an input transaction (negative value) sigs[tx.Address] = append(sigs[tx.Address], tx.SignatureMessageFragment) // find the subsequent txs containing the remaining signature // message fragments for this input transaction for j := i; j < len(bundle)-1; j++ { tx2 := &bundle[j+1] // check if the tx is part of the input transaction if tx2.Address == tx.Address && tx2.Value == 0 { // append the signature message fragment sigs[tx.Address] = append(sigs[tx.Address], tx2.SignatureMessageFragment) } } } // sum of all transaction must be 0 if totalSum != 0 { return errors.Wrapf(ErrInvalidBundle, "bundle total sum should be 0 but got %d", totalSum) } bundleHashTrits, err := k.Squeeze(HashTrinarySize) if err != nil { return err } bundleHash := MustTritsToTrytes(bundleHashTrits) if bundleHash != bundle[0].Bundle { return ErrInvalidBundleHash } // validate the signatures valid, err := ValidateBundleSignatures(bundle) if err != nil { return err } if !valid { return ErrInvalidSignature } return nil }
go
func ValidBundle(bundle Bundle) error { var totalSum int64 sigs := make(map[Hash][]Trytes) k := kerl.NewKerl() lastIndex := uint64(len(bundle) - 1) for i := range bundle { tx := &bundle[i] totalSum += tx.Value if tx.CurrentIndex != uint64(i) { return errors.Wrapf(ErrInvalidBundle, "expected tx at index %d to have current index %d but got %d", i, i, tx.CurrentIndex) } if tx.LastIndex != lastIndex { return errors.Wrapf(ErrInvalidBundle, "expected tx at index %d to have last index %d but got %d", i, lastIndex, tx.LastIndex) } txTrits := MustTrytesToTrits(transaction.MustTransactionToTrytes(tx)[2187 : 2187+162]) k.Absorb(txTrits) // continue if output or signature txbundle bundle if tx.Value >= 0 { continue } // here we have an input transaction (negative value) sigs[tx.Address] = append(sigs[tx.Address], tx.SignatureMessageFragment) // find the subsequent txs containing the remaining signature // message fragments for this input transaction for j := i; j < len(bundle)-1; j++ { tx2 := &bundle[j+1] // check if the tx is part of the input transaction if tx2.Address == tx.Address && tx2.Value == 0 { // append the signature message fragment sigs[tx.Address] = append(sigs[tx.Address], tx2.SignatureMessageFragment) } } } // sum of all transaction must be 0 if totalSum != 0 { return errors.Wrapf(ErrInvalidBundle, "bundle total sum should be 0 but got %d", totalSum) } bundleHashTrits, err := k.Squeeze(HashTrinarySize) if err != nil { return err } bundleHash := MustTritsToTrytes(bundleHashTrits) if bundleHash != bundle[0].Bundle { return ErrInvalidBundleHash } // validate the signatures valid, err := ValidateBundleSignatures(bundle) if err != nil { return err } if !valid { return ErrInvalidSignature } return nil }
[ "func", "ValidBundle", "(", "bundle", "Bundle", ")", "error", "{", "var", "totalSum", "int64", "\n\n", "sigs", ":=", "make", "(", "map", "[", "Hash", "]", "[", "]", "Trytes", ")", "\n", "k", ":=", "kerl", ".", "NewKerl", "(", ")", "\n\n", "lastIndex", ":=", "uint64", "(", "len", "(", "bundle", ")", "-", "1", ")", "\n", "for", "i", ":=", "range", "bundle", "{", "tx", ":=", "&", "bundle", "[", "i", "]", "\n", "totalSum", "+=", "tx", ".", "Value", "\n\n", "if", "tx", ".", "CurrentIndex", "!=", "uint64", "(", "i", ")", "{", "return", "errors", ".", "Wrapf", "(", "ErrInvalidBundle", ",", "\"", "\"", ",", "i", ",", "i", ",", "tx", ".", "CurrentIndex", ")", "\n", "}", "\n", "if", "tx", ".", "LastIndex", "!=", "lastIndex", "{", "return", "errors", ".", "Wrapf", "(", "ErrInvalidBundle", ",", "\"", "\"", ",", "i", ",", "lastIndex", ",", "tx", ".", "LastIndex", ")", "\n", "}", "\n\n", "txTrits", ":=", "MustTrytesToTrits", "(", "transaction", ".", "MustTransactionToTrytes", "(", "tx", ")", "[", "2187", ":", "2187", "+", "162", "]", ")", "\n", "k", ".", "Absorb", "(", "txTrits", ")", "\n\n", "// continue if output or signature txbundle bundle", "if", "tx", ".", "Value", ">=", "0", "{", "continue", "\n", "}", "\n\n", "// here we have an input transaction (negative value)", "sigs", "[", "tx", ".", "Address", "]", "=", "append", "(", "sigs", "[", "tx", ".", "Address", "]", ",", "tx", ".", "SignatureMessageFragment", ")", "\n\n", "// find the subsequent txs containing the remaining signature", "// message fragments for this input transaction", "for", "j", ":=", "i", ";", "j", "<", "len", "(", "bundle", ")", "-", "1", ";", "j", "++", "{", "tx2", ":=", "&", "bundle", "[", "j", "+", "1", "]", "\n\n", "// check if the tx is part of the input transaction", "if", "tx2", ".", "Address", "==", "tx", ".", "Address", "&&", "tx2", ".", "Value", "==", "0", "{", "// append the signature message fragment", "sigs", "[", "tx", ".", "Address", "]", "=", "append", "(", "sigs", "[", "tx", ".", "Address", "]", ",", "tx2", ".", "SignatureMessageFragment", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// sum of all transaction must be 0", "if", "totalSum", "!=", "0", "{", "return", "errors", ".", "Wrapf", "(", "ErrInvalidBundle", ",", "\"", "\"", ",", "totalSum", ")", "\n", "}", "\n\n", "bundleHashTrits", ",", "err", ":=", "k", ".", "Squeeze", "(", "HashTrinarySize", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bundleHash", ":=", "MustTritsToTrytes", "(", "bundleHashTrits", ")", "\n\n", "if", "bundleHash", "!=", "bundle", "[", "0", "]", ".", "Bundle", "{", "return", "ErrInvalidBundleHash", "\n", "}", "\n\n", "// validate the signatures", "valid", ",", "err", ":=", "ValidateBundleSignatures", "(", "bundle", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "valid", "{", "return", "ErrInvalidSignature", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ValidBundle checks if a bundle is syntactically valid. // Validates signatures and overall structure.
[ "ValidBundle", "checks", "if", "a", "bundle", "is", "syntactically", "valid", ".", "Validates", "signatures", "and", "overall", "structure", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/bundle/bundle.go#L292-L361
404
iotaledger/iota.go
bundle/bundle.go
GroupTransactionsIntoBundles
func GroupTransactionsIntoBundles(txs transaction.Transactions) Bundles { bundles := Bundles{} for i := range txs { tx := &txs[i] if tx.CurrentIndex != 0 { continue } bundle := Bundle{*tx} lastIndex := int(tx.LastIndex) current := tx for x := 1; x <= lastIndex; x++ { // get all txs belonging into this bundle found := false for j := range txs { if current.Bundle != txs[j].Bundle || txs[j].CurrentIndex != current.CurrentIndex+1 || current.TrunkTransaction != txs[j].Hash { continue } found = true bundle = append(bundle, txs[j]) current = &txs[j] break } if !found { break } } bundles = append(bundles, bundle) } return bundles }
go
func GroupTransactionsIntoBundles(txs transaction.Transactions) Bundles { bundles := Bundles{} for i := range txs { tx := &txs[i] if tx.CurrentIndex != 0 { continue } bundle := Bundle{*tx} lastIndex := int(tx.LastIndex) current := tx for x := 1; x <= lastIndex; x++ { // get all txs belonging into this bundle found := false for j := range txs { if current.Bundle != txs[j].Bundle || txs[j].CurrentIndex != current.CurrentIndex+1 || current.TrunkTransaction != txs[j].Hash { continue } found = true bundle = append(bundle, txs[j]) current = &txs[j] break } if !found { break } } bundles = append(bundles, bundle) } return bundles }
[ "func", "GroupTransactionsIntoBundles", "(", "txs", "transaction", ".", "Transactions", ")", "Bundles", "{", "bundles", ":=", "Bundles", "{", "}", "\n\n", "for", "i", ":=", "range", "txs", "{", "tx", ":=", "&", "txs", "[", "i", "]", "\n", "if", "tx", ".", "CurrentIndex", "!=", "0", "{", "continue", "\n", "}", "\n\n", "bundle", ":=", "Bundle", "{", "*", "tx", "}", "\n", "lastIndex", ":=", "int", "(", "tx", ".", "LastIndex", ")", "\n", "current", ":=", "tx", "\n", "for", "x", ":=", "1", ";", "x", "<=", "lastIndex", ";", "x", "++", "{", "// get all txs belonging into this bundle", "found", ":=", "false", "\n", "for", "j", ":=", "range", "txs", "{", "if", "current", ".", "Bundle", "!=", "txs", "[", "j", "]", ".", "Bundle", "||", "txs", "[", "j", "]", ".", "CurrentIndex", "!=", "current", ".", "CurrentIndex", "+", "1", "||", "current", ".", "TrunkTransaction", "!=", "txs", "[", "j", "]", ".", "Hash", "{", "continue", "\n", "}", "\n", "found", "=", "true", "\n", "bundle", "=", "append", "(", "bundle", ",", "txs", "[", "j", "]", ")", "\n", "current", "=", "&", "txs", "[", "j", "]", "\n", "break", "\n", "}", "\n", "if", "!", "found", "{", "break", "\n", "}", "\n", "}", "\n", "bundles", "=", "append", "(", "bundles", ",", "bundle", ")", "\n", "}", "\n\n", "return", "bundles", "\n", "}" ]
// GroupTransactionsIntoBundles groups the given transactions into groups of bundles. // Note that the same bundle can exist in the return slice multiple times, though they // are reattachments of the same transfer.
[ "GroupTransactionsIntoBundles", "groups", "the", "given", "transactions", "into", "groups", "of", "bundles", ".", "Note", "that", "the", "same", "bundle", "can", "exist", "in", "the", "return", "slice", "multiple", "times", "though", "they", "are", "reattachments", "of", "the", "same", "transfer", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/bundle/bundle.go#L366-L400
405
iotaledger/iota.go
bundle/bundle.go
TailTransactionHash
func TailTransactionHash(bndl Bundle) Hash { if bndl == nil || len(bndl) == 0 { return "" } for i := range bndl { tx := &bndl[i] if tx.CurrentIndex != 0 { continue } if len(tx.Hash) > 0 { return tx.Hash } return transaction.TransactionHash(tx) } return "" }
go
func TailTransactionHash(bndl Bundle) Hash { if bndl == nil || len(bndl) == 0 { return "" } for i := range bndl { tx := &bndl[i] if tx.CurrentIndex != 0 { continue } if len(tx.Hash) > 0 { return tx.Hash } return transaction.TransactionHash(tx) } return "" }
[ "func", "TailTransactionHash", "(", "bndl", "Bundle", ")", "Hash", "{", "if", "bndl", "==", "nil", "||", "len", "(", "bndl", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "for", "i", ":=", "range", "bndl", "{", "tx", ":=", "&", "bndl", "[", "i", "]", "\n", "if", "tx", ".", "CurrentIndex", "!=", "0", "{", "continue", "\n", "}", "\n", "if", "len", "(", "tx", ".", "Hash", ")", ">", "0", "{", "return", "tx", ".", "Hash", "\n", "}", "\n", "return", "transaction", ".", "TransactionHash", "(", "tx", ")", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// TailTransactionHash returns the tail transaction's hash.
[ "TailTransactionHash", "returns", "the", "tail", "transaction", "s", "hash", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/bundle/bundle.go#L403-L418
406
iotaledger/iota.go
api/http.go
NewHTTPClient
func NewHTTPClient(settings interface{}) (Provider, error) { httpClient := &httpclient{} if err := httpClient.SetSettings(settings); err != nil { return nil, err } return httpClient, nil }
go
func NewHTTPClient(settings interface{}) (Provider, error) { httpClient := &httpclient{} if err := httpClient.SetSettings(settings); err != nil { return nil, err } return httpClient, nil }
[ "func", "NewHTTPClient", "(", "settings", "interface", "{", "}", ")", "(", "Provider", ",", "error", ")", "{", "httpClient", ":=", "&", "httpclient", "{", "}", "\n", "if", "err", ":=", "httpClient", ".", "SetSettings", "(", "settings", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "httpClient", ",", "nil", "\n", "}" ]
// NewHTTPClient creates a new Http Provider.
[ "NewHTTPClient", "creates", "a", "new", "Http", "Provider", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/api/http.go#L18-L24
407
iotaledger/iota.go
trinary/trinary.go
ValidTrits
func ValidTrits(t Trits) error { for i, tt := range t { if valid := ValidTrit(tt); !valid { return errors.Wrapf(ErrInvalidTrit, "at index %d", i) } } return nil }
go
func ValidTrits(t Trits) error { for i, tt := range t { if valid := ValidTrit(tt); !valid { return errors.Wrapf(ErrInvalidTrit, "at index %d", i) } } return nil }
[ "func", "ValidTrits", "(", "t", "Trits", ")", "error", "{", "for", "i", ",", "tt", ":=", "range", "t", "{", "if", "valid", ":=", "ValidTrit", "(", "tt", ")", ";", "!", "valid", "{", "return", "errors", ".", "Wrapf", "(", "ErrInvalidTrit", ",", "\"", "\"", ",", "i", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidTrits returns true if t is valid trits.
[ "ValidTrits", "returns", "true", "if", "t", "is", "valid", "trits", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L57-L64
408
iotaledger/iota.go
trinary/trinary.go
NewTrits
func NewTrits(t []int8) (Trits, error) { err := ValidTrits(t) return t, err }
go
func NewTrits(t []int8) (Trits, error) { err := ValidTrits(t) return t, err }
[ "func", "NewTrits", "(", "t", "[", "]", "int8", ")", "(", "Trits", ",", "error", ")", "{", "err", ":=", "ValidTrits", "(", "t", ")", "\n", "return", "t", ",", "err", "\n", "}" ]
// NewTrits casts Trits and checks its validity.
[ "NewTrits", "casts", "Trits", "and", "checks", "its", "validity", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L67-L70
409
iotaledger/iota.go
trinary/trinary.go
TritsEqual
func TritsEqual(a Trits, b Trits) (bool, error) { if err := ValidTrits(a); err != nil { return false, err } if err := ValidTrits(b); err != nil { return false, err } if len(a) != len(b) { return false, nil } for i := range a { if a[i] != b[i] { return false, nil } } return true, nil }
go
func TritsEqual(a Trits, b Trits) (bool, error) { if err := ValidTrits(a); err != nil { return false, err } if err := ValidTrits(b); err != nil { return false, err } if len(a) != len(b) { return false, nil } for i := range a { if a[i] != b[i] { return false, nil } } return true, nil }
[ "func", "TritsEqual", "(", "a", "Trits", ",", "b", "Trits", ")", "(", "bool", ",", "error", ")", "{", "if", "err", ":=", "ValidTrits", "(", "a", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "err", ":=", "ValidTrits", "(", "b", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "for", "i", ":=", "range", "a", "{", "if", "a", "[", "i", "]", "!=", "b", "[", "i", "]", "{", "return", "false", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// TritsEqual returns true if t and b are equal Trits.
[ "TritsEqual", "returns", "true", "if", "t", "and", "b", "are", "equal", "Trits", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L73-L91
410
iotaledger/iota.go
trinary/trinary.go
MustAbsInt64
func MustAbsInt64(n int64) int64 { if n == -1<<63 { panic("value out of range") } y := n >> 63 // y ← x ⟫ 63 return (n ^ y) - y // (x ⨁ y) - y }
go
func MustAbsInt64(n int64) int64 { if n == -1<<63 { panic("value out of range") } y := n >> 63 // y ← x ⟫ 63 return (n ^ y) - y // (x ⨁ y) - y }
[ "func", "MustAbsInt64", "(", "n", "int64", ")", "int64", "{", "if", "n", "==", "-", "1", "<<", "63", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "y", ":=", "n", ">>", "63", "// y ← x ⟫ 63", "\n", "return", "(", "n", "^", "y", ")", "-", "y", "// (x ⨁ y) - y", "\n", "}" ]
// MustAbsInt64 returns the absolute value of an int64.
[ "MustAbsInt64", "returns", "the", "absolute", "value", "of", "an", "int64", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L94-L100
411
iotaledger/iota.go
trinary/trinary.go
MinTrits
func MinTrits(value int64) uint64 { var num uint64 = 1 var vp uint64 = 1 valueAbs := uint64(MustAbsInt64(value)) for uint64(valueAbs) > vp { vp = vp*uint64(Radix) + 1 num++ } return num }
go
func MinTrits(value int64) uint64 { var num uint64 = 1 var vp uint64 = 1 valueAbs := uint64(MustAbsInt64(value)) for uint64(valueAbs) > vp { vp = vp*uint64(Radix) + 1 num++ } return num }
[ "func", "MinTrits", "(", "value", "int64", ")", "uint64", "{", "var", "num", "uint64", "=", "1", "\n", "var", "vp", "uint64", "=", "1", "\n\n", "valueAbs", ":=", "uint64", "(", "MustAbsInt64", "(", "value", ")", ")", "\n\n", "for", "uint64", "(", "valueAbs", ")", ">", "vp", "{", "vp", "=", "vp", "*", "uint64", "(", "Radix", ")", "+", "1", "\n", "num", "++", "\n", "}", "\n", "return", "num", "\n", "}" ]
// MinTrits returns the length of trits needed to encode the value.
[ "MinTrits", "returns", "the", "length", "of", "trits", "needed", "to", "encode", "the", "value", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L111-L122
412
iotaledger/iota.go
trinary/trinary.go
EncodedLength
func EncodedLength(value int64) uint64 { if value == 0 { return uint64(len(encodedZero)) } length := nearestGreaterMultipleOfThree(MinTrits(value)) // trits length + encoding length return length + MinTrits((1<<(length/uint64(Radix)))-1) }
go
func EncodedLength(value int64) uint64 { if value == 0 { return uint64(len(encodedZero)) } length := nearestGreaterMultipleOfThree(MinTrits(value)) // trits length + encoding length return length + MinTrits((1<<(length/uint64(Radix)))-1) }
[ "func", "EncodedLength", "(", "value", "int64", ")", "uint64", "{", "if", "value", "==", "0", "{", "return", "uint64", "(", "len", "(", "encodedZero", ")", ")", "\n", "}", "\n", "length", ":=", "nearestGreaterMultipleOfThree", "(", "MinTrits", "(", "value", ")", ")", "\n\n", "// trits length + encoding length", "return", "length", "+", "MinTrits", "(", "(", "1", "<<", "(", "length", "/", "uint64", "(", "Radix", ")", ")", ")", "-", "1", ")", "\n", "}" ]
// EncodedLength returns the length of trits needed to encode the value + encoding information.
[ "EncodedLength", "returns", "the", "length", "of", "trits", "needed", "to", "encode", "the", "value", "+", "encoding", "information", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L125-L133
413
iotaledger/iota.go
trinary/trinary.go
IntToTrytes
func IntToTrytes(value int64, trytesCnt int) Trytes { remainder := value if value < 0 { remainder = -value } var t Trytes for tryte := 0; tryte < trytesCnt; tryte++ { idx := remainder % 27 remainder /= 27 if idx > 13 { remainder += 1 } if value < 0 && idx != 0 { idx = 27 - idx } t += string(TryteAlphabet[idx]) } return t }
go
func IntToTrytes(value int64, trytesCnt int) Trytes { remainder := value if value < 0 { remainder = -value } var t Trytes for tryte := 0; tryte < trytesCnt; tryte++ { idx := remainder % 27 remainder /= 27 if idx > 13 { remainder += 1 } if value < 0 && idx != 0 { idx = 27 - idx } t += string(TryteAlphabet[idx]) } return t }
[ "func", "IntToTrytes", "(", "value", "int64", ",", "trytesCnt", "int", ")", "Trytes", "{", "remainder", ":=", "value", "\n", "if", "value", "<", "0", "{", "remainder", "=", "-", "value", "\n", "}", "\n\n", "var", "t", "Trytes", "\n\n", "for", "tryte", ":=", "0", ";", "tryte", "<", "trytesCnt", ";", "tryte", "++", "{", "idx", ":=", "remainder", "%", "27", "\n", "remainder", "/=", "27", "\n\n", "if", "idx", ">", "13", "{", "remainder", "+=", "1", "\n", "}", "\n\n", "if", "value", "<", "0", "&&", "idx", "!=", "0", "{", "idx", "=", "27", "-", "idx", "\n", "}", "\n\n", "t", "+=", "string", "(", "TryteAlphabet", "[", "idx", "]", ")", "\n", "}", "\n", "return", "t", "\n", "}" ]
// IntToTrytes converts int64 to a slice of trytes.
[ "IntToTrytes", "converts", "int64", "to", "a", "slice", "of", "trytes", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L136-L159
414
iotaledger/iota.go
trinary/trinary.go
TrytesToInt
func TrytesToInt(t Trytes) int64 { var val int64 for i := len(t) - 1; i >= 0; i-- { idx := strings.Index(TryteAlphabet, string(t[i])) if idx > 13 { idx = idx - 27 } val = val*27 + int64(idx) } return val }
go
func TrytesToInt(t Trytes) int64 { var val int64 for i := len(t) - 1; i >= 0; i-- { idx := strings.Index(TryteAlphabet, string(t[i])) if idx > 13 { idx = idx - 27 } val = val*27 + int64(idx) } return val }
[ "func", "TrytesToInt", "(", "t", "Trytes", ")", "int64", "{", "var", "val", "int64", "\n\n", "for", "i", ":=", "len", "(", "t", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "idx", ":=", "strings", ".", "Index", "(", "TryteAlphabet", ",", "string", "(", "t", "[", "i", "]", ")", ")", "\n", "if", "idx", ">", "13", "{", "idx", "=", "idx", "-", "27", "\n", "}", "\n", "val", "=", "val", "*", "27", "+", "int64", "(", "idx", ")", "\n", "}", "\n", "return", "val", "\n", "}" ]
// TrytesToInt converts a slice of trytes to int64.
[ "TrytesToInt", "converts", "a", "slice", "of", "trytes", "to", "int64", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L162-L173
415
iotaledger/iota.go
trinary/trinary.go
IntToTrits
func IntToTrits(value int64) Trits { if value == 0 { return Trits{0} } negative := value < 0 size := MinTrits(value) valueAbs := MustAbsInt64(value) t := make(Trits, size) for i := 0; i < int(size); i++ { if valueAbs == 0 { break } trit := int8((valueAbs+1)%(TrinaryRadix) - 1) if negative { trit = -trit } t[i] = trit valueAbs++ valueAbs /= TrinaryRadix } return t }
go
func IntToTrits(value int64) Trits { if value == 0 { return Trits{0} } negative := value < 0 size := MinTrits(value) valueAbs := MustAbsInt64(value) t := make(Trits, size) for i := 0; i < int(size); i++ { if valueAbs == 0 { break } trit := int8((valueAbs+1)%(TrinaryRadix) - 1) if negative { trit = -trit } t[i] = trit valueAbs++ valueAbs /= TrinaryRadix } return t }
[ "func", "IntToTrits", "(", "value", "int64", ")", "Trits", "{", "if", "value", "==", "0", "{", "return", "Trits", "{", "0", "}", "\n", "}", "\n\n", "negative", ":=", "value", "<", "0", "\n", "size", ":=", "MinTrits", "(", "value", ")", "\n", "valueAbs", ":=", "MustAbsInt64", "(", "value", ")", "\n\n", "t", ":=", "make", "(", "Trits", ",", "size", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "size", ")", ";", "i", "++", "{", "if", "valueAbs", "==", "0", "{", "break", "\n", "}", "\n", "trit", ":=", "int8", "(", "(", "valueAbs", "+", "1", ")", "%", "(", "TrinaryRadix", ")", "-", "1", ")", "\n", "if", "negative", "{", "trit", "=", "-", "trit", "\n", "}", "\n", "t", "[", "i", "]", "=", "trit", "\n", "valueAbs", "++", "\n", "valueAbs", "/=", "TrinaryRadix", "\n", "}", "\n\n", "return", "t", "\n", "}" ]
// IntToTrits converts int64 to a slice of trits.
[ "IntToTrits", "converts", "int64", "to", "a", "slice", "of", "trits", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L176-L201
416
iotaledger/iota.go
trinary/trinary.go
TritsToInt
func TritsToInt(t Trits) int64 { var val int64 for i := len(t) - 1; i >= 0; i-- { val = val*3 + int64(t[i]) } return val }
go
func TritsToInt(t Trits) int64 { var val int64 for i := len(t) - 1; i >= 0; i-- { val = val*3 + int64(t[i]) } return val }
[ "func", "TritsToInt", "(", "t", "Trits", ")", "int64", "{", "var", "val", "int64", "\n", "for", "i", ":=", "len", "(", "t", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "val", "=", "val", "*", "3", "+", "int64", "(", "t", "[", "i", "]", ")", "\n", "}", "\n", "return", "val", "\n", "}" ]
// TritsToInt converts a slice of trits into an integer and assumes little-endian notation.
[ "TritsToInt", "converts", "a", "slice", "of", "trits", "into", "an", "integer", "and", "assumes", "little", "-", "endian", "notation", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L204-L210
417
iotaledger/iota.go
trinary/trinary.go
EncodeInt64
func EncodeInt64(value int64) (t Trits, size uint64, err error) { size = EncodedLength(value) if value == 0 { return encodedZero, size, nil } var encoding int64 = 0 index := 0 length := nearestGreaterMultipleOfThree(MinTrits(MustAbsInt64(value))) t = make(Trits, size) copy(t, IntToTrits(value)) for i := 0; i < int(length)-TrinaryRadix; i += TrinaryRadix { if TritsToInt(t[i:i+TrinaryRadix]) >= 0 { encoding |= 1 << uint(index) for j := 0; j < TrinaryRadix; j++ { t[i+j] = -t[i+j] } } index++ } if TritsToInt(t[length-TrinaryRadix:length]) <= 0 { encoding |= 1 << uint(index) for i := 1; i < TrinaryRadix+1; i++ { t[int(length)-i] = -t[int(length)-i] } } copy(t[length:], IntToTrits(encoding)) return t, size, nil }
go
func EncodeInt64(value int64) (t Trits, size uint64, err error) { size = EncodedLength(value) if value == 0 { return encodedZero, size, nil } var encoding int64 = 0 index := 0 length := nearestGreaterMultipleOfThree(MinTrits(MustAbsInt64(value))) t = make(Trits, size) copy(t, IntToTrits(value)) for i := 0; i < int(length)-TrinaryRadix; i += TrinaryRadix { if TritsToInt(t[i:i+TrinaryRadix]) >= 0 { encoding |= 1 << uint(index) for j := 0; j < TrinaryRadix; j++ { t[i+j] = -t[i+j] } } index++ } if TritsToInt(t[length-TrinaryRadix:length]) <= 0 { encoding |= 1 << uint(index) for i := 1; i < TrinaryRadix+1; i++ { t[int(length)-i] = -t[int(length)-i] } } copy(t[length:], IntToTrits(encoding)) return t, size, nil }
[ "func", "EncodeInt64", "(", "value", "int64", ")", "(", "t", "Trits", ",", "size", "uint64", ",", "err", "error", ")", "{", "size", "=", "EncodedLength", "(", "value", ")", "\n\n", "if", "value", "==", "0", "{", "return", "encodedZero", ",", "size", ",", "nil", "\n", "}", "\n\n", "var", "encoding", "int64", "=", "0", "\n", "index", ":=", "0", "\n", "length", ":=", "nearestGreaterMultipleOfThree", "(", "MinTrits", "(", "MustAbsInt64", "(", "value", ")", ")", ")", "\n", "t", "=", "make", "(", "Trits", ",", "size", ")", "\n", "copy", "(", "t", ",", "IntToTrits", "(", "value", ")", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "length", ")", "-", "TrinaryRadix", ";", "i", "+=", "TrinaryRadix", "{", "if", "TritsToInt", "(", "t", "[", "i", ":", "i", "+", "TrinaryRadix", "]", ")", ">=", "0", "{", "encoding", "|=", "1", "<<", "uint", "(", "index", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "TrinaryRadix", ";", "j", "++", "{", "t", "[", "i", "+", "j", "]", "=", "-", "t", "[", "i", "+", "j", "]", "\n", "}", "\n", "}", "\n", "index", "++", "\n", "}", "\n\n", "if", "TritsToInt", "(", "t", "[", "length", "-", "TrinaryRadix", ":", "length", "]", ")", "<=", "0", "{", "encoding", "|=", "1", "<<", "uint", "(", "index", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "TrinaryRadix", "+", "1", ";", "i", "++", "{", "t", "[", "int", "(", "length", ")", "-", "i", "]", "=", "-", "t", "[", "int", "(", "length", ")", "-", "i", "]", "\n", "}", "\n", "}", "\n\n", "copy", "(", "t", "[", "length", ":", "]", ",", "IntToTrits", "(", "encoding", ")", ")", "\n", "return", "t", ",", "size", ",", "nil", "\n", "}" ]
// EncodeInt64 encodes an int64 as a slice of trits with encoding information.
[ "EncodeInt64", "encodes", "an", "int64", "as", "a", "slice", "of", "trits", "with", "encoding", "information", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L213-L245
418
iotaledger/iota.go
trinary/trinary.go
DecodeInt64
func DecodeInt64(t Trits) (value int64, size uint64, err error) { numTrits := uint64(len(t)) equal, err := TritsEqual(t[0:4], encodedZero) if err != nil { return 0, 0, err } if equal { return 0, EncodedLength(0), nil } value = 0 var encodingStart uint64 = 0 for (encodingStart < numTrits) && (TritsToInt(t[encodingStart:encodingStart+TrinaryRadix]) <= 0) { encodingStart += TrinaryRadix } if encodingStart >= numTrits { return 0, 0, errors.New("encodingStart > numTrits") } encodingStart += TrinaryRadix encodingLength := MinTrits((1 << (encodingStart / TrinaryRadix)) - 1) encoding := TritsToInt(t[encodingStart : encodingStart+encodingLength]) // Bound checking for the lookup table if encodingStart/TrinaryRadix > 13 { return 0, 0, errors.New("encodingStart/TrinaryRadix > 13") } for i := 0; i < int(encodingStart/TrinaryRadix); i++ { tryteValue := TritsToInt(t[i*TrinaryRadix : (i*TrinaryRadix)+TrinaryRadix]) if ((encoding >> uint(i)) & 1) == 1 { tryteValue = -tryteValue } value += Pow27LUT[i] * tryteValue } return value, encodingStart + encodingLength, nil }
go
func DecodeInt64(t Trits) (value int64, size uint64, err error) { numTrits := uint64(len(t)) equal, err := TritsEqual(t[0:4], encodedZero) if err != nil { return 0, 0, err } if equal { return 0, EncodedLength(0), nil } value = 0 var encodingStart uint64 = 0 for (encodingStart < numTrits) && (TritsToInt(t[encodingStart:encodingStart+TrinaryRadix]) <= 0) { encodingStart += TrinaryRadix } if encodingStart >= numTrits { return 0, 0, errors.New("encodingStart > numTrits") } encodingStart += TrinaryRadix encodingLength := MinTrits((1 << (encodingStart / TrinaryRadix)) - 1) encoding := TritsToInt(t[encodingStart : encodingStart+encodingLength]) // Bound checking for the lookup table if encodingStart/TrinaryRadix > 13 { return 0, 0, errors.New("encodingStart/TrinaryRadix > 13") } for i := 0; i < int(encodingStart/TrinaryRadix); i++ { tryteValue := TritsToInt(t[i*TrinaryRadix : (i*TrinaryRadix)+TrinaryRadix]) if ((encoding >> uint(i)) & 1) == 1 { tryteValue = -tryteValue } value += Pow27LUT[i] * tryteValue } return value, encodingStart + encodingLength, nil }
[ "func", "DecodeInt64", "(", "t", "Trits", ")", "(", "value", "int64", ",", "size", "uint64", ",", "err", "error", ")", "{", "numTrits", ":=", "uint64", "(", "len", "(", "t", ")", ")", "\n\n", "equal", ",", "err", ":=", "TritsEqual", "(", "t", "[", "0", ":", "4", "]", ",", "encodedZero", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n\n", "if", "equal", "{", "return", "0", ",", "EncodedLength", "(", "0", ")", ",", "nil", "\n", "}", "\n\n", "value", "=", "0", "\n", "var", "encodingStart", "uint64", "=", "0", "\n\n", "for", "(", "encodingStart", "<", "numTrits", ")", "&&", "(", "TritsToInt", "(", "t", "[", "encodingStart", ":", "encodingStart", "+", "TrinaryRadix", "]", ")", "<=", "0", ")", "{", "encodingStart", "+=", "TrinaryRadix", "\n", "}", "\n\n", "if", "encodingStart", ">=", "numTrits", "{", "return", "0", ",", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "encodingStart", "+=", "TrinaryRadix", "\n", "encodingLength", ":=", "MinTrits", "(", "(", "1", "<<", "(", "encodingStart", "/", "TrinaryRadix", ")", ")", "-", "1", ")", "\n", "encoding", ":=", "TritsToInt", "(", "t", "[", "encodingStart", ":", "encodingStart", "+", "encodingLength", "]", ")", "\n\n", "// Bound checking for the lookup table", "if", "encodingStart", "/", "TrinaryRadix", ">", "13", "{", "return", "0", ",", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "encodingStart", "/", "TrinaryRadix", ")", ";", "i", "++", "{", "tryteValue", ":=", "TritsToInt", "(", "t", "[", "i", "*", "TrinaryRadix", ":", "(", "i", "*", "TrinaryRadix", ")", "+", "TrinaryRadix", "]", ")", "\n\n", "if", "(", "(", "encoding", ">>", "uint", "(", "i", ")", ")", "&", "1", ")", "==", "1", "{", "tryteValue", "=", "-", "tryteValue", "\n", "}", "\n", "value", "+=", "Pow27LUT", "[", "i", "]", "*", "tryteValue", "\n", "}", "\n\n", "return", "value", ",", "encodingStart", "+", "encodingLength", ",", "nil", "\n", "}" ]
// DecodeInt64 decodes a slice of trits with encoding information as an int64.
[ "DecodeInt64", "decodes", "a", "slice", "of", "trits", "with", "encoding", "information", "as", "an", "int64", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L248-L290
419
iotaledger/iota.go
trinary/trinary.go
TrailingZeros
func TrailingZeros(trits Trits) int64 { z := int64(0) for i := len(trits) - 1; i >= 0 && trits[i] == 0; i-- { z++ } return z }
go
func TrailingZeros(trits Trits) int64 { z := int64(0) for i := len(trits) - 1; i >= 0 && trits[i] == 0; i-- { z++ } return z }
[ "func", "TrailingZeros", "(", "trits", "Trits", ")", "int64", "{", "z", ":=", "int64", "(", "0", ")", "\n", "for", "i", ":=", "len", "(", "trits", ")", "-", "1", ";", "i", ">=", "0", "&&", "trits", "[", "i", "]", "==", "0", ";", "i", "--", "{", "z", "++", "\n", "}", "\n", "return", "z", "\n", "}" ]
// TrailingZeros returns the number of trailing zeros of the given trits.
[ "TrailingZeros", "returns", "the", "number", "of", "trailing", "zeros", "of", "the", "given", "trits", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L301-L307
420
iotaledger/iota.go
trinary/trinary.go
BytesToTrytes
func BytesToTrytes(bytes []byte, numTrytes ...int) (Trytes, error) { numTrits := []int{} if len(numTrytes) > 0 { numTrits = append(numTrits, numTrytes[0]*3) } trits, err := BytesToTrits(bytes, numTrits...) if err != nil { return "", err } trits = PadTrits(trits, int(nearestGreaterMultipleOfThree(uint64(len(trits))))) return TritsToTrytes(trits) }
go
func BytesToTrytes(bytes []byte, numTrytes ...int) (Trytes, error) { numTrits := []int{} if len(numTrytes) > 0 { numTrits = append(numTrits, numTrytes[0]*3) } trits, err := BytesToTrits(bytes, numTrits...) if err != nil { return "", err } trits = PadTrits(trits, int(nearestGreaterMultipleOfThree(uint64(len(trits))))) return TritsToTrytes(trits) }
[ "func", "BytesToTrytes", "(", "bytes", "[", "]", "byte", ",", "numTrytes", "...", "int", ")", "(", "Trytes", ",", "error", ")", "{", "numTrits", ":=", "[", "]", "int", "{", "}", "\n", "if", "len", "(", "numTrytes", ")", ">", "0", "{", "numTrits", "=", "append", "(", "numTrits", ",", "numTrytes", "[", "0", "]", "*", "3", ")", "\n", "}", "\n\n", "trits", ",", "err", ":=", "BytesToTrits", "(", "bytes", ",", "numTrits", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "trits", "=", "PadTrits", "(", "trits", ",", "int", "(", "nearestGreaterMultipleOfThree", "(", "uint64", "(", "len", "(", "trits", ")", ")", ")", ")", ")", "\n", "return", "TritsToTrytes", "(", "trits", ")", "\n", "}" ]
// BytesToTrytes converts bytes to Trytes. Returns an error if the bytes slice is not 48 in length.
[ "BytesToTrytes", "converts", "bytes", "to", "Trytes", ".", "Returns", "an", "error", "if", "the", "bytes", "slice", "is", "not", "48", "in", "length", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L359-L372
421
iotaledger/iota.go
trinary/trinary.go
MustBytesToTrytes
func MustBytesToTrytes(bytes []byte, numTrytes ...int) Trytes { trytes, err := BytesToTrytes(bytes, numTrytes...) if err != nil { panic(err) } return trytes }
go
func MustBytesToTrytes(bytes []byte, numTrytes ...int) Trytes { trytes, err := BytesToTrytes(bytes, numTrytes...) if err != nil { panic(err) } return trytes }
[ "func", "MustBytesToTrytes", "(", "bytes", "[", "]", "byte", ",", "numTrytes", "...", "int", ")", "Trytes", "{", "trytes", ",", "err", ":=", "BytesToTrytes", "(", "bytes", ",", "numTrytes", "...", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "trytes", "\n", "}" ]
// MustBytesToTrytes converts bytes to Trytes.
[ "MustBytesToTrytes", "converts", "bytes", "to", "Trytes", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L375-L381
422
iotaledger/iota.go
trinary/trinary.go
BytesToTrits
func BytesToTrits(bytes []byte, numTrits ...int) (trits Trits, err error) { bytesLength := len(bytes) tritsLength := bytesLength * NumberOfTritsInAByte if len(numTrits) > 0 { tritsLength = numTrits[0] minTritLength := (bytesLength-1)*NumberOfTritsInAByte + 1 maxTritLength := bytesLength * NumberOfTritsInAByte if tritsLength < minTritLength || tritsLength > maxTritLength { return nil, errors.Wrapf(ErrInvalidTritsLength, "must be %d-%d in size", minTritLength, maxTritLength) } } trits = make(Trits, tritsLength) for byteNum := 0; byteNum < bytesLength; byteNum++ { value := int8(bytes[byteNum]) tritOffset := byteNum * NumberOfTritsInAByte for tritNum := NumberOfTritsInAByte - 1; tritNum >= 0; tritNum-- { var trit int8 = 0 tritIdx := tritOffset + tritNum if tritIdx < tritsLength { byteRadixHalf := byteRadix[tritNum] >> 1 if value > byteRadixHalf { value -= byteRadix[tritNum] trit = 1 } else if value < (-byteRadixHalf) { value += byteRadix[tritNum] trit = -1 } trits[tritIdx] = trit } } } return trits, nil }
go
func BytesToTrits(bytes []byte, numTrits ...int) (trits Trits, err error) { bytesLength := len(bytes) tritsLength := bytesLength * NumberOfTritsInAByte if len(numTrits) > 0 { tritsLength = numTrits[0] minTritLength := (bytesLength-1)*NumberOfTritsInAByte + 1 maxTritLength := bytesLength * NumberOfTritsInAByte if tritsLength < minTritLength || tritsLength > maxTritLength { return nil, errors.Wrapf(ErrInvalidTritsLength, "must be %d-%d in size", minTritLength, maxTritLength) } } trits = make(Trits, tritsLength) for byteNum := 0; byteNum < bytesLength; byteNum++ { value := int8(bytes[byteNum]) tritOffset := byteNum * NumberOfTritsInAByte for tritNum := NumberOfTritsInAByte - 1; tritNum >= 0; tritNum-- { var trit int8 = 0 tritIdx := tritOffset + tritNum if tritIdx < tritsLength { byteRadixHalf := byteRadix[tritNum] >> 1 if value > byteRadixHalf { value -= byteRadix[tritNum] trit = 1 } else if value < (-byteRadixHalf) { value += byteRadix[tritNum] trit = -1 } trits[tritIdx] = trit } } } return trits, nil }
[ "func", "BytesToTrits", "(", "bytes", "[", "]", "byte", ",", "numTrits", "...", "int", ")", "(", "trits", "Trits", ",", "err", "error", ")", "{", "bytesLength", ":=", "len", "(", "bytes", ")", "\n", "tritsLength", ":=", "bytesLength", "*", "NumberOfTritsInAByte", "\n\n", "if", "len", "(", "numTrits", ")", ">", "0", "{", "tritsLength", "=", "numTrits", "[", "0", "]", "\n\n", "minTritLength", ":=", "(", "bytesLength", "-", "1", ")", "*", "NumberOfTritsInAByte", "+", "1", "\n", "maxTritLength", ":=", "bytesLength", "*", "NumberOfTritsInAByte", "\n", "if", "tritsLength", "<", "minTritLength", "||", "tritsLength", ">", "maxTritLength", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "ErrInvalidTritsLength", ",", "\"", "\"", ",", "minTritLength", ",", "maxTritLength", ")", "\n", "}", "\n", "}", "\n\n", "trits", "=", "make", "(", "Trits", ",", "tritsLength", ")", "\n\n", "for", "byteNum", ":=", "0", ";", "byteNum", "<", "bytesLength", ";", "byteNum", "++", "{", "value", ":=", "int8", "(", "bytes", "[", "byteNum", "]", ")", "\n\n", "tritOffset", ":=", "byteNum", "*", "NumberOfTritsInAByte", "\n\n", "for", "tritNum", ":=", "NumberOfTritsInAByte", "-", "1", ";", "tritNum", ">=", "0", ";", "tritNum", "--", "{", "var", "trit", "int8", "=", "0", "\n\n", "tritIdx", ":=", "tritOffset", "+", "tritNum", "\n\n", "if", "tritIdx", "<", "tritsLength", "{", "byteRadixHalf", ":=", "byteRadix", "[", "tritNum", "]", ">>", "1", "\n", "if", "value", ">", "byteRadixHalf", "{", "value", "-=", "byteRadix", "[", "tritNum", "]", "\n", "trit", "=", "1", "\n", "}", "else", "if", "value", "<", "(", "-", "byteRadixHalf", ")", "{", "value", "+=", "byteRadix", "[", "tritNum", "]", "\n", "trit", "=", "-", "1", "\n", "}", "\n\n", "trits", "[", "tritIdx", "]", "=", "trit", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "trits", ",", "nil", "\n", "}" ]
// BytesToTrits unpacks an array of bytes into an array of trits
[ "BytesToTrits", "unpacks", "an", "array", "of", "bytes", "into", "an", "array", "of", "trits" ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L407-L448
423
iotaledger/iota.go
trinary/trinary.go
ReverseTrits
func ReverseTrits(trits Trits) Trits { for left, right := 0, len(trits)-1; left < right; left, right = left+1, right-1 { trits[left], trits[right] = trits[right], trits[left] } return trits }
go
func ReverseTrits(trits Trits) Trits { for left, right := 0, len(trits)-1; left < right; left, right = left+1, right-1 { trits[left], trits[right] = trits[right], trits[left] } return trits }
[ "func", "ReverseTrits", "(", "trits", "Trits", ")", "Trits", "{", "for", "left", ",", "right", ":=", "0", ",", "len", "(", "trits", ")", "-", "1", ";", "left", "<", "right", ";", "left", ",", "right", "=", "left", "+", "1", ",", "right", "-", "1", "{", "trits", "[", "left", "]", ",", "trits", "[", "right", "]", "=", "trits", "[", "right", "]", ",", "trits", "[", "left", "]", "\n", "}", "\n\n", "return", "trits", "\n", "}" ]
// ReverseTrits reverses the given trits.
[ "ReverseTrits", "reverses", "the", "given", "trits", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L451-L457
424
iotaledger/iota.go
trinary/trinary.go
ValidTrytes
func ValidTrytes(trytes Trytes) error { if !trytesRegex.MatchString(string(trytes)) { return ErrInvalidTrytes } return nil }
go
func ValidTrytes(trytes Trytes) error { if !trytesRegex.MatchString(string(trytes)) { return ErrInvalidTrytes } return nil }
[ "func", "ValidTrytes", "(", "trytes", "Trytes", ")", "error", "{", "if", "!", "trytesRegex", ".", "MatchString", "(", "string", "(", "trytes", ")", ")", "{", "return", "ErrInvalidTrytes", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidTrytes returns true if t is made of valid trytes.
[ "ValidTrytes", "returns", "true", "if", "t", "is", "made", "of", "valid", "trytes", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L471-L476
425
iotaledger/iota.go
trinary/trinary.go
NewTrytes
func NewTrytes(s string) (Trytes, error) { err := ValidTrytes(s) return s, err }
go
func NewTrytes(s string) (Trytes, error) { err := ValidTrytes(s) return s, err }
[ "func", "NewTrytes", "(", "s", "string", ")", "(", "Trytes", ",", "error", ")", "{", "err", ":=", "ValidTrytes", "(", "s", ")", "\n", "return", "s", ",", "err", "\n", "}" ]
// NewTrytes casts to Trytes and checks its validity.
[ "NewTrytes", "casts", "to", "Trytes", "and", "checks", "its", "validity", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L484-L487
426
iotaledger/iota.go
trinary/trinary.go
TrytesToTrits
func TrytesToTrits(trytes Trytes) (Trits, error) { if err := ValidTrytes(trytes); err != nil { return nil, err } trits := make(Trits, len(trytes)*3) for i := range trytes { idx := strings.Index(TryteAlphabet, string(trytes[i:i+1])) copy(trits[i*3:i*3+3], TryteToTritsLUT[idx]) } return trits, nil }
go
func TrytesToTrits(trytes Trytes) (Trits, error) { if err := ValidTrytes(trytes); err != nil { return nil, err } trits := make(Trits, len(trytes)*3) for i := range trytes { idx := strings.Index(TryteAlphabet, string(trytes[i:i+1])) copy(trits[i*3:i*3+3], TryteToTritsLUT[idx]) } return trits, nil }
[ "func", "TrytesToTrits", "(", "trytes", "Trytes", ")", "(", "Trits", ",", "error", ")", "{", "if", "err", ":=", "ValidTrytes", "(", "trytes", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "trits", ":=", "make", "(", "Trits", ",", "len", "(", "trytes", ")", "*", "3", ")", "\n", "for", "i", ":=", "range", "trytes", "{", "idx", ":=", "strings", ".", "Index", "(", "TryteAlphabet", ",", "string", "(", "trytes", "[", "i", ":", "i", "+", "1", "]", ")", ")", "\n", "copy", "(", "trits", "[", "i", "*", "3", ":", "i", "*", "3", "+", "3", "]", ",", "TryteToTritsLUT", "[", "idx", "]", ")", "\n", "}", "\n", "return", "trits", ",", "nil", "\n", "}" ]
// TrytesToTrits converts a slice of trytes into trits.
[ "TrytesToTrits", "converts", "a", "slice", "of", "trytes", "into", "trits", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L490-L500
427
iotaledger/iota.go
trinary/trinary.go
MustTrytesToTrits
func MustTrytesToTrits(trytes Trytes) Trits { trits, err := TrytesToTrits(trytes) if err != nil { panic(err) } return trits }
go
func MustTrytesToTrits(trytes Trytes) Trits { trits, err := TrytesToTrits(trytes) if err != nil { panic(err) } return trits }
[ "func", "MustTrytesToTrits", "(", "trytes", "Trytes", ")", "Trits", "{", "trits", ",", "err", ":=", "TrytesToTrits", "(", "trytes", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "trits", "\n", "}" ]
// MustTrytesToTrits converts a slice of trytes into trits.
[ "MustTrytesToTrits", "converts", "a", "slice", "of", "trytes", "into", "trits", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L503-L509
428
iotaledger/iota.go
trinary/trinary.go
Pad
func Pad(trytes Trytes, size int) Trytes { if len(trytes) >= size { return trytes } out := make([]byte, size) copy(out, []byte(trytes)) for i := len(trytes); i < size; i++ { out[i] = '9' } return Trytes(out) }
go
func Pad(trytes Trytes, size int) Trytes { if len(trytes) >= size { return trytes } out := make([]byte, size) copy(out, []byte(trytes)) for i := len(trytes); i < size; i++ { out[i] = '9' } return Trytes(out) }
[ "func", "Pad", "(", "trytes", "Trytes", ",", "size", "int", ")", "Trytes", "{", "if", "len", "(", "trytes", ")", ">=", "size", "{", "return", "trytes", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "copy", "(", "out", ",", "[", "]", "byte", "(", "trytes", ")", ")", "\n\n", "for", "i", ":=", "len", "(", "trytes", ")", ";", "i", "<", "size", ";", "i", "++", "{", "out", "[", "i", "]", "=", "'9'", "\n", "}", "\n", "return", "Trytes", "(", "out", ")", "\n", "}" ]
// Pad pads the given trytes with 9s up to the given size.
[ "Pad", "pads", "the", "given", "trytes", "with", "9s", "up", "to", "the", "given", "size", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L512-L523
429
iotaledger/iota.go
trinary/trinary.go
PadTrits
func PadTrits(trits Trits, size int) Trits { if len(trits) >= size { return trits } sized := make(Trits, size) for i := 0; i < size; i++ { if len(trits) > i { sized[i] = trits[i] continue } sized[i] = 0 } return sized }
go
func PadTrits(trits Trits, size int) Trits { if len(trits) >= size { return trits } sized := make(Trits, size) for i := 0; i < size; i++ { if len(trits) > i { sized[i] = trits[i] continue } sized[i] = 0 } return sized }
[ "func", "PadTrits", "(", "trits", "Trits", ",", "size", "int", ")", "Trits", "{", "if", "len", "(", "trits", ")", ">=", "size", "{", "return", "trits", "\n", "}", "\n", "sized", ":=", "make", "(", "Trits", ",", "size", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "size", ";", "i", "++", "{", "if", "len", "(", "trits", ")", ">", "i", "{", "sized", "[", "i", "]", "=", "trits", "[", "i", "]", "\n", "continue", "\n", "}", "\n", "sized", "[", "i", "]", "=", "0", "\n", "}", "\n", "return", "sized", "\n", "}" ]
// PadTrits pads the given trits with 0 up to the given size.
[ "PadTrits", "pads", "the", "given", "trits", "with", "0", "up", "to", "the", "given", "size", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L526-L539
430
iotaledger/iota.go
trinary/trinary.go
Sum
func Sum(a int8, b int8) int8 { s := a + b switch s { case 2: return -1 case -2: return 1 default: return s } }
go
func Sum(a int8, b int8) int8 { s := a + b switch s { case 2: return -1 case -2: return 1 default: return s } }
[ "func", "Sum", "(", "a", "int8", ",", "b", "int8", ")", "int8", "{", "s", ":=", "a", "+", "b", "\n\n", "switch", "s", "{", "case", "2", ":", "return", "-", "1", "\n", "case", "-", "2", ":", "return", "1", "\n", "default", ":", "return", "s", "\n", "}", "\n", "}" ]
// Sum returns the sum of two trits.
[ "Sum", "returns", "the", "sum", "of", "two", "trits", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L542-L553
431
iotaledger/iota.go
trinary/trinary.go
AddTrits
func AddTrits(a Trits, b Trits) Trits { maxLen := int64(math.Max(float64(len(a)), float64(len(b)))) if maxLen == 0 { return Trits{0} } out := make(Trits, maxLen) var aI, bI, carry int8 for i := 0; i < len(out); i++ { if i < len(a) { aI = a[i] } else { aI = 0 } if i < len(b) { bI = b[i] } else { bI = 0 } fA := fullAdd(aI, bI, carry) out[i] = fA[0] carry = fA[1] } return out }
go
func AddTrits(a Trits, b Trits) Trits { maxLen := int64(math.Max(float64(len(a)), float64(len(b)))) if maxLen == 0 { return Trits{0} } out := make(Trits, maxLen) var aI, bI, carry int8 for i := 0; i < len(out); i++ { if i < len(a) { aI = a[i] } else { aI = 0 } if i < len(b) { bI = b[i] } else { bI = 0 } fA := fullAdd(aI, bI, carry) out[i] = fA[0] carry = fA[1] } return out }
[ "func", "AddTrits", "(", "a", "Trits", ",", "b", "Trits", ")", "Trits", "{", "maxLen", ":=", "int64", "(", "math", ".", "Max", "(", "float64", "(", "len", "(", "a", ")", ")", ",", "float64", "(", "len", "(", "b", ")", ")", ")", ")", "\n", "if", "maxLen", "==", "0", "{", "return", "Trits", "{", "0", "}", "\n", "}", "\n", "out", ":=", "make", "(", "Trits", ",", "maxLen", ")", "\n", "var", "aI", ",", "bI", ",", "carry", "int8", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "out", ")", ";", "i", "++", "{", "if", "i", "<", "len", "(", "a", ")", "{", "aI", "=", "a", "[", "i", "]", "\n", "}", "else", "{", "aI", "=", "0", "\n", "}", "\n", "if", "i", "<", "len", "(", "b", ")", "{", "bI", "=", "b", "[", "i", "]", "\n", "}", "else", "{", "bI", "=", "0", "\n", "}", "\n\n", "fA", ":=", "fullAdd", "(", "aI", ",", "bI", ",", "carry", ")", "\n", "out", "[", "i", "]", "=", "fA", "[", "0", "]", "\n", "carry", "=", "fA", "[", "1", "]", "\n", "}", "\n", "return", "out", "\n", "}" ]
// AddTrits adds a to b.
[ "AddTrits", "adds", "a", "to", "b", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/trinary/trinary.go#L587-L612
432
iotaledger/iota.go
kerl/kerl.go
Squeeze
func (k *Kerl) Squeeze(length int) (Trits, error) { if length%HashTrinarySize != 0 { return nil, ErrInvalidSqueezeLength } out := make(Trits, length) for i := 1; i <= length/HashTrinarySize; i++ { h := k.s.Sum(nil) ts, err := KerlBytesToTrits(h) if err != nil { return nil, err } //ts[HashSize-1] = 0 copy(out[HashTrinarySize*(i-1):HashTrinarySize*i], ts) k.s.Reset() for i, e := range h { h[i] = ^e } if _, err := k.s.Write(h); err != nil { return nil, err } } return out, nil }
go
func (k *Kerl) Squeeze(length int) (Trits, error) { if length%HashTrinarySize != 0 { return nil, ErrInvalidSqueezeLength } out := make(Trits, length) for i := 1; i <= length/HashTrinarySize; i++ { h := k.s.Sum(nil) ts, err := KerlBytesToTrits(h) if err != nil { return nil, err } //ts[HashSize-1] = 0 copy(out[HashTrinarySize*(i-1):HashTrinarySize*i], ts) k.s.Reset() for i, e := range h { h[i] = ^e } if _, err := k.s.Write(h); err != nil { return nil, err } } return out, nil }
[ "func", "(", "k", "*", "Kerl", ")", "Squeeze", "(", "length", "int", ")", "(", "Trits", ",", "error", ")", "{", "if", "length", "%", "HashTrinarySize", "!=", "0", "{", "return", "nil", ",", "ErrInvalidSqueezeLength", "\n", "}", "\n\n", "out", ":=", "make", "(", "Trits", ",", "length", ")", "\n", "for", "i", ":=", "1", ";", "i", "<=", "length", "/", "HashTrinarySize", ";", "i", "++", "{", "h", ":=", "k", ".", "s", ".", "Sum", "(", "nil", ")", "\n", "ts", ",", "err", ":=", "KerlBytesToTrits", "(", "h", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "//ts[HashSize-1] = 0", "copy", "(", "out", "[", "HashTrinarySize", "*", "(", "i", "-", "1", ")", ":", "HashTrinarySize", "*", "i", "]", ",", "ts", ")", "\n", "k", ".", "s", ".", "Reset", "(", ")", "\n", "for", "i", ",", "e", ":=", "range", "h", "{", "h", "[", "i", "]", "=", "^", "e", "\n", "}", "\n", "if", "_", ",", "err", ":=", "k", ".", "s", ".", "Write", "(", "h", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "out", ",", "nil", "\n", "}" ]
// Squeeze out length trits. Length has to be a multiple of HashTrinarySize.
[ "Squeeze", "out", "length", "trits", ".", "Length", "has", "to", "be", "a", "multiple", "of", "HashTrinarySize", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/kerl/kerl.go#L29-L53
433
iotaledger/iota.go
kerl/kerl.go
Absorb
func (k *Kerl) Absorb(in Trits) error { if len(in) == 0 || len(in)%HashTrinarySize != 0 { return errors.Wrap(ErrInvalidTritsLength, "trits slice length must be a multiple of 243") } for i := 1; i <= len(in)/HashTrinarySize; i++ { // in[(HashSize*i)-1] = 0 b, err := KerlTritsToBytes(in[HashTrinarySize*(i-1) : HashTrinarySize*i]) if err != nil { return err } if _, err := k.s.Write(b); err != nil { return err } } return nil }
go
func (k *Kerl) Absorb(in Trits) error { if len(in) == 0 || len(in)%HashTrinarySize != 0 { return errors.Wrap(ErrInvalidTritsLength, "trits slice length must be a multiple of 243") } for i := 1; i <= len(in)/HashTrinarySize; i++ { // in[(HashSize*i)-1] = 0 b, err := KerlTritsToBytes(in[HashTrinarySize*(i-1) : HashTrinarySize*i]) if err != nil { return err } if _, err := k.s.Write(b); err != nil { return err } } return nil }
[ "func", "(", "k", "*", "Kerl", ")", "Absorb", "(", "in", "Trits", ")", "error", "{", "if", "len", "(", "in", ")", "==", "0", "||", "len", "(", "in", ")", "%", "HashTrinarySize", "!=", "0", "{", "return", "errors", ".", "Wrap", "(", "ErrInvalidTritsLength", ",", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ":=", "1", ";", "i", "<=", "len", "(", "in", ")", "/", "HashTrinarySize", ";", "i", "++", "{", "// in[(HashSize*i)-1] = 0", "b", ",", "err", ":=", "KerlTritsToBytes", "(", "in", "[", "HashTrinarySize", "*", "(", "i", "-", "1", ")", ":", "HashTrinarySize", "*", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "k", ".", "s", ".", "Write", "(", "b", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Absorb fills the internal state of the sponge with the given trits. // This is only defined for Trit slices that are a multiple of HashTrinarySize long.
[ "Absorb", "fills", "the", "internal", "state", "of", "the", "sponge", "with", "the", "given", "trits", ".", "This", "is", "only", "defined", "for", "Trit", "slices", "that", "are", "a", "multiple", "of", "HashTrinarySize", "long", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/kerl/kerl.go#L82-L99
434
iotaledger/iota.go
kerl/kerl.go
Clone
func (k *Kerl) Clone() SpongeFunction { clone := NewKerl().(*Kerl) clone.s = keccak.CloneState(k.s) return clone }
go
func (k *Kerl) Clone() SpongeFunction { clone := NewKerl().(*Kerl) clone.s = keccak.CloneState(k.s) return clone }
[ "func", "(", "k", "*", "Kerl", ")", "Clone", "(", ")", "SpongeFunction", "{", "clone", ":=", "NewKerl", "(", ")", ".", "(", "*", "Kerl", ")", "\n\n", "clone", ".", "s", "=", "keccak", ".", "CloneState", "(", "k", ".", "s", ")", "\n", "return", "clone", "\n", "}" ]
// Clone returns a deep copy of the current Kerl
[ "Clone", "returns", "a", "deep", "copy", "of", "the", "current", "Kerl" ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/kerl/kerl.go#L132-L137
435
iotaledger/iota.go
account/oracle/time/time.go
NewTimeDecider
func NewTimeDecider(timesource timesrc.TimeSource, remainingTimeThreshold time.Duration) oracle.OracleSource { return &timedecider{timesource, remainingTimeThreshold} }
go
func NewTimeDecider(timesource timesrc.TimeSource, remainingTimeThreshold time.Duration) oracle.OracleSource { return &timedecider{timesource, remainingTimeThreshold} }
[ "func", "NewTimeDecider", "(", "timesource", "timesrc", ".", "TimeSource", ",", "remainingTimeThreshold", "time", ".", "Duration", ")", "oracle", ".", "OracleSource", "{", "return", "&", "timedecider", "{", "timesource", ",", "remainingTimeThreshold", "}", "\n", "}" ]
// NewTimeDecider creates a new OracleSource which uses the current time to decide whether // it makes sense to send a transaction. remainingTimeThreshold defines the maximum allowed // remaining time between now and the conditions' timeout.
[ "NewTimeDecider", "creates", "a", "new", "OracleSource", "which", "uses", "the", "current", "time", "to", "decide", "whether", "it", "makes", "sense", "to", "send", "a", "transaction", ".", "remainingTimeThreshold", "defines", "the", "maximum", "allowed", "remaining", "time", "between", "now", "and", "the", "conditions", "timeout", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/account/oracle/time/time.go#L16-L18
436
iotaledger/iota.go
account/util/synctimer.go
NewSyncIntervalTimer
func NewSyncIntervalTimer(interval time.Duration, f SyncFunc, onError OnErrorFunc) *SyncIntervalTimer { var intervalTimer *time.Ticker if interval > 0 { intervalTimer = time.NewTicker(interval) } return &SyncIntervalTimer{ f: f, onError: onError, intervalTimer: intervalTimer, sync: make(chan struct{}), stop: make(chan struct{}), } }
go
func NewSyncIntervalTimer(interval time.Duration, f SyncFunc, onError OnErrorFunc) *SyncIntervalTimer { var intervalTimer *time.Ticker if interval > 0 { intervalTimer = time.NewTicker(interval) } return &SyncIntervalTimer{ f: f, onError: onError, intervalTimer: intervalTimer, sync: make(chan struct{}), stop: make(chan struct{}), } }
[ "func", "NewSyncIntervalTimer", "(", "interval", "time", ".", "Duration", ",", "f", "SyncFunc", ",", "onError", "OnErrorFunc", ")", "*", "SyncIntervalTimer", "{", "var", "intervalTimer", "*", "time", ".", "Ticker", "\n", "if", "interval", ">", "0", "{", "intervalTimer", "=", "time", ".", "NewTicker", "(", "interval", ")", "\n", "}", "\n", "return", "&", "SyncIntervalTimer", "{", "f", ":", "f", ",", "onError", ":", "onError", ",", "intervalTimer", ":", "intervalTimer", ",", "sync", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "stop", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// NewSyncIntervalTimer creates a new SyncIntervalTimer with the given function and interval. onError can be nil.
[ "NewSyncIntervalTimer", "creates", "a", "new", "SyncIntervalTimer", "with", "the", "given", "function", "and", "interval", ".", "onError", "can", "be", "nil", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/account/util/synctimer.go#L14-L25
437
iotaledger/iota.go
account/util/synctimer.go
Start
func (sit *SyncIntervalTimer) Start() { if sit.intervalTimer == nil { exitA: for { select { case sit.sync <- struct{}{}: <-sit.sync case <-sit.stop: break exitA } } } else { exitB: for { select { case <-sit.intervalTimer.C: if err := sit.f(); err != nil { if sit.onError != nil { sit.onError(err) } } select { case <-sit.stop: break exitB default: } case sit.sync <- struct{}{}: <-sit.sync case <-sit.stop: break exitB } } } close(sit.sync) }
go
func (sit *SyncIntervalTimer) Start() { if sit.intervalTimer == nil { exitA: for { select { case sit.sync <- struct{}{}: <-sit.sync case <-sit.stop: break exitA } } } else { exitB: for { select { case <-sit.intervalTimer.C: if err := sit.f(); err != nil { if sit.onError != nil { sit.onError(err) } } select { case <-sit.stop: break exitB default: } case sit.sync <- struct{}{}: <-sit.sync case <-sit.stop: break exitB } } } close(sit.sync) }
[ "func", "(", "sit", "*", "SyncIntervalTimer", ")", "Start", "(", ")", "{", "if", "sit", ".", "intervalTimer", "==", "nil", "{", "exitA", ":", "for", "{", "select", "{", "case", "sit", ".", "sync", "<-", "struct", "{", "}", "{", "}", ":", "<-", "sit", ".", "sync", "\n", "case", "<-", "sit", ".", "stop", ":", "break", "exitA", "\n", "}", "\n", "}", "\n", "}", "else", "{", "exitB", ":", "for", "{", "select", "{", "case", "<-", "sit", ".", "intervalTimer", ".", "C", ":", "if", "err", ":=", "sit", ".", "f", "(", ")", ";", "err", "!=", "nil", "{", "if", "sit", ".", "onError", "!=", "nil", "{", "sit", ".", "onError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "select", "{", "case", "<-", "sit", ".", "stop", ":", "break", "exitB", "\n", "default", ":", "}", "\n", "case", "sit", ".", "sync", "<-", "struct", "{", "}", "{", "}", ":", "<-", "sit", ".", "sync", "\n", "case", "<-", "sit", ".", "stop", ":", "break", "exitB", "\n", "}", "\n", "}", "\n", "}", "\n", "close", "(", "sit", ".", "sync", ")", "\n", "}" ]
// Start starts the timer loop. This function blocks the caller until // the timer is stopped.
[ "Start", "starts", "the", "timer", "loop", ".", "This", "function", "blocks", "the", "caller", "until", "the", "timer", "is", "stopped", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/account/util/synctimer.go#L38-L72
438
iotaledger/iota.go
account/util/synctimer.go
Stop
func (sit *SyncIntervalTimer) Stop() { sit.stop <- struct{}{} if sit.intervalTimer != nil { sit.intervalTimer.Stop() } }
go
func (sit *SyncIntervalTimer) Stop() { sit.stop <- struct{}{} if sit.intervalTimer != nil { sit.intervalTimer.Stop() } }
[ "func", "(", "sit", "*", "SyncIntervalTimer", ")", "Stop", "(", ")", "{", "sit", ".", "stop", "<-", "struct", "{", "}", "{", "}", "\n", "if", "sit", ".", "intervalTimer", "!=", "nil", "{", "sit", ".", "intervalTimer", ".", "Stop", "(", ")", "\n", "}", "\n", "}" ]
// Stop awaits the currently executing function to return and then stops the interval loop.
[ "Stop", "awaits", "the", "currently", "executing", "function", "to", "return", "and", "then", "stops", "the", "interval", "loop", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/account/util/synctimer.go#L85-L90
439
iotaledger/iota.go
kerl/sha3/sha3_s390x.go
copyIntoBuf
func (s *asmState) copyIntoBuf(b []byte) { bufLen := len(s.buf) s.buf = s.buf[:len(s.buf)+len(b)] copy(s.buf[bufLen:], b) }
go
func (s *asmState) copyIntoBuf(b []byte) { bufLen := len(s.buf) s.buf = s.buf[:len(s.buf)+len(b)] copy(s.buf[bufLen:], b) }
[ "func", "(", "s", "*", "asmState", ")", "copyIntoBuf", "(", "b", "[", "]", "byte", ")", "{", "bufLen", ":=", "len", "(", "s", ".", "buf", ")", "\n", "s", ".", "buf", "=", "s", ".", "buf", "[", ":", "len", "(", "s", ".", "buf", ")", "+", "len", "(", "b", ")", "]", "\n", "copy", "(", "s", ".", "buf", "[", "bufLen", ":", "]", ",", "b", ")", "\n", "}" ]
// copyIntoBuf copies b into buf. It will panic if there is not enough space to // store all of b.
[ "copyIntoBuf", "copies", "b", "into", "buf", ".", "It", "will", "panic", "if", "there", "is", "not", "enough", "space", "to", "store", "all", "of", "b", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/kerl/sha3/sha3_s390x.go#L96-L100
440
iotaledger/iota.go
kerl/sha3/sha3_s390x.go
resetBuf
func (s *asmState) resetBuf() { max := (cap(s.storage) / s.rate) * s.rate s.buf = s.storage[:0:max] }
go
func (s *asmState) resetBuf() { max := (cap(s.storage) / s.rate) * s.rate s.buf = s.storage[:0:max] }
[ "func", "(", "s", "*", "asmState", ")", "resetBuf", "(", ")", "{", "max", ":=", "(", "cap", "(", "s", ".", "storage", ")", "/", "s", ".", "rate", ")", "*", "s", ".", "rate", "\n", "s", ".", "buf", "=", "s", ".", "storage", "[", ":", "0", ":", "max", "]", "\n", "}" ]
// resetBuf points buf at storage, sets the length to 0 and sets cap to be a // multiple of the rate.
[ "resetBuf", "points", "buf", "at", "storage", "sets", "the", "length", "to", "0", "and", "sets", "cap", "to", "be", "a", "multiple", "of", "the", "rate", "." ]
812d82f707314a82defbb5ef9d965fd2129dfa50
https://github.com/iotaledger/iota.go/blob/812d82f707314a82defbb5ef9d965fd2129dfa50/kerl/sha3/sha3_s390x.go#L104-L107
441
hoisie/mustache
mustache.go
call
func call(v reflect.Value, method reflect.Method) reflect.Value { funcType := method.Type // Method must take no arguments, meaning as a func it has one argument (the receiver) if funcType.NumIn() != 1 { return reflect.Value{} } // Method must return a single value. if funcType.NumOut() == 0 { return reflect.Value{} } // Result will be the zeroth element of the returned slice. return method.Func.Call([]reflect.Value{v})[0] }
go
func call(v reflect.Value, method reflect.Method) reflect.Value { funcType := method.Type // Method must take no arguments, meaning as a func it has one argument (the receiver) if funcType.NumIn() != 1 { return reflect.Value{} } // Method must return a single value. if funcType.NumOut() == 0 { return reflect.Value{} } // Result will be the zeroth element of the returned slice. return method.Func.Call([]reflect.Value{v})[0] }
[ "func", "call", "(", "v", "reflect", ".", "Value", ",", "method", "reflect", ".", "Method", ")", "reflect", ".", "Value", "{", "funcType", ":=", "method", ".", "Type", "\n", "// Method must take no arguments, meaning as a func it has one argument (the receiver)", "if", "funcType", ".", "NumIn", "(", ")", "!=", "1", "{", "return", "reflect", ".", "Value", "{", "}", "\n", "}", "\n", "// Method must return a single value.", "if", "funcType", ".", "NumOut", "(", ")", "==", "0", "{", "return", "reflect", ".", "Value", "{", "}", "\n", "}", "\n", "// Result will be the zeroth element of the returned slice.", "return", "method", ".", "Func", ".", "Call", "(", "[", "]", "reflect", ".", "Value", "{", "v", "}", ")", "[", "0", "]", "\n", "}" ]
// Invoke the method. If its signature is wrong, return nil.
[ "Invoke", "the", "method", ".", "If", "its", "signature", "is", "wrong", "return", "nil", "." ]
6375acf62c69d9d3ad20fd0599d82ca94ea12284
https://github.com/hoisie/mustache/blob/6375acf62c69d9d3ad20fd0599d82ca94ea12284/mustache.go#L330-L342
442
hoisie/mustache
mustache.go
lookup
func lookup(contextChain []interface{}, name string) reflect.Value { // dot notation if name != "." && strings.Contains(name, ".") { parts := strings.SplitN(name, ".", 2) v := lookup(contextChain, parts[0]) return lookup([]interface{}{v}, parts[1]) } defer func() { if r := recover(); r != nil { fmt.Printf("Panic while looking up %q: %s\n", name, r) } }() Outer: for _, ctx := range contextChain { //i := len(contextChain) - 1; i >= 0; i-- { v := ctx.(reflect.Value) for v.IsValid() { typ := v.Type() if n := v.Type().NumMethod(); n > 0 { for i := 0; i < n; i++ { m := typ.Method(i) mtyp := m.Type if m.Name == name && mtyp.NumIn() == 1 { return v.Method(i).Call(nil)[0] } } } if name == "." { return v } switch av := v; av.Kind() { case reflect.Ptr: v = av.Elem() case reflect.Interface: v = av.Elem() case reflect.Struct: ret := av.FieldByName(name) if ret.IsValid() { return ret } else { continue Outer } case reflect.Map: ret := av.MapIndex(reflect.ValueOf(name)) if ret.IsValid() { return ret } else { continue Outer } default: continue Outer } } } return reflect.Value{} }
go
func lookup(contextChain []interface{}, name string) reflect.Value { // dot notation if name != "." && strings.Contains(name, ".") { parts := strings.SplitN(name, ".", 2) v := lookup(contextChain, parts[0]) return lookup([]interface{}{v}, parts[1]) } defer func() { if r := recover(); r != nil { fmt.Printf("Panic while looking up %q: %s\n", name, r) } }() Outer: for _, ctx := range contextChain { //i := len(contextChain) - 1; i >= 0; i-- { v := ctx.(reflect.Value) for v.IsValid() { typ := v.Type() if n := v.Type().NumMethod(); n > 0 { for i := 0; i < n; i++ { m := typ.Method(i) mtyp := m.Type if m.Name == name && mtyp.NumIn() == 1 { return v.Method(i).Call(nil)[0] } } } if name == "." { return v } switch av := v; av.Kind() { case reflect.Ptr: v = av.Elem() case reflect.Interface: v = av.Elem() case reflect.Struct: ret := av.FieldByName(name) if ret.IsValid() { return ret } else { continue Outer } case reflect.Map: ret := av.MapIndex(reflect.ValueOf(name)) if ret.IsValid() { return ret } else { continue Outer } default: continue Outer } } } return reflect.Value{} }
[ "func", "lookup", "(", "contextChain", "[", "]", "interface", "{", "}", ",", "name", "string", ")", "reflect", ".", "Value", "{", "// dot notation", "if", "name", "!=", "\"", "\"", "&&", "strings", ".", "Contains", "(", "name", ",", "\"", "\"", ")", "{", "parts", ":=", "strings", ".", "SplitN", "(", "name", ",", "\"", "\"", ",", "2", ")", "\n", "v", ":=", "lookup", "(", "contextChain", ",", "parts", "[", "0", "]", ")", "\n", "return", "lookup", "(", "[", "]", "interface", "{", "}", "{", "v", "}", ",", "parts", "[", "1", "]", ")", "\n", "}", "\n\n", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "name", ",", "r", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "Outer", ":", "for", "_", ",", "ctx", ":=", "range", "contextChain", "{", "//i := len(contextChain) - 1; i >= 0; i-- {", "v", ":=", "ctx", ".", "(", "reflect", ".", "Value", ")", "\n", "for", "v", ".", "IsValid", "(", ")", "{", "typ", ":=", "v", ".", "Type", "(", ")", "\n", "if", "n", ":=", "v", ".", "Type", "(", ")", ".", "NumMethod", "(", ")", ";", "n", ">", "0", "{", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "m", ":=", "typ", ".", "Method", "(", "i", ")", "\n", "mtyp", ":=", "m", ".", "Type", "\n", "if", "m", ".", "Name", "==", "name", "&&", "mtyp", ".", "NumIn", "(", ")", "==", "1", "{", "return", "v", ".", "Method", "(", "i", ")", ".", "Call", "(", "nil", ")", "[", "0", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "name", "==", "\"", "\"", "{", "return", "v", "\n", "}", "\n", "switch", "av", ":=", "v", ";", "av", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Ptr", ":", "v", "=", "av", ".", "Elem", "(", ")", "\n", "case", "reflect", ".", "Interface", ":", "v", "=", "av", ".", "Elem", "(", ")", "\n", "case", "reflect", ".", "Struct", ":", "ret", ":=", "av", ".", "FieldByName", "(", "name", ")", "\n", "if", "ret", ".", "IsValid", "(", ")", "{", "return", "ret", "\n", "}", "else", "{", "continue", "Outer", "\n", "}", "\n", "case", "reflect", ".", "Map", ":", "ret", ":=", "av", ".", "MapIndex", "(", "reflect", ".", "ValueOf", "(", "name", ")", ")", "\n", "if", "ret", ".", "IsValid", "(", ")", "{", "return", "ret", "\n", "}", "else", "{", "continue", "Outer", "\n", "}", "\n", "default", ":", "continue", "Outer", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "reflect", ".", "Value", "{", "}", "\n", "}" ]
// Evaluate interfaces and pointers looking for a value that can look up the name, via a // struct field, method, or map key, and return the result of the lookup.
[ "Evaluate", "interfaces", "and", "pointers", "looking", "for", "a", "value", "that", "can", "look", "up", "the", "name", "via", "a", "struct", "field", "method", "or", "map", "key", "and", "return", "the", "result", "of", "the", "lookup", "." ]
6375acf62c69d9d3ad20fd0599d82ca94ea12284
https://github.com/hoisie/mustache/blob/6375acf62c69d9d3ad20fd0599d82ca94ea12284/mustache.go#L346-L403
443
leonelquinteros/gotext
po.go
saveBuffer
func (po *Po) saveBuffer() { // With no context... if po.ctxBuffer == "" { po.translations[po.trBuffer.ID] = po.trBuffer } else { // With context... if _, ok := po.contexts[po.ctxBuffer]; !ok { po.contexts[po.ctxBuffer] = make(map[string]*Translation) } po.contexts[po.ctxBuffer][po.trBuffer.ID] = po.trBuffer // Cleanup current context buffer if needed if po.trBuffer.ID != "" { po.ctxBuffer = "" } } // Flush Translation buffer po.trBuffer = NewTranslation() }
go
func (po *Po) saveBuffer() { // With no context... if po.ctxBuffer == "" { po.translations[po.trBuffer.ID] = po.trBuffer } else { // With context... if _, ok := po.contexts[po.ctxBuffer]; !ok { po.contexts[po.ctxBuffer] = make(map[string]*Translation) } po.contexts[po.ctxBuffer][po.trBuffer.ID] = po.trBuffer // Cleanup current context buffer if needed if po.trBuffer.ID != "" { po.ctxBuffer = "" } } // Flush Translation buffer po.trBuffer = NewTranslation() }
[ "func", "(", "po", "*", "Po", ")", "saveBuffer", "(", ")", "{", "// With no context...", "if", "po", ".", "ctxBuffer", "==", "\"", "\"", "{", "po", ".", "translations", "[", "po", ".", "trBuffer", ".", "ID", "]", "=", "po", ".", "trBuffer", "\n", "}", "else", "{", "// With context...", "if", "_", ",", "ok", ":=", "po", ".", "contexts", "[", "po", ".", "ctxBuffer", "]", ";", "!", "ok", "{", "po", ".", "contexts", "[", "po", ".", "ctxBuffer", "]", "=", "make", "(", "map", "[", "string", "]", "*", "Translation", ")", "\n", "}", "\n", "po", ".", "contexts", "[", "po", ".", "ctxBuffer", "]", "[", "po", ".", "trBuffer", ".", "ID", "]", "=", "po", ".", "trBuffer", "\n\n", "// Cleanup current context buffer if needed", "if", "po", ".", "trBuffer", ".", "ID", "!=", "\"", "\"", "{", "po", ".", "ctxBuffer", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "// Flush Translation buffer", "po", ".", "trBuffer", "=", "NewTranslation", "(", ")", "\n", "}" ]
// saveBuffer takes the context and Translation buffers // and saves it on the translations collection
[ "saveBuffer", "takes", "the", "context", "and", "Translation", "buffers", "and", "saves", "it", "on", "the", "translations", "collection" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/po.go#L185-L204
444
leonelquinteros/gotext
po.go
parseContext
func (po *Po) parseContext(l string) { // Save current Translation buffer. po.saveBuffer() // Buffer context po.ctxBuffer, _ = strconv.Unquote(strings.TrimSpace(strings.TrimPrefix(l, "msgctxt"))) }
go
func (po *Po) parseContext(l string) { // Save current Translation buffer. po.saveBuffer() // Buffer context po.ctxBuffer, _ = strconv.Unquote(strings.TrimSpace(strings.TrimPrefix(l, "msgctxt"))) }
[ "func", "(", "po", "*", "Po", ")", "parseContext", "(", "l", "string", ")", "{", "// Save current Translation buffer.", "po", ".", "saveBuffer", "(", ")", "\n\n", "// Buffer context", "po", ".", "ctxBuffer", ",", "_", "=", "strconv", ".", "Unquote", "(", "strings", ".", "TrimSpace", "(", "strings", ".", "TrimPrefix", "(", "l", ",", "\"", "\"", ")", ")", ")", "\n", "}" ]
// parseContext takes a line starting with "msgctxt", // saves the current Translation buffer and creates a new context.
[ "parseContext", "takes", "a", "line", "starting", "with", "msgctxt", "saves", "the", "current", "Translation", "buffer", "and", "creates", "a", "new", "context", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/po.go#L208-L214
445
leonelquinteros/gotext
po.go
parseID
func (po *Po) parseID(l string) { // Save current Translation buffer. po.saveBuffer() // Set id po.trBuffer.ID, _ = strconv.Unquote(strings.TrimSpace(strings.TrimPrefix(l, "msgid"))) }
go
func (po *Po) parseID(l string) { // Save current Translation buffer. po.saveBuffer() // Set id po.trBuffer.ID, _ = strconv.Unquote(strings.TrimSpace(strings.TrimPrefix(l, "msgid"))) }
[ "func", "(", "po", "*", "Po", ")", "parseID", "(", "l", "string", ")", "{", "// Save current Translation buffer.", "po", ".", "saveBuffer", "(", ")", "\n\n", "// Set id", "po", ".", "trBuffer", ".", "ID", ",", "_", "=", "strconv", ".", "Unquote", "(", "strings", ".", "TrimSpace", "(", "strings", ".", "TrimPrefix", "(", "l", ",", "\"", "\"", ")", ")", ")", "\n", "}" ]
// parseID takes a line starting with "msgid", // saves the current Translation and creates a new msgid buffer.
[ "parseID", "takes", "a", "line", "starting", "with", "msgid", "saves", "the", "current", "Translation", "and", "creates", "a", "new", "msgid", "buffer", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/po.go#L218-L224
446
leonelquinteros/gotext
po.go
parsePluralID
func (po *Po) parsePluralID(l string) { po.trBuffer.PluralID, _ = strconv.Unquote(strings.TrimSpace(strings.TrimPrefix(l, "msgid_plural"))) }
go
func (po *Po) parsePluralID(l string) { po.trBuffer.PluralID, _ = strconv.Unquote(strings.TrimSpace(strings.TrimPrefix(l, "msgid_plural"))) }
[ "func", "(", "po", "*", "Po", ")", "parsePluralID", "(", "l", "string", ")", "{", "po", ".", "trBuffer", ".", "PluralID", ",", "_", "=", "strconv", ".", "Unquote", "(", "strings", ".", "TrimSpace", "(", "strings", ".", "TrimPrefix", "(", "l", ",", "\"", "\"", ")", ")", ")", "\n", "}" ]
// parsePluralID saves the plural id buffer from a line starting with "msgid_plural"
[ "parsePluralID", "saves", "the", "plural", "id", "buffer", "from", "a", "line", "starting", "with", "msgid_plural" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/po.go#L227-L229
447
leonelquinteros/gotext
po.go
parseMessage
func (po *Po) parseMessage(l string) { l = strings.TrimSpace(strings.TrimPrefix(l, "msgstr")) // Check for indexed Translation forms if strings.HasPrefix(l, "[") { idx := strings.Index(l, "]") if idx == -1 { // Skip wrong index formatting return } // Parse index i, err := strconv.Atoi(l[1:idx]) if err != nil { // Skip wrong index formatting return } // Parse Translation string po.trBuffer.Trs[i], _ = strconv.Unquote(strings.TrimSpace(l[idx+1:])) // Loop return } // Save single Translation form under 0 index po.trBuffer.Trs[0], _ = strconv.Unquote(l) }
go
func (po *Po) parseMessage(l string) { l = strings.TrimSpace(strings.TrimPrefix(l, "msgstr")) // Check for indexed Translation forms if strings.HasPrefix(l, "[") { idx := strings.Index(l, "]") if idx == -1 { // Skip wrong index formatting return } // Parse index i, err := strconv.Atoi(l[1:idx]) if err != nil { // Skip wrong index formatting return } // Parse Translation string po.trBuffer.Trs[i], _ = strconv.Unquote(strings.TrimSpace(l[idx+1:])) // Loop return } // Save single Translation form under 0 index po.trBuffer.Trs[0], _ = strconv.Unquote(l) }
[ "func", "(", "po", "*", "Po", ")", "parseMessage", "(", "l", "string", ")", "{", "l", "=", "strings", ".", "TrimSpace", "(", "strings", ".", "TrimPrefix", "(", "l", ",", "\"", "\"", ")", ")", "\n\n", "// Check for indexed Translation forms", "if", "strings", ".", "HasPrefix", "(", "l", ",", "\"", "\"", ")", "{", "idx", ":=", "strings", ".", "Index", "(", "l", ",", "\"", "\"", ")", "\n", "if", "idx", "==", "-", "1", "{", "// Skip wrong index formatting", "return", "\n", "}", "\n\n", "// Parse index", "i", ",", "err", ":=", "strconv", ".", "Atoi", "(", "l", "[", "1", ":", "idx", "]", ")", "\n", "if", "err", "!=", "nil", "{", "// Skip wrong index formatting", "return", "\n", "}", "\n\n", "// Parse Translation string", "po", ".", "trBuffer", ".", "Trs", "[", "i", "]", ",", "_", "=", "strconv", ".", "Unquote", "(", "strings", ".", "TrimSpace", "(", "l", "[", "idx", "+", "1", ":", "]", ")", ")", "\n\n", "// Loop", "return", "\n", "}", "\n\n", "// Save single Translation form under 0 index", "po", ".", "trBuffer", ".", "Trs", "[", "0", "]", ",", "_", "=", "strconv", ".", "Unquote", "(", "l", ")", "\n", "}" ]
// parseMessage takes a line starting with "msgstr" and saves it into the current buffer.
[ "parseMessage", "takes", "a", "line", "starting", "with", "msgstr", "and", "saves", "it", "into", "the", "current", "buffer", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/po.go#L232-L259
448
leonelquinteros/gotext
po.go
parseString
func (po *Po) parseString(l string, state parseState) { clean, _ := strconv.Unquote(l) switch state { case msgStr: // Append to last Translation found po.trBuffer.Trs[len(po.trBuffer.Trs)-1] += clean case msgID: // Multiline msgid - Append to current id po.trBuffer.ID += clean case msgIDPlural: // Multiline msgid - Append to current id po.trBuffer.PluralID += clean case msgCtxt: // Multiline context - Append to current context po.ctxBuffer += clean } }
go
func (po *Po) parseString(l string, state parseState) { clean, _ := strconv.Unquote(l) switch state { case msgStr: // Append to last Translation found po.trBuffer.Trs[len(po.trBuffer.Trs)-1] += clean case msgID: // Multiline msgid - Append to current id po.trBuffer.ID += clean case msgIDPlural: // Multiline msgid - Append to current id po.trBuffer.PluralID += clean case msgCtxt: // Multiline context - Append to current context po.ctxBuffer += clean } }
[ "func", "(", "po", "*", "Po", ")", "parseString", "(", "l", "string", ",", "state", "parseState", ")", "{", "clean", ",", "_", ":=", "strconv", ".", "Unquote", "(", "l", ")", "\n\n", "switch", "state", "{", "case", "msgStr", ":", "// Append to last Translation found", "po", ".", "trBuffer", ".", "Trs", "[", "len", "(", "po", ".", "trBuffer", ".", "Trs", ")", "-", "1", "]", "+=", "clean", "\n\n", "case", "msgID", ":", "// Multiline msgid - Append to current id", "po", ".", "trBuffer", ".", "ID", "+=", "clean", "\n\n", "case", "msgIDPlural", ":", "// Multiline msgid - Append to current id", "po", ".", "trBuffer", ".", "PluralID", "+=", "clean", "\n\n", "case", "msgCtxt", ":", "// Multiline context - Append to current context", "po", ".", "ctxBuffer", "+=", "clean", "\n\n", "}", "\n", "}" ]
// parseString takes a well formatted string without prefix // and creates headers or attach multi-line strings when corresponding
[ "parseString", "takes", "a", "well", "formatted", "string", "without", "prefix", "and", "creates", "headers", "or", "attach", "multi", "-", "line", "strings", "when", "corresponding" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/po.go#L263-L284
449
leonelquinteros/gotext
po.go
isValidLine
func (po *Po) isValidLine(l string) bool { // Check prefix valid := []string{ "\"", "msgctxt", "msgid", "msgid_plural", "msgstr", } for _, v := range valid { if strings.HasPrefix(l, v) { return true } } return false }
go
func (po *Po) isValidLine(l string) bool { // Check prefix valid := []string{ "\"", "msgctxt", "msgid", "msgid_plural", "msgstr", } for _, v := range valid { if strings.HasPrefix(l, v) { return true } } return false }
[ "func", "(", "po", "*", "Po", ")", "isValidLine", "(", "l", "string", ")", "bool", "{", "// Check prefix", "valid", ":=", "[", "]", "string", "{", "\"", "\\\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n\n", "for", "_", ",", "v", ":=", "range", "valid", "{", "if", "strings", ".", "HasPrefix", "(", "l", ",", "v", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// isValidLine checks for line prefixes to detect valid syntax.
[ "isValidLine", "checks", "for", "line", "prefixes", "to", "detect", "valid", "syntax", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/po.go#L287-L304
450
leonelquinteros/gotext
po.go
UnmarshalBinary
func (po *Po) UnmarshalBinary(data []byte) error { buff := bytes.NewBuffer(data) obj := new(TranslatorEncoding) decoder := gob.NewDecoder(buff) err := decoder.Decode(obj) if err != nil { return err } po.Headers = obj.Headers po.Language = obj.Language po.PluralForms = obj.PluralForms po.nplurals = obj.Nplurals po.plural = obj.Plural po.translations = obj.Translations po.contexts = obj.Contexts if expr, err := plurals.Compile(po.plural); err == nil { po.pluralforms = expr } return nil }
go
func (po *Po) UnmarshalBinary(data []byte) error { buff := bytes.NewBuffer(data) obj := new(TranslatorEncoding) decoder := gob.NewDecoder(buff) err := decoder.Decode(obj) if err != nil { return err } po.Headers = obj.Headers po.Language = obj.Language po.PluralForms = obj.PluralForms po.nplurals = obj.Nplurals po.plural = obj.Plural po.translations = obj.Translations po.contexts = obj.Contexts if expr, err := plurals.Compile(po.plural); err == nil { po.pluralforms = expr } return nil }
[ "func", "(", "po", "*", "Po", ")", "UnmarshalBinary", "(", "data", "[", "]", "byte", ")", "error", "{", "buff", ":=", "bytes", ".", "NewBuffer", "(", "data", ")", "\n", "obj", ":=", "new", "(", "TranslatorEncoding", ")", "\n\n", "decoder", ":=", "gob", ".", "NewDecoder", "(", "buff", ")", "\n", "err", ":=", "decoder", ".", "Decode", "(", "obj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "po", ".", "Headers", "=", "obj", ".", "Headers", "\n", "po", ".", "Language", "=", "obj", ".", "Language", "\n", "po", ".", "PluralForms", "=", "obj", ".", "PluralForms", "\n", "po", ".", "nplurals", "=", "obj", ".", "Nplurals", "\n", "po", ".", "plural", "=", "obj", ".", "Plural", "\n", "po", ".", "translations", "=", "obj", ".", "Translations", "\n", "po", ".", "contexts", "=", "obj", ".", "Contexts", "\n\n", "if", "expr", ",", "err", ":=", "plurals", ".", "Compile", "(", "po", ".", "plural", ")", ";", "err", "==", "nil", "{", "po", ".", "pluralforms", "=", "expr", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalBinary implements encoding.BinaryUnmarshaler interface
[ "UnmarshalBinary", "implements", "encoding", ".", "BinaryUnmarshaler", "interface" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/po.go#L476-L499
451
leonelquinteros/gotext
translation.go
NewTranslation
func NewTranslation() *Translation { tr := new(Translation) tr.Trs = make(map[int]string) return tr }
go
func NewTranslation() *Translation { tr := new(Translation) tr.Trs = make(map[int]string) return tr }
[ "func", "NewTranslation", "(", ")", "*", "Translation", "{", "tr", ":=", "new", "(", "Translation", ")", "\n", "tr", ".", "Trs", "=", "make", "(", "map", "[", "int", "]", "string", ")", "\n\n", "return", "tr", "\n", "}" ]
// NewTranslation returns the Translation object and initialized it.
[ "NewTranslation", "returns", "the", "Translation", "object", "and", "initialized", "it", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/translation.go#L16-L21
452
leonelquinteros/gotext
translation.go
Get
func (t *Translation) Get() string { // Look for Translation index 0 if _, ok := t.Trs[0]; ok { if t.Trs[0] != "" { return t.Trs[0] } } // Return untranslated id by default return t.ID }
go
func (t *Translation) Get() string { // Look for Translation index 0 if _, ok := t.Trs[0]; ok { if t.Trs[0] != "" { return t.Trs[0] } } // Return untranslated id by default return t.ID }
[ "func", "(", "t", "*", "Translation", ")", "Get", "(", ")", "string", "{", "// Look for Translation index 0", "if", "_", ",", "ok", ":=", "t", ".", "Trs", "[", "0", "]", ";", "ok", "{", "if", "t", ".", "Trs", "[", "0", "]", "!=", "\"", "\"", "{", "return", "t", ".", "Trs", "[", "0", "]", "\n", "}", "\n", "}", "\n\n", "// Return untranslated id by default", "return", "t", ".", "ID", "\n", "}" ]
// Get returns the string of the translation
[ "Get", "returns", "the", "string", "of", "the", "translation" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/translation.go#L24-L34
453
leonelquinteros/gotext
translation.go
GetN
func (t *Translation) GetN(n int) string { // Look for Translation index if _, ok := t.Trs[n]; ok { if t.Trs[n] != "" { return t.Trs[n] } } // Return untranslated singular if corresponding if n == 0 { return t.ID } // Return untranslated plural by default return t.PluralID }
go
func (t *Translation) GetN(n int) string { // Look for Translation index if _, ok := t.Trs[n]; ok { if t.Trs[n] != "" { return t.Trs[n] } } // Return untranslated singular if corresponding if n == 0 { return t.ID } // Return untranslated plural by default return t.PluralID }
[ "func", "(", "t", "*", "Translation", ")", "GetN", "(", "n", "int", ")", "string", "{", "// Look for Translation index", "if", "_", ",", "ok", ":=", "t", ".", "Trs", "[", "n", "]", ";", "ok", "{", "if", "t", ".", "Trs", "[", "n", "]", "!=", "\"", "\"", "{", "return", "t", ".", "Trs", "[", "n", "]", "\n", "}", "\n", "}", "\n\n", "// Return untranslated singular if corresponding", "if", "n", "==", "0", "{", "return", "t", ".", "ID", "\n", "}", "\n\n", "// Return untranslated plural by default", "return", "t", ".", "PluralID", "\n", "}" ]
// GetN returns the string of the plural translation
[ "GetN", "returns", "the", "string", "of", "the", "plural", "translation" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/translation.go#L37-L52
454
leonelquinteros/gotext
locale.go
AddDomain
func (l *Locale) AddDomain(dom string) { var poObj Translator file := l.findExt(dom, "po") if file != "" { poObj = new(Po) // Parse file. poObj.ParseFile(file) } else { file = l.findExt(dom, "mo") if file != "" { poObj = new(Mo) // Parse file. poObj.ParseFile(file) } else { // fallback return if no file found with return } } // Save new domain l.Lock() if l.Domains == nil { l.Domains = make(map[string]Translator) } if l.defaultDomain == "" { l.defaultDomain = dom } l.Domains[dom] = poObj // Unlock "Save new domain" l.Unlock() }
go
func (l *Locale) AddDomain(dom string) { var poObj Translator file := l.findExt(dom, "po") if file != "" { poObj = new(Po) // Parse file. poObj.ParseFile(file) } else { file = l.findExt(dom, "mo") if file != "" { poObj = new(Mo) // Parse file. poObj.ParseFile(file) } else { // fallback return if no file found with return } } // Save new domain l.Lock() if l.Domains == nil { l.Domains = make(map[string]Translator) } if l.defaultDomain == "" { l.defaultDomain = dom } l.Domains[dom] = poObj // Unlock "Save new domain" l.Unlock() }
[ "func", "(", "l", "*", "Locale", ")", "AddDomain", "(", "dom", "string", ")", "{", "var", "poObj", "Translator", "\n\n", "file", ":=", "l", ".", "findExt", "(", "dom", ",", "\"", "\"", ")", "\n", "if", "file", "!=", "\"", "\"", "{", "poObj", "=", "new", "(", "Po", ")", "\n", "// Parse file.", "poObj", ".", "ParseFile", "(", "file", ")", "\n", "}", "else", "{", "file", "=", "l", ".", "findExt", "(", "dom", ",", "\"", "\"", ")", "\n", "if", "file", "!=", "\"", "\"", "{", "poObj", "=", "new", "(", "Mo", ")", "\n", "// Parse file.", "poObj", ".", "ParseFile", "(", "file", ")", "\n", "}", "else", "{", "// fallback return if no file found with", "return", "\n", "}", "\n", "}", "\n\n", "// Save new domain", "l", ".", "Lock", "(", ")", "\n\n", "if", "l", ".", "Domains", "==", "nil", "{", "l", ".", "Domains", "=", "make", "(", "map", "[", "string", "]", "Translator", ")", "\n", "}", "\n", "if", "l", ".", "defaultDomain", "==", "\"", "\"", "{", "l", ".", "defaultDomain", "=", "dom", "\n", "}", "\n", "l", ".", "Domains", "[", "dom", "]", "=", "poObj", "\n\n", "// Unlock \"Save new domain\"", "l", ".", "Unlock", "(", ")", "\n", "}" ]
// AddDomain creates a new domain for a given locale object and initializes the Po object. // If the domain exists, it gets reloaded.
[ "AddDomain", "creates", "a", "new", "domain", "for", "a", "given", "locale", "object", "and", "initializes", "the", "Po", "object", ".", "If", "the", "domain", "exists", "it", "gets", "reloaded", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/locale.go#L105-L138
455
leonelquinteros/gotext
locale.go
AddTranslator
func (l *Locale) AddTranslator(dom string, tr Translator) { l.Lock() if l.Domains == nil { l.Domains = make(map[string]Translator) } if l.defaultDomain == "" { l.defaultDomain = dom } l.Domains[dom] = tr l.Unlock() }
go
func (l *Locale) AddTranslator(dom string, tr Translator) { l.Lock() if l.Domains == nil { l.Domains = make(map[string]Translator) } if l.defaultDomain == "" { l.defaultDomain = dom } l.Domains[dom] = tr l.Unlock() }
[ "func", "(", "l", "*", "Locale", ")", "AddTranslator", "(", "dom", "string", ",", "tr", "Translator", ")", "{", "l", ".", "Lock", "(", ")", "\n\n", "if", "l", ".", "Domains", "==", "nil", "{", "l", ".", "Domains", "=", "make", "(", "map", "[", "string", "]", "Translator", ")", "\n", "}", "\n", "if", "l", ".", "defaultDomain", "==", "\"", "\"", "{", "l", ".", "defaultDomain", "=", "dom", "\n", "}", "\n", "l", ".", "Domains", "[", "dom", "]", "=", "tr", "\n\n", "l", ".", "Unlock", "(", ")", "\n", "}" ]
// AddTranslator takes a domain name and a Translator object to make it available in the Locale object.
[ "AddTranslator", "takes", "a", "domain", "name", "and", "a", "Translator", "object", "to", "make", "it", "available", "in", "the", "Locale", "object", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/locale.go#L141-L153
456
leonelquinteros/gotext
locale.go
GetDomain
func (l *Locale) GetDomain() string { l.RLock() dom := l.defaultDomain l.RUnlock() return dom }
go
func (l *Locale) GetDomain() string { l.RLock() dom := l.defaultDomain l.RUnlock() return dom }
[ "func", "(", "l", "*", "Locale", ")", "GetDomain", "(", ")", "string", "{", "l", ".", "RLock", "(", ")", "\n", "dom", ":=", "l", ".", "defaultDomain", "\n", "l", ".", "RUnlock", "(", ")", "\n", "return", "dom", "\n", "}" ]
// GetDomain is the domain getter for Locale configuration
[ "GetDomain", "is", "the", "domain", "getter", "for", "Locale", "configuration" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/locale.go#L156-L161
457
leonelquinteros/gotext
locale.go
SetDomain
func (l *Locale) SetDomain(dom string) { l.Lock() l.defaultDomain = dom l.Unlock() }
go
func (l *Locale) SetDomain(dom string) { l.Lock() l.defaultDomain = dom l.Unlock() }
[ "func", "(", "l", "*", "Locale", ")", "SetDomain", "(", "dom", "string", ")", "{", "l", ".", "Lock", "(", ")", "\n", "l", ".", "defaultDomain", "=", "dom", "\n", "l", ".", "Unlock", "(", ")", "\n", "}" ]
// SetDomain sets the name for the domain to be used.
[ "SetDomain", "sets", "the", "name", "for", "the", "domain", "to", "be", "used", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/locale.go#L164-L168
458
leonelquinteros/gotext
locale.go
MarshalBinary
func (l *Locale) MarshalBinary() ([]byte, error) { obj := new(LocaleEncoding) obj.DefaultDomain = l.defaultDomain obj.Domains = make(map[string][]byte) for k, v := range l.Domains { var err error obj.Domains[k], err = v.MarshalBinary() if err != nil { return nil, err } } obj.Lang = l.lang obj.Path = l.path var buff bytes.Buffer encoder := gob.NewEncoder(&buff) err := encoder.Encode(obj) return buff.Bytes(), err }
go
func (l *Locale) MarshalBinary() ([]byte, error) { obj := new(LocaleEncoding) obj.DefaultDomain = l.defaultDomain obj.Domains = make(map[string][]byte) for k, v := range l.Domains { var err error obj.Domains[k], err = v.MarshalBinary() if err != nil { return nil, err } } obj.Lang = l.lang obj.Path = l.path var buff bytes.Buffer encoder := gob.NewEncoder(&buff) err := encoder.Encode(obj) return buff.Bytes(), err }
[ "func", "(", "l", "*", "Locale", ")", "MarshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "obj", ":=", "new", "(", "LocaleEncoding", ")", "\n", "obj", ".", "DefaultDomain", "=", "l", ".", "defaultDomain", "\n", "obj", ".", "Domains", "=", "make", "(", "map", "[", "string", "]", "[", "]", "byte", ")", "\n", "for", "k", ",", "v", ":=", "range", "l", ".", "Domains", "{", "var", "err", "error", "\n", "obj", ".", "Domains", "[", "k", "]", ",", "err", "=", "v", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "obj", ".", "Lang", "=", "l", ".", "lang", "\n", "obj", ".", "Path", "=", "l", ".", "path", "\n\n", "var", "buff", "bytes", ".", "Buffer", "\n", "encoder", ":=", "gob", ".", "NewEncoder", "(", "&", "buff", ")", "\n", "err", ":=", "encoder", ".", "Encode", "(", "obj", ")", "\n\n", "return", "buff", ".", "Bytes", "(", ")", ",", "err", "\n", "}" ]
// MarshalBinary implements encoding BinaryMarshaler interface
[ "MarshalBinary", "implements", "encoding", "BinaryMarshaler", "interface" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/locale.go#L253-L272
459
leonelquinteros/gotext
locale.go
UnmarshalBinary
func (l *Locale) UnmarshalBinary(data []byte) error { buff := bytes.NewBuffer(data) obj := new(LocaleEncoding) decoder := gob.NewDecoder(buff) err := decoder.Decode(obj) if err != nil { return err } l.defaultDomain = obj.DefaultDomain l.lang = obj.Lang l.path = obj.Path // Decode Domains l.Domains = make(map[string]Translator) for k, v := range obj.Domains { var tr TranslatorEncoding buff := bytes.NewBuffer(v) trDecoder := gob.NewDecoder(buff) err := trDecoder.Decode(&tr) if err != nil { return err } l.Domains[k] = tr.GetTranslator() } return nil }
go
func (l *Locale) UnmarshalBinary(data []byte) error { buff := bytes.NewBuffer(data) obj := new(LocaleEncoding) decoder := gob.NewDecoder(buff) err := decoder.Decode(obj) if err != nil { return err } l.defaultDomain = obj.DefaultDomain l.lang = obj.Lang l.path = obj.Path // Decode Domains l.Domains = make(map[string]Translator) for k, v := range obj.Domains { var tr TranslatorEncoding buff := bytes.NewBuffer(v) trDecoder := gob.NewDecoder(buff) err := trDecoder.Decode(&tr) if err != nil { return err } l.Domains[k] = tr.GetTranslator() } return nil }
[ "func", "(", "l", "*", "Locale", ")", "UnmarshalBinary", "(", "data", "[", "]", "byte", ")", "error", "{", "buff", ":=", "bytes", ".", "NewBuffer", "(", "data", ")", "\n", "obj", ":=", "new", "(", "LocaleEncoding", ")", "\n\n", "decoder", ":=", "gob", ".", "NewDecoder", "(", "buff", ")", "\n", "err", ":=", "decoder", ".", "Decode", "(", "obj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "l", ".", "defaultDomain", "=", "obj", ".", "DefaultDomain", "\n", "l", ".", "lang", "=", "obj", ".", "Lang", "\n", "l", ".", "path", "=", "obj", ".", "Path", "\n\n", "// Decode Domains", "l", ".", "Domains", "=", "make", "(", "map", "[", "string", "]", "Translator", ")", "\n", "for", "k", ",", "v", ":=", "range", "obj", ".", "Domains", "{", "var", "tr", "TranslatorEncoding", "\n", "buff", ":=", "bytes", ".", "NewBuffer", "(", "v", ")", "\n", "trDecoder", ":=", "gob", ".", "NewDecoder", "(", "buff", ")", "\n", "err", ":=", "trDecoder", ".", "Decode", "(", "&", "tr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "l", ".", "Domains", "[", "k", "]", "=", "tr", ".", "GetTranslator", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalBinary implements encoding BinaryUnmarshaler interface
[ "UnmarshalBinary", "implements", "encoding", "BinaryUnmarshaler", "interface" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/locale.go#L275-L304
460
leonelquinteros/gotext
translator.go
GetTranslator
func (te *TranslatorEncoding) GetTranslator() Translator { po := new(Po) po.Headers = te.Headers po.Language = te.Language po.PluralForms = te.PluralForms po.nplurals = te.Nplurals po.plural = te.Plural po.translations = te.Translations po.contexts = te.Contexts return po }
go
func (te *TranslatorEncoding) GetTranslator() Translator { po := new(Po) po.Headers = te.Headers po.Language = te.Language po.PluralForms = te.PluralForms po.nplurals = te.Nplurals po.plural = te.Plural po.translations = te.Translations po.contexts = te.Contexts return po }
[ "func", "(", "te", "*", "TranslatorEncoding", ")", "GetTranslator", "(", ")", "Translator", "{", "po", ":=", "new", "(", "Po", ")", "\n", "po", ".", "Headers", "=", "te", ".", "Headers", "\n", "po", ".", "Language", "=", "te", ".", "Language", "\n", "po", ".", "PluralForms", "=", "te", ".", "PluralForms", "\n", "po", ".", "nplurals", "=", "te", ".", "Nplurals", "\n", "po", ".", "plural", "=", "te", ".", "Plural", "\n", "po", ".", "translations", "=", "te", ".", "Translations", "\n", "po", ".", "contexts", "=", "te", ".", "Contexts", "\n\n", "return", "po", "\n", "}" ]
// GetTranslator is used to recover a Translator object after unmarshaling the TranslatorEncoding object. // Internally uses a Po object as it should be switcheable with Mo objects without problem. // External Translator implementations should be able to serialize into a TranslatorEncoding object in order to unserialize into a Po-compatible object.
[ "GetTranslator", "is", "used", "to", "recover", "a", "Translator", "object", "after", "unmarshaling", "the", "TranslatorEncoding", "object", ".", "Internally", "uses", "a", "Po", "object", "as", "it", "should", "be", "switcheable", "with", "Mo", "objects", "without", "problem", ".", "External", "Translator", "implementations", "should", "be", "able", "to", "serialize", "into", "a", "TranslatorEncoding", "object", "in", "order", "to", "unserialize", "into", "a", "Po", "-", "compatible", "object", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/translator.go#L48-L59
461
leonelquinteros/gotext
helper.go
Printf
func Printf(str string, vars ...interface{}) string { if len(vars) > 0 { return fmt.Sprintf(str, vars...) } return str }
go
func Printf(str string, vars ...interface{}) string { if len(vars) > 0 { return fmt.Sprintf(str, vars...) } return str }
[ "func", "Printf", "(", "str", "string", ",", "vars", "...", "interface", "{", "}", ")", "string", "{", "if", "len", "(", "vars", ")", ">", "0", "{", "return", "fmt", ".", "Sprintf", "(", "str", ",", "vars", "...", ")", "\n", "}", "\n\n", "return", "str", "\n", "}" ]
// Printf applies text formatting only when needed to parse variables.
[ "Printf", "applies", "text", "formatting", "only", "when", "needed", "to", "parse", "variables", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/helper.go#L32-L38
462
leonelquinteros/gotext
plurals/compiler.go
index
func index(tokens []string, sep string) int { for index, token := range tokens { if token == sep { return index } } return -1 }
go
func index(tokens []string, sep string) int { for index, token := range tokens { if token == sep { return index } } return -1 }
[ "func", "index", "(", "tokens", "[", "]", "string", ",", "sep", "string", ")", "int", "{", "for", "index", ",", "token", ":=", "range", "tokens", "{", "if", "token", "==", "sep", "{", "return", "index", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// Find index of token in list of tokens
[ "Find", "index", "of", "token", "in", "list", "of", "tokens" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/plurals/compiler.go#L276-L283
463
leonelquinteros/gotext
plurals/compiler.go
splitTokens
func splitTokens(tokens []string, sep string) (s splitted, err error) { index := index(tokens, sep) if index == -1 { return s, fmt.Errorf("'%s' not found in ['%s']", sep, strings.Join(tokens, "','")) } return splitted{ Left: tokens[:index], Right: tokens[index+1:], }, nil }
go
func splitTokens(tokens []string, sep string) (s splitted, err error) { index := index(tokens, sep) if index == -1 { return s, fmt.Errorf("'%s' not found in ['%s']", sep, strings.Join(tokens, "','")) } return splitted{ Left: tokens[:index], Right: tokens[index+1:], }, nil }
[ "func", "splitTokens", "(", "tokens", "[", "]", "string", ",", "sep", "string", ")", "(", "s", "splitted", ",", "err", "error", ")", "{", "index", ":=", "index", "(", "tokens", ",", "sep", ")", "\n", "if", "index", "==", "-", "1", "{", "return", "s", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sep", ",", "strings", ".", "Join", "(", "tokens", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "splitted", "{", "Left", ":", "tokens", "[", ":", "index", "]", ",", "Right", ":", "tokens", "[", "index", "+", "1", ":", "]", ",", "}", ",", "nil", "\n", "}" ]
// Split a list of tokens by a token into a splitted struct holding the tokens // before and after the token to be split by.
[ "Split", "a", "list", "of", "tokens", "by", "a", "token", "into", "a", "splitted", "struct", "holding", "the", "tokens", "before", "and", "after", "the", "token", "to", "be", "split", "by", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/plurals/compiler.go#L287-L296
464
leonelquinteros/gotext
plurals/compiler.go
scan
func scan(s string) <-chan match { ch := make(chan match) go func() { depth := 0 opener := 0 for index, char := range s { switch char { case '(': if depth == 0 { opener = index } depth++ case ')': depth-- if depth == 0 { ch <- match{ openPos: opener, closePos: index + 1, } } } } close(ch) }() return ch }
go
func scan(s string) <-chan match { ch := make(chan match) go func() { depth := 0 opener := 0 for index, char := range s { switch char { case '(': if depth == 0 { opener = index } depth++ case ')': depth-- if depth == 0 { ch <- match{ openPos: opener, closePos: index + 1, } } } } close(ch) }() return ch }
[ "func", "scan", "(", "s", "string", ")", "<-", "chan", "match", "{", "ch", ":=", "make", "(", "chan", "match", ")", "\n", "go", "func", "(", ")", "{", "depth", ":=", "0", "\n", "opener", ":=", "0", "\n", "for", "index", ",", "char", ":=", "range", "s", "{", "switch", "char", "{", "case", "'('", ":", "if", "depth", "==", "0", "{", "opener", "=", "index", "\n", "}", "\n", "depth", "++", "\n", "case", "')'", ":", "depth", "--", "\n", "if", "depth", "==", "0", "{", "ch", "<-", "match", "{", "openPos", ":", "opener", ",", "closePos", ":", "index", "+", "1", ",", "}", "\n", "}", "\n", "}", "\n\n", "}", "\n", "close", "(", "ch", ")", "\n", "}", "(", ")", "\n", "return", "ch", "\n", "}" ]
// Scan a string for parenthesis
[ "Scan", "a", "string", "for", "parenthesis" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/plurals/compiler.go#L299-L325
465
leonelquinteros/gotext
plurals/compiler.go
split
func split(s string) <-chan string { ch := make(chan string) go func() { s = strings.Replace(s, " ", "", -1) if !strings.Contains(s, "(") { ch <- s } else { last := 0 end := len(s) for info := range scan(s) { if last != info.openPos { ch <- s[last:info.openPos] } ch <- s[info.openPos:info.closePos] last = info.closePos } if last != end { ch <- s[last:] } } close(ch) }() return ch }
go
func split(s string) <-chan string { ch := make(chan string) go func() { s = strings.Replace(s, " ", "", -1) if !strings.Contains(s, "(") { ch <- s } else { last := 0 end := len(s) for info := range scan(s) { if last != info.openPos { ch <- s[last:info.openPos] } ch <- s[info.openPos:info.closePos] last = info.closePos } if last != end { ch <- s[last:] } } close(ch) }() return ch }
[ "func", "split", "(", "s", "string", ")", "<-", "chan", "string", "{", "ch", ":=", "make", "(", "chan", "string", ")", "\n", "go", "func", "(", ")", "{", "s", "=", "strings", ".", "Replace", "(", "s", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "if", "!", "strings", ".", "Contains", "(", "s", ",", "\"", "\"", ")", "{", "ch", "<-", "s", "\n", "}", "else", "{", "last", ":=", "0", "\n", "end", ":=", "len", "(", "s", ")", "\n", "for", "info", ":=", "range", "scan", "(", "s", ")", "{", "if", "last", "!=", "info", ".", "openPos", "{", "ch", "<-", "s", "[", "last", ":", "info", ".", "openPos", "]", "\n", "}", "\n", "ch", "<-", "s", "[", "info", ".", "openPos", ":", "info", ".", "closePos", "]", "\n", "last", "=", "info", ".", "closePos", "\n", "}", "\n", "if", "last", "!=", "end", "{", "ch", "<-", "s", "[", "last", ":", "]", "\n", "}", "\n", "}", "\n", "close", "(", "ch", ")", "\n", "}", "(", ")", "\n", "return", "ch", "\n", "}" ]
// Split the string into tokens
[ "Split", "the", "string", "into", "tokens" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/plurals/compiler.go#L328-L351
466
leonelquinteros/gotext
plurals/compiler.go
Compile
func Compile(s string) (expr Expression, err error) { if s == "0" { return constValue{value: 0}, nil } if !strings.Contains(s, "?") { s += "?1:0" } return compileExpression(s) }
go
func Compile(s string) (expr Expression, err error) { if s == "0" { return constValue{value: 0}, nil } if !strings.Contains(s, "?") { s += "?1:0" } return compileExpression(s) }
[ "func", "Compile", "(", "s", "string", ")", "(", "expr", "Expression", ",", "err", "error", ")", "{", "if", "s", "==", "\"", "\"", "{", "return", "constValue", "{", "value", ":", "0", "}", ",", "nil", "\n", "}", "\n", "if", "!", "strings", ".", "Contains", "(", "s", ",", "\"", "\"", ")", "{", "s", "+=", "\"", "\"", "\n", "}", "\n", "return", "compileExpression", "(", "s", ")", "\n", "}" ]
// Compile a string containing a plural form expression to a Expression object.
[ "Compile", "a", "string", "containing", "a", "plural", "form", "expression", "to", "a", "Expression", "object", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/plurals/compiler.go#L383-L391
467
leonelquinteros/gotext
gotext.go
loadStorage
func loadStorage(force bool) { globalConfig.Lock() if globalConfig.storage == nil || force { globalConfig.storage = NewLocale(globalConfig.library, globalConfig.language) } if _, ok := globalConfig.storage.Domains[globalConfig.domain]; !ok || force { globalConfig.storage.AddDomain(globalConfig.domain) } globalConfig.storage.SetDomain(globalConfig.domain) globalConfig.Unlock() }
go
func loadStorage(force bool) { globalConfig.Lock() if globalConfig.storage == nil || force { globalConfig.storage = NewLocale(globalConfig.library, globalConfig.language) } if _, ok := globalConfig.storage.Domains[globalConfig.domain]; !ok || force { globalConfig.storage.AddDomain(globalConfig.domain) } globalConfig.storage.SetDomain(globalConfig.domain) globalConfig.Unlock() }
[ "func", "loadStorage", "(", "force", "bool", ")", "{", "globalConfig", ".", "Lock", "(", ")", "\n\n", "if", "globalConfig", ".", "storage", "==", "nil", "||", "force", "{", "globalConfig", ".", "storage", "=", "NewLocale", "(", "globalConfig", ".", "library", ",", "globalConfig", ".", "language", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "globalConfig", ".", "storage", ".", "Domains", "[", "globalConfig", ".", "domain", "]", ";", "!", "ok", "||", "force", "{", "globalConfig", ".", "storage", ".", "AddDomain", "(", "globalConfig", ".", "domain", ")", "\n", "}", "\n", "globalConfig", ".", "storage", ".", "SetDomain", "(", "globalConfig", ".", "domain", ")", "\n\n", "globalConfig", ".", "Unlock", "(", ")", "\n", "}" ]
// loadStorage creates a new Locale object at package level based on the Global variables settings. // It's called automatically when trying to use Get or GetD methods.
[ "loadStorage", "creates", "a", "new", "Locale", "object", "at", "package", "level", "based", "on", "the", "Global", "variables", "settings", ".", "It", "s", "called", "automatically", "when", "trying", "to", "use", "Get", "or", "GetD", "methods", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/gotext.go#L64-L77
468
leonelquinteros/gotext
gotext.go
GetDomain
func GetDomain() string { var dom string globalConfig.RLock() if globalConfig.storage != nil { dom = globalConfig.storage.GetDomain() } if dom == "" { dom = globalConfig.domain } globalConfig.RUnlock() return dom }
go
func GetDomain() string { var dom string globalConfig.RLock() if globalConfig.storage != nil { dom = globalConfig.storage.GetDomain() } if dom == "" { dom = globalConfig.domain } globalConfig.RUnlock() return dom }
[ "func", "GetDomain", "(", ")", "string", "{", "var", "dom", "string", "\n", "globalConfig", ".", "RLock", "(", ")", "\n", "if", "globalConfig", ".", "storage", "!=", "nil", "{", "dom", "=", "globalConfig", ".", "storage", ".", "GetDomain", "(", ")", "\n", "}", "\n", "if", "dom", "==", "\"", "\"", "{", "dom", "=", "globalConfig", ".", "domain", "\n", "}", "\n", "globalConfig", ".", "RUnlock", "(", ")", "\n\n", "return", "dom", "\n", "}" ]
// GetDomain is the domain getter for the package configuration
[ "GetDomain", "is", "the", "domain", "getter", "for", "the", "package", "configuration" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/gotext.go#L80-L92
469
leonelquinteros/gotext
gotext.go
SetDomain
func SetDomain(dom string) { globalConfig.Lock() globalConfig.domain = dom if globalConfig.storage != nil { globalConfig.storage.SetDomain(dom) } globalConfig.Unlock() loadStorage(true) }
go
func SetDomain(dom string) { globalConfig.Lock() globalConfig.domain = dom if globalConfig.storage != nil { globalConfig.storage.SetDomain(dom) } globalConfig.Unlock() loadStorage(true) }
[ "func", "SetDomain", "(", "dom", "string", ")", "{", "globalConfig", ".", "Lock", "(", ")", "\n", "globalConfig", ".", "domain", "=", "dom", "\n", "if", "globalConfig", ".", "storage", "!=", "nil", "{", "globalConfig", ".", "storage", ".", "SetDomain", "(", "dom", ")", "\n", "}", "\n", "globalConfig", ".", "Unlock", "(", ")", "\n\n", "loadStorage", "(", "true", ")", "\n", "}" ]
// SetDomain sets the name for the domain to be used at package level. // It reloads the corresponding Translation file.
[ "SetDomain", "sets", "the", "name", "for", "the", "domain", "to", "be", "used", "at", "package", "level", ".", "It", "reloads", "the", "corresponding", "Translation", "file", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/gotext.go#L96-L105
470
leonelquinteros/gotext
gotext.go
GetLanguage
func GetLanguage() string { globalConfig.RLock() lang := globalConfig.language globalConfig.RUnlock() return lang }
go
func GetLanguage() string { globalConfig.RLock() lang := globalConfig.language globalConfig.RUnlock() return lang }
[ "func", "GetLanguage", "(", ")", "string", "{", "globalConfig", ".", "RLock", "(", ")", "\n", "lang", ":=", "globalConfig", ".", "language", "\n", "globalConfig", ".", "RUnlock", "(", ")", "\n\n", "return", "lang", "\n", "}" ]
// GetLanguage is the language getter for the package configuration
[ "GetLanguage", "is", "the", "language", "getter", "for", "the", "package", "configuration" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/gotext.go#L108-L114
471
leonelquinteros/gotext
gotext.go
SetLanguage
func SetLanguage(lang string) { globalConfig.Lock() globalConfig.language = SimplifiedLocale(lang) globalConfig.Unlock() loadStorage(true) }
go
func SetLanguage(lang string) { globalConfig.Lock() globalConfig.language = SimplifiedLocale(lang) globalConfig.Unlock() loadStorage(true) }
[ "func", "SetLanguage", "(", "lang", "string", ")", "{", "globalConfig", ".", "Lock", "(", ")", "\n", "globalConfig", ".", "language", "=", "SimplifiedLocale", "(", "lang", ")", "\n", "globalConfig", ".", "Unlock", "(", ")", "\n\n", "loadStorage", "(", "true", ")", "\n", "}" ]
// SetLanguage sets the language code to be used at package level. // It reloads the corresponding Translation file.
[ "SetLanguage", "sets", "the", "language", "code", "to", "be", "used", "at", "package", "level", ".", "It", "reloads", "the", "corresponding", "Translation", "file", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/gotext.go#L118-L124
472
leonelquinteros/gotext
gotext.go
GetLibrary
func GetLibrary() string { globalConfig.RLock() lib := globalConfig.library globalConfig.RUnlock() return lib }
go
func GetLibrary() string { globalConfig.RLock() lib := globalConfig.library globalConfig.RUnlock() return lib }
[ "func", "GetLibrary", "(", ")", "string", "{", "globalConfig", ".", "RLock", "(", ")", "\n", "lib", ":=", "globalConfig", ".", "library", "\n", "globalConfig", ".", "RUnlock", "(", ")", "\n\n", "return", "lib", "\n", "}" ]
// GetLibrary is the library getter for the package configuration
[ "GetLibrary", "is", "the", "library", "getter", "for", "the", "package", "configuration" ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/gotext.go#L127-L133
473
leonelquinteros/gotext
gotext.go
SetLibrary
func SetLibrary(lib string) { globalConfig.Lock() globalConfig.library = lib globalConfig.Unlock() loadStorage(true) }
go
func SetLibrary(lib string) { globalConfig.Lock() globalConfig.library = lib globalConfig.Unlock() loadStorage(true) }
[ "func", "SetLibrary", "(", "lib", "string", ")", "{", "globalConfig", ".", "Lock", "(", ")", "\n", "globalConfig", ".", "library", "=", "lib", "\n", "globalConfig", ".", "Unlock", "(", ")", "\n\n", "loadStorage", "(", "true", ")", "\n", "}" ]
// SetLibrary sets the root path for the loale directories and files to be used at package level. // It reloads the corresponding Translation file.
[ "SetLibrary", "sets", "the", "root", "path", "for", "the", "loale", "directories", "and", "files", "to", "be", "used", "at", "package", "level", ".", "It", "reloads", "the", "corresponding", "Translation", "file", "." ]
6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f
https://github.com/leonelquinteros/gotext/blob/6431cb3aeab2ec99af31c6a0cee11ae4e8c9b05f/gotext.go#L137-L143
474
mholt/binding
binding.go
Bind
func Bind(req *http.Request, userStruct FieldMapper) error { var errs Errors contentType := req.Header.Get("Content-Type") if strings.Contains(contentType, "form-urlencoded") { return Form(req, userStruct) } if strings.Contains(contentType, "multipart/form-data") { return MultipartForm(req, userStruct) } if strings.Contains(contentType, "json") { return Json(req, userStruct) } if req.Method == http.MethodGet || req.Method == http.MethodHead || (contentType == "" && len(req.URL.Query()) > 0) { return URL(req, userStruct) } if contentType == "" { errs.Add([]string{}, ContentTypeError, "Empty Content-Type") errs = validate(errs, req, userStruct) } else { errs.Add([]string{}, ContentTypeError, "Unsupported Content-Type") } if len(errs) > 0 { return errs } return nil }
go
func Bind(req *http.Request, userStruct FieldMapper) error { var errs Errors contentType := req.Header.Get("Content-Type") if strings.Contains(contentType, "form-urlencoded") { return Form(req, userStruct) } if strings.Contains(contentType, "multipart/form-data") { return MultipartForm(req, userStruct) } if strings.Contains(contentType, "json") { return Json(req, userStruct) } if req.Method == http.MethodGet || req.Method == http.MethodHead || (contentType == "" && len(req.URL.Query()) > 0) { return URL(req, userStruct) } if contentType == "" { errs.Add([]string{}, ContentTypeError, "Empty Content-Type") errs = validate(errs, req, userStruct) } else { errs.Add([]string{}, ContentTypeError, "Unsupported Content-Type") } if len(errs) > 0 { return errs } return nil }
[ "func", "Bind", "(", "req", "*", "http", ".", "Request", ",", "userStruct", "FieldMapper", ")", "error", "{", "var", "errs", "Errors", "\n\n", "contentType", ":=", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n\n", "if", "strings", ".", "Contains", "(", "contentType", ",", "\"", "\"", ")", "{", "return", "Form", "(", "req", ",", "userStruct", ")", "\n", "}", "\n\n", "if", "strings", ".", "Contains", "(", "contentType", ",", "\"", "\"", ")", "{", "return", "MultipartForm", "(", "req", ",", "userStruct", ")", "\n", "}", "\n\n", "if", "strings", ".", "Contains", "(", "contentType", ",", "\"", "\"", ")", "{", "return", "Json", "(", "req", ",", "userStruct", ")", "\n", "}", "\n\n", "if", "req", ".", "Method", "==", "http", ".", "MethodGet", "||", "req", ".", "Method", "==", "http", ".", "MethodHead", "||", "(", "contentType", "==", "\"", "\"", "&&", "len", "(", "req", ".", "URL", ".", "Query", "(", ")", ")", ">", "0", ")", "{", "return", "URL", "(", "req", ",", "userStruct", ")", "\n", "}", "\n\n", "if", "contentType", "==", "\"", "\"", "{", "errs", ".", "Add", "(", "[", "]", "string", "{", "}", ",", "ContentTypeError", ",", "\"", "\"", ")", "\n", "errs", "=", "validate", "(", "errs", ",", "req", ",", "userStruct", ")", "\n", "}", "else", "{", "errs", ".", "Add", "(", "[", "]", "string", "{", "}", ",", "ContentTypeError", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "errs", ")", ">", "0", "{", "return", "errs", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Bind takes data out of the request and deserializes into a struct according // to the Content-Type of the request. If no Content-Type is specified, there // better be data in the query string, otherwise an error will be produced. // // A non-nil return value may be an Errors value.
[ "Bind", "takes", "data", "out", "of", "the", "request", "and", "deserializes", "into", "a", "struct", "according", "to", "the", "Content", "-", "Type", "of", "the", "request", ".", "If", "no", "Content", "-", "Type", "is", "specified", "there", "better", "be", "data", "in", "the", "query", "string", "otherwise", "an", "error", "will", "be", "produced", ".", "A", "non", "-", "nil", "return", "value", "may", "be", "an", "Errors", "value", "." ]
f4f58459f5f7f67cb8fb4a72a905a4ca63fead83
https://github.com/mholt/binding/blob/f4f58459f5f7f67cb8fb4a72a905a4ca63fead83/binding.go#L24-L56
475
mholt/binding
binding.go
Form
func Form(req *http.Request, userStruct FieldMapper) error { err := formBinder(req, userStruct) if len(err) > 0 { return err } return nil }
go
func Form(req *http.Request, userStruct FieldMapper) error { err := formBinder(req, userStruct) if len(err) > 0 { return err } return nil }
[ "func", "Form", "(", "req", "*", "http", ".", "Request", ",", "userStruct", "FieldMapper", ")", "error", "{", "err", ":=", "formBinder", "(", "req", ",", "userStruct", ")", "\n", "if", "len", "(", "err", ")", ">", "0", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Form deserializes form data out of the request into a struct you provide. // This function invokes data validation after deserialization.
[ "Form", "deserializes", "form", "data", "out", "of", "the", "request", "into", "a", "struct", "you", "provide", ".", "This", "function", "invokes", "data", "validation", "after", "deserialization", "." ]
f4f58459f5f7f67cb8fb4a72a905a4ca63fead83
https://github.com/mholt/binding/blob/f4f58459f5f7f67cb8fb4a72a905a4ca63fead83/binding.go#L60-L66
476
mholt/binding
binding.go
URL
func URL(req *http.Request, userStruct FieldMapper) error { err := urlBinder(req, userStruct) if len(err) > 0 { return err } return nil }
go
func URL(req *http.Request, userStruct FieldMapper) error { err := urlBinder(req, userStruct) if len(err) > 0 { return err } return nil }
[ "func", "URL", "(", "req", "*", "http", ".", "Request", ",", "userStruct", "FieldMapper", ")", "error", "{", "err", ":=", "urlBinder", "(", "req", ",", "userStruct", ")", "\n", "if", "len", "(", "err", ")", ">", "0", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n\n", "}" ]
// URL reads data out of the query string into a struct you provide. // This function invokes data validation after deserialization.
[ "URL", "reads", "data", "out", "of", "the", "query", "string", "into", "a", "struct", "you", "provide", ".", "This", "function", "invokes", "data", "validation", "after", "deserialization", "." ]
f4f58459f5f7f67cb8fb4a72a905a4ca63fead83
https://github.com/mholt/binding/blob/f4f58459f5f7f67cb8fb4a72a905a4ca63fead83/binding.go#L84-L91
477
mholt/binding
binding.go
Validate
func Validate(req *http.Request, userStruct FieldMapper) error { err := validate(Errors{}, req, userStruct) if len(err) > 0 { return err } return nil }
go
func Validate(req *http.Request, userStruct FieldMapper) error { err := validate(Errors{}, req, userStruct) if len(err) > 0 { return err } return nil }
[ "func", "Validate", "(", "req", "*", "http", ".", "Request", ",", "userStruct", "FieldMapper", ")", "error", "{", "err", ":=", "validate", "(", "Errors", "{", "}", ",", "req", ",", "userStruct", ")", "\n", "if", "len", "(", "err", ")", ">", "0", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate ensures that all conditions have been met on every field in the // populated struct. Validation should occur after the request has been // deserialized into the struct.
[ "Validate", "ensures", "that", "all", "conditions", "have", "been", "met", "on", "every", "field", "in", "the", "populated", "struct", ".", "Validation", "should", "occur", "after", "the", "request", "has", "been", "deserialized", "into", "the", "struct", "." ]
f4f58459f5f7f67cb8fb4a72a905a4ca63fead83
https://github.com/mholt/binding/blob/f4f58459f5f7f67cb8fb4a72a905a4ca63fead83/binding.go#L173-L180
478
mholt/binding
errors.go
Add
func (e *Errors) Add(fieldNames []string, kind, message string) { *e = append(*e, NewError(fieldNames, kind, message)) }
go
func (e *Errors) Add(fieldNames []string, kind, message string) { *e = append(*e, NewError(fieldNames, kind, message)) }
[ "func", "(", "e", "*", "Errors", ")", "Add", "(", "fieldNames", "[", "]", "string", ",", "kind", ",", "message", "string", ")", "{", "*", "e", "=", "append", "(", "*", "e", ",", "NewError", "(", "fieldNames", ",", "kind", ",", "message", ")", ")", "\n", "}" ]
// Add adds an Error associated with the fields indicated by fieldNames, with // the given kind and message. // // Use a fieldNames value of length 0 to indicate that the error is about the // request as a whole, and not necessarily any of the fields. // // kind should be a string that can be used like an error code to process or // categorize the error being added. // // message should be human-readable and detailed enough to pinpoint and resolve // the problem, but it should be brief. For example, a payload of 100 objects // in a JSON array might have an error in the 41st object. The message should // help the end user find and fix the error with their request.
[ "Add", "adds", "an", "Error", "associated", "with", "the", "fields", "indicated", "by", "fieldNames", "with", "the", "given", "kind", "and", "message", ".", "Use", "a", "fieldNames", "value", "of", "length", "0", "to", "indicate", "that", "the", "error", "is", "about", "the", "request", "as", "a", "whole", "and", "not", "necessarily", "any", "of", "the", "fields", ".", "kind", "should", "be", "a", "string", "that", "can", "be", "used", "like", "an", "error", "code", "to", "process", "or", "categorize", "the", "error", "being", "added", ".", "message", "should", "be", "human", "-", "readable", "and", "detailed", "enough", "to", "pinpoint", "and", "resolve", "the", "problem", "but", "it", "should", "be", "brief", ".", "For", "example", "a", "payload", "of", "100", "objects", "in", "a", "JSON", "array", "might", "have", "an", "error", "in", "the", "41st", "object", ".", "The", "message", "should", "help", "the", "end", "user", "find", "and", "fix", "the", "error", "with", "their", "request", "." ]
f4f58459f5f7f67cb8fb4a72a905a4ca63fead83
https://github.com/mholt/binding/blob/f4f58459f5f7f67cb8fb4a72a905a4ca63fead83/errors.go#L68-L70
479
mholt/binding
errors.go
Error
func (e Errors) Error() string { messages := []string{} for _, err := range e { messages = append(messages, err.Message()) } return strings.Join(messages, "\n") }
go
func (e Errors) Error() string { messages := []string{} for _, err := range e { messages = append(messages, err.Message()) } return strings.Join(messages, "\n") }
[ "func", "(", "e", "Errors", ")", "Error", "(", ")", "string", "{", "messages", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "err", ":=", "range", "e", "{", "messages", "=", "append", "(", "messages", ",", "err", ".", "Message", "(", ")", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "messages", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// Error returns a concatenation of all its error messages.
[ "Error", "returns", "a", "concatenation", "of", "all", "its", "error", "messages", "." ]
f4f58459f5f7f67cb8fb4a72a905a4ca63fead83
https://github.com/mholt/binding/blob/f4f58459f5f7f67cb8fb4a72a905a4ca63fead83/errors.go#L89-L95
480
aymerick/raymond
helper.go
RegisterHelper
func RegisterHelper(name string, helper interface{}) { helpersMutex.Lock() defer helpersMutex.Unlock() if helpers[name] != zero { panic(fmt.Errorf("Helper already registered: %s", name)) } val := reflect.ValueOf(helper) ensureValidHelper(name, val) helpers[name] = val }
go
func RegisterHelper(name string, helper interface{}) { helpersMutex.Lock() defer helpersMutex.Unlock() if helpers[name] != zero { panic(fmt.Errorf("Helper already registered: %s", name)) } val := reflect.ValueOf(helper) ensureValidHelper(name, val) helpers[name] = val }
[ "func", "RegisterHelper", "(", "name", "string", ",", "helper", "interface", "{", "}", ")", "{", "helpersMutex", ".", "Lock", "(", ")", "\n", "defer", "helpersMutex", ".", "Unlock", "(", ")", "\n\n", "if", "helpers", "[", "name", "]", "!=", "zero", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n\n", "val", ":=", "reflect", ".", "ValueOf", "(", "helper", ")", "\n", "ensureValidHelper", "(", "name", ",", "val", ")", "\n\n", "helpers", "[", "name", "]", "=", "val", "\n", "}" ]
// RegisterHelper registers a global helper. That helper will be available to all templates.
[ "RegisterHelper", "registers", "a", "global", "helper", ".", "That", "helper", "will", "be", "available", "to", "all", "templates", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L38-L50
481
aymerick/raymond
helper.go
RemoveHelper
func RemoveHelper(name string) { helpersMutex.Lock() defer helpersMutex.Unlock() delete(helpers, name) }
go
func RemoveHelper(name string) { helpersMutex.Lock() defer helpersMutex.Unlock() delete(helpers, name) }
[ "func", "RemoveHelper", "(", "name", "string", ")", "{", "helpersMutex", ".", "Lock", "(", ")", "\n", "defer", "helpersMutex", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "helpers", ",", "name", ")", "\n", "}" ]
// RemoveHelper unregisters a global helper
[ "RemoveHelper", "unregisters", "a", "global", "helper" ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L60-L65
482
aymerick/raymond
helper.go
RemoveAllHelpers
func RemoveAllHelpers() { helpersMutex.Lock() defer helpersMutex.Unlock() helpers = make(map[string]reflect.Value) }
go
func RemoveAllHelpers() { helpersMutex.Lock() defer helpersMutex.Unlock() helpers = make(map[string]reflect.Value) }
[ "func", "RemoveAllHelpers", "(", ")", "{", "helpersMutex", ".", "Lock", "(", ")", "\n", "defer", "helpersMutex", ".", "Unlock", "(", ")", "\n\n", "helpers", "=", "make", "(", "map", "[", "string", "]", "reflect", ".", "Value", ")", "\n", "}" ]
// RemoveAllHelpers unregisters all global helpers
[ "RemoveAllHelpers", "unregisters", "all", "global", "helpers" ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L68-L73
483
aymerick/raymond
helper.go
ensureValidHelper
func ensureValidHelper(name string, funcValue reflect.Value) { if funcValue.Kind() != reflect.Func { panic(fmt.Errorf("Helper must be a function: %s", name)) } funcType := funcValue.Type() if funcType.NumOut() != 1 { panic(fmt.Errorf("Helper function must return a string or a SafeString: %s", name)) } // @todo Check if first returned value is a string, SafeString or interface{} ? }
go
func ensureValidHelper(name string, funcValue reflect.Value) { if funcValue.Kind() != reflect.Func { panic(fmt.Errorf("Helper must be a function: %s", name)) } funcType := funcValue.Type() if funcType.NumOut() != 1 { panic(fmt.Errorf("Helper function must return a string or a SafeString: %s", name)) } // @todo Check if first returned value is a string, SafeString or interface{} ? }
[ "func", "ensureValidHelper", "(", "name", "string", ",", "funcValue", "reflect", ".", "Value", ")", "{", "if", "funcValue", ".", "Kind", "(", ")", "!=", "reflect", ".", "Func", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n\n", "funcType", ":=", "funcValue", ".", "Type", "(", ")", "\n\n", "if", "funcType", ".", "NumOut", "(", ")", "!=", "1", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n\n", "// @todo Check if first returned value is a string, SafeString or interface{} ?", "}" ]
// ensureValidHelper panics if given helper is not valid
[ "ensureValidHelper", "panics", "if", "given", "helper", "is", "not", "valid" ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L76-L88
484
aymerick/raymond
helper.go
findHelper
func findHelper(name string) reflect.Value { helpersMutex.RLock() defer helpersMutex.RUnlock() return helpers[name] }
go
func findHelper(name string) reflect.Value { helpersMutex.RLock() defer helpersMutex.RUnlock() return helpers[name] }
[ "func", "findHelper", "(", "name", "string", ")", "reflect", ".", "Value", "{", "helpersMutex", ".", "RLock", "(", ")", "\n", "defer", "helpersMutex", ".", "RUnlock", "(", ")", "\n\n", "return", "helpers", "[", "name", "]", "\n", "}" ]
// findHelper finds a globally registered helper
[ "findHelper", "finds", "a", "globally", "registered", "helper" ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L91-L96
485
aymerick/raymond
helper.go
newOptions
func newOptions(eval *evalVisitor, params []interface{}, hash map[string]interface{}) *Options { return &Options{ eval: eval, params: params, hash: hash, } }
go
func newOptions(eval *evalVisitor, params []interface{}, hash map[string]interface{}) *Options { return &Options{ eval: eval, params: params, hash: hash, } }
[ "func", "newOptions", "(", "eval", "*", "evalVisitor", ",", "params", "[", "]", "interface", "{", "}", ",", "hash", "map", "[", "string", "]", "interface", "{", "}", ")", "*", "Options", "{", "return", "&", "Options", "{", "eval", ":", "eval", ",", "params", ":", "params", ",", "hash", ":", "hash", ",", "}", "\n", "}" ]
// newOptions instanciates a new Options
[ "newOptions", "instanciates", "a", "new", "Options" ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L99-L105
486
aymerick/raymond
helper.go
newEmptyOptions
func newEmptyOptions(eval *evalVisitor) *Options { return &Options{ eval: eval, hash: make(map[string]interface{}), } }
go
func newEmptyOptions(eval *evalVisitor) *Options { return &Options{ eval: eval, hash: make(map[string]interface{}), } }
[ "func", "newEmptyOptions", "(", "eval", "*", "evalVisitor", ")", "*", "Options", "{", "return", "&", "Options", "{", "eval", ":", "eval", ",", "hash", ":", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ",", "}", "\n", "}" ]
// newEmptyOptions instanciates a new empty Options
[ "newEmptyOptions", "instanciates", "a", "new", "empty", "Options" ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L108-L113
487
aymerick/raymond
helper.go
Value
func (options *Options) Value(name string) interface{} { value := options.eval.evalField(options.eval.curCtx(), name, false) if !value.IsValid() { return nil } return value.Interface() }
go
func (options *Options) Value(name string) interface{} { value := options.eval.evalField(options.eval.curCtx(), name, false) if !value.IsValid() { return nil } return value.Interface() }
[ "func", "(", "options", "*", "Options", ")", "Value", "(", "name", "string", ")", "interface", "{", "}", "{", "value", ":=", "options", ".", "eval", ".", "evalField", "(", "options", ".", "eval", ".", "curCtx", "(", ")", ",", "name", ",", "false", ")", "\n", "if", "!", "value", ".", "IsValid", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "return", "value", ".", "Interface", "(", ")", "\n", "}" ]
// // Context Values // // Value returns field value from current context.
[ "Context", "Values", "Value", "returns", "field", "value", "from", "current", "context", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L120-L127
488
aymerick/raymond
helper.go
ValueStr
func (options *Options) ValueStr(name string) string { return Str(options.Value(name)) }
go
func (options *Options) ValueStr(name string) string { return Str(options.Value(name)) }
[ "func", "(", "options", "*", "Options", ")", "ValueStr", "(", "name", "string", ")", "string", "{", "return", "Str", "(", "options", ".", "Value", "(", "name", ")", ")", "\n", "}" ]
// ValueStr returns string representation of field value from current context.
[ "ValueStr", "returns", "string", "representation", "of", "field", "value", "from", "current", "context", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L130-L132
489
aymerick/raymond
helper.go
HashStr
func (options *Options) HashStr(name string) string { return Str(options.hash[name]) }
go
func (options *Options) HashStr(name string) string { return Str(options.hash[name]) }
[ "func", "(", "options", "*", "Options", ")", "HashStr", "(", "name", "string", ")", "string", "{", "return", "Str", "(", "options", ".", "hash", "[", "name", "]", ")", "\n", "}" ]
// HashStr returns string representation of hash property.
[ "HashStr", "returns", "string", "representation", "of", "hash", "property", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L149-L151
490
aymerick/raymond
helper.go
Param
func (options *Options) Param(pos int) interface{} { if len(options.params) > pos { return options.params[pos] } return nil }
go
func (options *Options) Param(pos int) interface{} { if len(options.params) > pos { return options.params[pos] } return nil }
[ "func", "(", "options", "*", "Options", ")", "Param", "(", "pos", "int", ")", "interface", "{", "}", "{", "if", "len", "(", "options", ".", "params", ")", ">", "pos", "{", "return", "options", ".", "params", "[", "pos", "]", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// // Parameters // // Param returns parameter at given position.
[ "Parameters", "Param", "returns", "parameter", "at", "given", "position", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L163-L169
491
aymerick/raymond
helper.go
ParamStr
func (options *Options) ParamStr(pos int) string { return Str(options.Param(pos)) }
go
func (options *Options) ParamStr(pos int) string { return Str(options.Param(pos)) }
[ "func", "(", "options", "*", "Options", ")", "ParamStr", "(", "pos", "int", ")", "string", "{", "return", "Str", "(", "options", ".", "Param", "(", "pos", ")", ")", "\n", "}" ]
// ParamStr returns string representation of parameter at given position.
[ "ParamStr", "returns", "string", "representation", "of", "parameter", "at", "given", "position", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L172-L174
492
aymerick/raymond
helper.go
Data
func (options *Options) Data(name string) interface{} { return options.eval.dataFrame.Get(name) }
go
func (options *Options) Data(name string) interface{} { return options.eval.dataFrame.Get(name) }
[ "func", "(", "options", "*", "Options", ")", "Data", "(", "name", "string", ")", "interface", "{", "}", "{", "return", "options", ".", "eval", ".", "dataFrame", ".", "Get", "(", "name", ")", "\n", "}" ]
// // Private data // // Data returns private data value.
[ "Private", "data", "Data", "returns", "private", "data", "value", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L186-L188
493
aymerick/raymond
helper.go
DataStr
func (options *Options) DataStr(name string) string { return Str(options.eval.dataFrame.Get(name)) }
go
func (options *Options) DataStr(name string) string { return Str(options.eval.dataFrame.Get(name)) }
[ "func", "(", "options", "*", "Options", ")", "DataStr", "(", "name", "string", ")", "string", "{", "return", "Str", "(", "options", ".", "eval", ".", "dataFrame", ".", "Get", "(", "name", ")", ")", "\n", "}" ]
// DataStr returns string representation of private data value.
[ "DataStr", "returns", "string", "representation", "of", "private", "data", "value", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L191-L193
494
aymerick/raymond
helper.go
newIterDataFrame
func (options *Options) newIterDataFrame(length int, i int, key interface{}) *DataFrame { return options.eval.dataFrame.newIterDataFrame(length, i, key) }
go
func (options *Options) newIterDataFrame(length int, i int, key interface{}) *DataFrame { return options.eval.dataFrame.newIterDataFrame(length, i, key) }
[ "func", "(", "options", "*", "Options", ")", "newIterDataFrame", "(", "length", "int", ",", "i", "int", ",", "key", "interface", "{", "}", ")", "*", "DataFrame", "{", "return", "options", ".", "eval", ".", "dataFrame", ".", "newIterDataFrame", "(", "length", ",", "i", ",", "key", ")", "\n", "}" ]
// newIterDataFrame instanciates a new data frame and set iteration specific vars
[ "newIterDataFrame", "instanciates", "a", "new", "data", "frame", "and", "set", "iteration", "specific", "vars" ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L208-L210
495
aymerick/raymond
helper.go
evalBlock
func (options *Options) evalBlock(ctx interface{}, data *DataFrame, key interface{}) string { result := "" if block := options.eval.curBlock(); (block != nil) && (block.Program != nil) { result = options.eval.evalProgram(block.Program, ctx, data, key) } return result }
go
func (options *Options) evalBlock(ctx interface{}, data *DataFrame, key interface{}) string { result := "" if block := options.eval.curBlock(); (block != nil) && (block.Program != nil) { result = options.eval.evalProgram(block.Program, ctx, data, key) } return result }
[ "func", "(", "options", "*", "Options", ")", "evalBlock", "(", "ctx", "interface", "{", "}", ",", "data", "*", "DataFrame", ",", "key", "interface", "{", "}", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "if", "block", ":=", "options", ".", "eval", ".", "curBlock", "(", ")", ";", "(", "block", "!=", "nil", ")", "&&", "(", "block", ".", "Program", "!=", "nil", ")", "{", "result", "=", "options", ".", "eval", ".", "evalProgram", "(", "block", ".", "Program", ",", "ctx", ",", "data", ",", "key", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// // Evaluation // // evalBlock evaluates block with given context, private data and iteration key
[ "Evaluation", "evalBlock", "evaluates", "block", "with", "given", "context", "private", "data", "and", "iteration", "key" ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L217-L225
496
aymerick/raymond
helper.go
FnCtxData
func (options *Options) FnCtxData(ctx interface{}, data *DataFrame) string { return options.evalBlock(ctx, data, nil) }
go
func (options *Options) FnCtxData(ctx interface{}, data *DataFrame) string { return options.evalBlock(ctx, data, nil) }
[ "func", "(", "options", "*", "Options", ")", "FnCtxData", "(", "ctx", "interface", "{", "}", ",", "data", "*", "DataFrame", ")", "string", "{", "return", "options", ".", "evalBlock", "(", "ctx", ",", "data", ",", "nil", ")", "\n", "}" ]
// FnCtxData evaluates block with given context and private data frame.
[ "FnCtxData", "evaluates", "block", "with", "given", "context", "and", "private", "data", "frame", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L233-L235
497
aymerick/raymond
helper.go
FnWith
func (options *Options) FnWith(ctx interface{}) string { return options.evalBlock(ctx, nil, nil) }
go
func (options *Options) FnWith(ctx interface{}) string { return options.evalBlock(ctx, nil, nil) }
[ "func", "(", "options", "*", "Options", ")", "FnWith", "(", "ctx", "interface", "{", "}", ")", "string", "{", "return", "options", ".", "evalBlock", "(", "ctx", ",", "nil", ",", "nil", ")", "\n", "}" ]
// FnWith evaluates block with given context.
[ "FnWith", "evaluates", "block", "with", "given", "context", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L238-L240
498
aymerick/raymond
helper.go
FnData
func (options *Options) FnData(data *DataFrame) string { return options.evalBlock(nil, data, nil) }
go
func (options *Options) FnData(data *DataFrame) string { return options.evalBlock(nil, data, nil) }
[ "func", "(", "options", "*", "Options", ")", "FnData", "(", "data", "*", "DataFrame", ")", "string", "{", "return", "options", ".", "evalBlock", "(", "nil", ",", "data", ",", "nil", ")", "\n", "}" ]
// FnData evaluates block with given private data frame.
[ "FnData", "evaluates", "block", "with", "given", "private", "data", "frame", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L243-L245
499
aymerick/raymond
helper.go
Inverse
func (options *Options) Inverse() string { result := "" if block := options.eval.curBlock(); (block != nil) && (block.Inverse != nil) { result, _ = block.Inverse.Accept(options.eval).(string) } return result }
go
func (options *Options) Inverse() string { result := "" if block := options.eval.curBlock(); (block != nil) && (block.Inverse != nil) { result, _ = block.Inverse.Accept(options.eval).(string) } return result }
[ "func", "(", "options", "*", "Options", ")", "Inverse", "(", ")", "string", "{", "result", ":=", "\"", "\"", "\n", "if", "block", ":=", "options", ".", "eval", ".", "curBlock", "(", ")", ";", "(", "block", "!=", "nil", ")", "&&", "(", "block", ".", "Inverse", "!=", "nil", ")", "{", "result", ",", "_", "=", "block", ".", "Inverse", ".", "Accept", "(", "options", ".", "eval", ")", ".", "(", "string", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Inverse evaluates "else block".
[ "Inverse", "evaluates", "else", "block", "." ]
b565731e1464263de0bda75f2e45d97b54b60110
https://github.com/aymerick/raymond/blob/b565731e1464263de0bda75f2e45d97b54b60110/helper.go#L248-L255