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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
mattn/go-gtk | gtk/gtk.go | SelectFilename | func (v *FileChooser) SelectFilename(filename string) bool {
ptr := C.CString(filename)
defer cfree(ptr)
return gobool(C.gtk_file_chooser_select_filename(v.GFileChooser, ptr))
} | go | func (v *FileChooser) SelectFilename(filename string) bool {
ptr := C.CString(filename)
defer cfree(ptr)
return gobool(C.gtk_file_chooser_select_filename(v.GFileChooser, ptr))
} | [
"func",
"(",
"v",
"*",
"FileChooser",
")",
"SelectFilename",
"(",
"filename",
"string",
")",
"bool",
"{",
"ptr",
":=",
"C",
".",
"CString",
"(",
"filename",
")",
"\n",
"defer",
"cfree",
"(",
"ptr",
")",
"\n",
"return",
"gobool",
"(",
"C",
".",
"gtk_f... | // GTK doc said the return value is "Not useful". | [
"GTK",
"doc",
"said",
"the",
"return",
"value",
"is",
"Not",
"useful",
"."
] | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L8113-L8117 | train |
mattn/go-gtk | gtk/gtk.go | Configure | func (v *Adjustment) Configure(value, lower, upper, step_increment, page_increment, page_size float64) {
panic_if_version_older(2, 14, 0, "gtk_adjustment_configure()")
C._gtk_adjustment_configure(v.GAdjustment, gdouble(value), gdouble(lower), gdouble(upper),
gdouble(step_increment), gdouble(page_increment), gdouble(page_size))
} | go | func (v *Adjustment) Configure(value, lower, upper, step_increment, page_increment, page_size float64) {
panic_if_version_older(2, 14, 0, "gtk_adjustment_configure()")
C._gtk_adjustment_configure(v.GAdjustment, gdouble(value), gdouble(lower), gdouble(upper),
gdouble(step_increment), gdouble(page_increment), gdouble(page_size))
} | [
"func",
"(",
"v",
"*",
"Adjustment",
")",
"Configure",
"(",
"value",
",",
"lower",
",",
"upper",
",",
"step_increment",
",",
"page_increment",
",",
"page_size",
"float64",
")",
"{",
"panic_if_version_older",
"(",
"2",
",",
"14",
",",
"0",
",",
"\"",
"\""... | // gtk_adjustment_clamp_page
// gtk_adjustment_changed
// gtk_adjustment_value_changed | [
"gtk_adjustment_clamp_page",
"gtk_adjustment_changed",
"gtk_adjustment_value_changed"
] | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L9687-L9691 | train |
mattn/go-gtk | gtk/gtk.go | NewArrow | func NewArrow(at ArrowType, st ShadowType) *Arrow {
return &Arrow{Widget{C.gtk_arrow_new(C.GtkArrowType(at), C.GtkShadowType(st))}}
} | go | func NewArrow(at ArrowType, st ShadowType) *Arrow {
return &Arrow{Widget{C.gtk_arrow_new(C.GtkArrowType(at), C.GtkShadowType(st))}}
} | [
"func",
"NewArrow",
"(",
"at",
"ArrowType",
",",
"st",
"ShadowType",
")",
"*",
"Arrow",
"{",
"return",
"&",
"Arrow",
"{",
"Widget",
"{",
"C",
".",
"gtk_arrow_new",
"(",
"C",
".",
"GtkArrowType",
"(",
"at",
")",
",",
"C",
".",
"GtkShadowType",
"(",
"s... | // Draw arrowhead facing in given direction with a shadow.
// Like gtk.Label it does not emit signals. | [
"Draw",
"arrowhead",
"facing",
"in",
"given",
"direction",
"with",
"a",
"shadow",
".",
"Like",
"gtk",
".",
"Label",
"it",
"does",
"not",
"emit",
"signals",
"."
] | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L9767-L9769 | train |
mattn/go-gtk | gtk/gtk.go | Set | func (a *Arrow) Set(at ArrowType, st ShadowType) {
C.gtk_arrow_set(ARROW(a), C.GtkArrowType(at), C.GtkShadowType(st))
} | go | func (a *Arrow) Set(at ArrowType, st ShadowType) {
C.gtk_arrow_set(ARROW(a), C.GtkArrowType(at), C.GtkShadowType(st))
} | [
"func",
"(",
"a",
"*",
"Arrow",
")",
"Set",
"(",
"at",
"ArrowType",
",",
"st",
"ShadowType",
")",
"{",
"C",
".",
"gtk_arrow_set",
"(",
"ARROW",
"(",
"a",
")",
",",
"C",
".",
"GtkArrowType",
"(",
"at",
")",
",",
"C",
".",
"GtkShadowType",
"(",
"st... | // Change the arrows direction and shadow. | [
"Change",
"the",
"arrows",
"direction",
"and",
"shadow",
"."
] | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L9772-L9774 | train |
mattn/go-gtk | gtk/gtk.go | EventBoxFromObject | func EventBoxFromObject(object *glib.GObject) *EventBox {
return &EventBox{Bin{Container{Widget{C.toGWidget(object.Object)}}}}
} | go | func EventBoxFromObject(object *glib.GObject) *EventBox {
return &EventBox{Bin{Container{Widget{C.toGWidget(object.Object)}}}}
} | [
"func",
"EventBoxFromObject",
"(",
"object",
"*",
"glib",
".",
"GObject",
")",
"*",
"EventBox",
"{",
"return",
"&",
"EventBox",
"{",
"Bin",
"{",
"Container",
"{",
"Widget",
"{",
"C",
".",
"toGWidget",
"(",
"object",
".",
"Object",
")",
"}",
"}",
"}",
... | //add by xtlx2000 | [
"add",
"by",
"xtlx2000"
] | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L9827-L9829 | train |
mattn/go-gtk | gtk/gtk.go | ChildSet | func (v *Container) ChildSet(w IWidget, propName string, value interface{}) {
ptr := C.CString(propName)
defer cfree(ptr)
switch value.(type) {
case bool:
C._gtk_container_child_set_bool(CONTAINER(v), ToNative(w), gstring(ptr), gbool(value.(bool)))
case int:
C._gtk_container_child_set_int(CONTAINER(v), ToNative(w), gstring(ptr), gint(value.(int)))
}
} | go | func (v *Container) ChildSet(w IWidget, propName string, value interface{}) {
ptr := C.CString(propName)
defer cfree(ptr)
switch value.(type) {
case bool:
C._gtk_container_child_set_bool(CONTAINER(v), ToNative(w), gstring(ptr), gbool(value.(bool)))
case int:
C._gtk_container_child_set_int(CONTAINER(v), ToNative(w), gstring(ptr), gint(value.(int)))
}
} | [
"func",
"(",
"v",
"*",
"Container",
")",
"ChildSet",
"(",
"w",
"IWidget",
",",
"propName",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"ptr",
":=",
"C",
".",
"CString",
"(",
"propName",
")",
"\n",
"defer",
"cfree",
"(",
"ptr",
")",
"\n... | // gtk_container_resize_children
// gtk_container_child_type
// gtk_container_child_get | [
"gtk_container_resize_children",
"gtk_container_child_type",
"gtk_container_child_get"
] | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L10211-L10222 | train |
mattn/go-gtk | gtk/gtk.go | AddAccelerator | func (v *Widget) AddAccelerator(signal string, group *AccelGroup, key uint, mods gdk.ModifierType, flags AccelFlags) {
csignal := C.CString(signal)
defer cfree(csignal)
C.gtk_widget_add_accelerator(v.GWidget, gstring(csignal), group.GAccelGroup, guint(key),
C.GdkModifierType(mods), C.GtkAccelFlags(flags))
} | go | func (v *Widget) AddAccelerator(signal string, group *AccelGroup, key uint, mods gdk.ModifierType, flags AccelFlags) {
csignal := C.CString(signal)
defer cfree(csignal)
C.gtk_widget_add_accelerator(v.GWidget, gstring(csignal), group.GAccelGroup, guint(key),
C.GdkModifierType(mods), C.GtkAccelFlags(flags))
} | [
"func",
"(",
"v",
"*",
"Widget",
")",
"AddAccelerator",
"(",
"signal",
"string",
",",
"group",
"*",
"AccelGroup",
",",
"key",
"uint",
",",
"mods",
"gdk",
".",
"ModifierType",
",",
"flags",
"AccelFlags",
")",
"{",
"csignal",
":=",
"C",
".",
"CString",
"... | // gtk_widget_size_request
// gtk_widget_get_child_requisition
// gtk_widget_size_allocate | [
"gtk_widget_size_request",
"gtk_widget_get_child_requisition",
"gtk_widget_size_allocate"
] | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L10718-L10723 | train |
mattn/go-gtk | gtk/gtk.go | CanActivateAccel | func (v *Widget) CanActivateAccel(signal_id uint) bool {
return gobool(C.gtk_widget_can_activate_accel(v.GWidget, guint(signal_id)))
} | go | func (v *Widget) CanActivateAccel(signal_id uint) bool {
return gobool(C.gtk_widget_can_activate_accel(v.GWidget, guint(signal_id)))
} | [
"func",
"(",
"v",
"*",
"Widget",
")",
"CanActivateAccel",
"(",
"signal_id",
"uint",
")",
"bool",
"{",
"return",
"gobool",
"(",
"C",
".",
"gtk_widget_can_activate_accel",
"(",
"v",
".",
"GWidget",
",",
"guint",
"(",
"signal_id",
")",
")",
")",
"\n",
"}"
] | // gtk_widget_remove_accelerator
// gtk_widget_set_accel_path
// gtk_widget_list_accel_closures | [
"gtk_widget_remove_accelerator",
"gtk_widget_set_accel_path",
"gtk_widget_list_accel_closures"
] | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L10729-L10731 | train |
mattn/go-gtk | gtk/gtk.go | GetPangoContext | func (v *Widget) GetPangoContext() *pango.Context {
return pango.ContextFromUnsafe(unsafe.Pointer(C.gtk_widget_get_pango_context((*C.GtkWidget)(v.GWidget))))
} | go | func (v *Widget) GetPangoContext() *pango.Context {
return pango.ContextFromUnsafe(unsafe.Pointer(C.gtk_widget_get_pango_context((*C.GtkWidget)(v.GWidget))))
} | [
"func",
"(",
"v",
"*",
"Widget",
")",
"GetPangoContext",
"(",
")",
"*",
"pango",
".",
"Context",
"{",
"return",
"pango",
".",
"ContextFromUnsafe",
"(",
"unsafe",
".",
"Pointer",
"(",
"C",
".",
"gtk_widget_get_pango_context",
"(",
"(",
"*",
"C",
".",
"Gtk... | // gtk_widget_reset_rc_styles
// gtk_widget_push_colormap
// gtk_widget_pop_colormap
// gtk_widget_set_default_colormap
// gtk_widget_get_default_style
// gtk_widget_get_default_colormap
// gtk_widget_get_default_visual
// gtk_widget_set_direction
// gtk_widget_get_direction
// gtk_widget_set_default_direction
// gtk_widget_get_default_direction
// gtk_widget_shape_combine_mask
// gtk_widget_input_shape_combine_mask
// gtk_widget_path
// gtk_widget_class_path
// gtk_widget_get_composite_name
// gtk_widget_modify_style
// gtk_widget_get_modifier_style
// gtk_widget_modify_text
// gtk_widget_modify_base
// gtk_widget_modify_cursor
// gtk_widget_create_pango_context
// gtk_widget_get_pango_context | [
"gtk_widget_reset_rc_styles",
"gtk_widget_push_colormap",
"gtk_widget_pop_colormap",
"gtk_widget_set_default_colormap",
"gtk_widget_get_default_style",
"gtk_widget_get_default_colormap",
"gtk_widget_get_default_visual",
"gtk_widget_set_direction",
"gtk_widget_get_direction",
"gtk_widget_set_defaul... | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L10856-L10858 | train |
mattn/go-gtk | gtk/gtk.go | GetSizeRequest | func (v *Widget) GetSizeRequest() (width int, height int) {
var w, h C.gint
C.gtk_widget_get_size_request(v.GWidget, &w, &h)
return int(w), int(h)
} | go | func (v *Widget) GetSizeRequest() (width int, height int) {
var w, h C.gint
C.gtk_widget_get_size_request(v.GWidget, &w, &h)
return int(w), int(h)
} | [
"func",
"(",
"v",
"*",
"Widget",
")",
"GetSizeRequest",
"(",
")",
"(",
"width",
"int",
",",
"height",
"int",
")",
"{",
"var",
"w",
",",
"h",
"C",
".",
"gint",
"\n",
"C",
".",
"gtk_widget_get_size_request",
"(",
"v",
".",
"GWidget",
",",
"&",
"w",
... | // gtk_widget_get_clipboard
// gtk_widget_get_display
// gtk_widget_get_root_window
// gtk_widget_get_screen
// gtk_widget_has_screen | [
"gtk_widget_get_clipboard",
"gtk_widget_get_display",
"gtk_widget_get_root_window",
"gtk_widget_get_screen",
"gtk_widget_has_screen"
] | 4deadb416788be678fb9cac22ea76dba83c946b0 | https://github.com/mattn/go-gtk/blob/4deadb416788be678fb9cac22ea76dba83c946b0/gtk/gtk.go#L10938-L10942 | train |
tjfoc/gmsm | sm2/pkcs7.go | UnmarshalSignedAttribute | func (p7 *PKCS7) UnmarshalSignedAttribute(attributeType asn1.ObjectIdentifier, out interface{}) error {
sd, ok := p7.raw.(signedData)
if !ok {
return errors.New("pkcs7: payload is not signedData content")
}
if len(sd.SignerInfos) < 1 {
return errors.New("pkcs7: payload has no signers")
}
attributes := sd.SignerInfos[0].AuthenticatedAttributes
return unmarshalAttribute(attributes, attributeType, out)
} | go | func (p7 *PKCS7) UnmarshalSignedAttribute(attributeType asn1.ObjectIdentifier, out interface{}) error {
sd, ok := p7.raw.(signedData)
if !ok {
return errors.New("pkcs7: payload is not signedData content")
}
if len(sd.SignerInfos) < 1 {
return errors.New("pkcs7: payload has no signers")
}
attributes := sd.SignerInfos[0].AuthenticatedAttributes
return unmarshalAttribute(attributes, attributeType, out)
} | [
"func",
"(",
"p7",
"*",
"PKCS7",
")",
"UnmarshalSignedAttribute",
"(",
"attributeType",
"asn1",
".",
"ObjectIdentifier",
",",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"sd",
",",
"ok",
":=",
"p7",
".",
"raw",
".",
"(",
"signedData",
")",
"\n",
"... | // UnmarshalSignedAttribute decodes a single attribute from the signer info | [
"UnmarshalSignedAttribute",
"decodes",
"a",
"single",
"attribute",
"from",
"the",
"signer",
"info"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/pkcs7.go#L518-L528 | train |
tjfoc/gmsm | sm2/pkcs7.go | NewSignedData | func NewSignedData(data []byte) (*SignedData, error) {
content, err := asn1.Marshal(data)
if err != nil {
return nil, err
}
ci := contentInfo{
ContentType: oidData,
Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: content, IsCompound: true},
}
digAlg := pkix.AlgorithmIdentifier{
Algorithm: oidDigestAlgorithmSHA1,
}
h := crypto.SHA1.New()
h.Write(data)
md := h.Sum(nil)
sd := signedData{
ContentInfo: ci,
Version: 1,
DigestAlgorithmIdentifiers: []pkix.AlgorithmIdentifier{digAlg},
}
return &SignedData{sd: sd, messageDigest: md}, nil
} | go | func NewSignedData(data []byte) (*SignedData, error) {
content, err := asn1.Marshal(data)
if err != nil {
return nil, err
}
ci := contentInfo{
ContentType: oidData,
Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: content, IsCompound: true},
}
digAlg := pkix.AlgorithmIdentifier{
Algorithm: oidDigestAlgorithmSHA1,
}
h := crypto.SHA1.New()
h.Write(data)
md := h.Sum(nil)
sd := signedData{
ContentInfo: ci,
Version: 1,
DigestAlgorithmIdentifiers: []pkix.AlgorithmIdentifier{digAlg},
}
return &SignedData{sd: sd, messageDigest: md}, nil
} | [
"func",
"NewSignedData",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"*",
"SignedData",
",",
"error",
")",
"{",
"content",
",",
"err",
":=",
"asn1",
".",
"Marshal",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
... | // NewSignedData initializes a SignedData with content | [
"NewSignedData",
"initializes",
"a",
"SignedData",
"with",
"content"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/pkcs7.go#L550-L571 | train |
tjfoc/gmsm | sm2/pkcs7.go | Add | func (attrs *attributes) Add(attrType asn1.ObjectIdentifier, value interface{}) {
attrs.types = append(attrs.types, attrType)
attrs.values = append(attrs.values, value)
} | go | func (attrs *attributes) Add(attrType asn1.ObjectIdentifier, value interface{}) {
attrs.types = append(attrs.types, attrType)
attrs.values = append(attrs.values, value)
} | [
"func",
"(",
"attrs",
"*",
"attributes",
")",
"Add",
"(",
"attrType",
"asn1",
".",
"ObjectIdentifier",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"attrs",
".",
"types",
"=",
"append",
"(",
"attrs",
".",
"types",
",",
"attrType",
")",
"\n",
"attrs",... | // Add adds the attribute, maintaining insertion order | [
"Add",
"adds",
"the",
"attribute",
"maintaining",
"insertion",
"order"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/pkcs7.go#L579-L582 | train |
tjfoc/gmsm | sm2/pkcs7.go | Finish | func (sd *SignedData) Finish() ([]byte, error) {
sd.sd.Certificates = marshalCertificates(sd.certs)
inner, err := asn1.Marshal(sd.sd)
if err != nil {
return nil, err
}
outer := contentInfo{
ContentType: oidSignedData,
Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: inner, IsCompound: true},
}
return asn1.Marshal(outer)
} | go | func (sd *SignedData) Finish() ([]byte, error) {
sd.sd.Certificates = marshalCertificates(sd.certs)
inner, err := asn1.Marshal(sd.sd)
if err != nil {
return nil, err
}
outer := contentInfo{
ContentType: oidSignedData,
Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: inner, IsCompound: true},
}
return asn1.Marshal(outer)
} | [
"func",
"(",
"sd",
"*",
"SignedData",
")",
"Finish",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"sd",
".",
"sd",
".",
"Certificates",
"=",
"marshalCertificates",
"(",
"sd",
".",
"certs",
")",
"\n",
"inner",
",",
"err",
":=",
"asn1",
... | // Finish marshals the content and its signers | [
"Finish",
"marshals",
"the",
"content",
"and",
"its",
"signers"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/pkcs7.go#L686-L697 | train |
tjfoc/gmsm | sm2/pkcs7.go | signAttributes | func signAttributes(attrs []attribute, pkey crypto.PrivateKey, hash crypto.Hash) ([]byte, error) {
attrBytes, err := marshalAttributes(attrs)
if err != nil {
return nil, err
}
h := hash.New()
h.Write(attrBytes)
hashed := h.Sum(nil)
switch priv := pkey.(type) {
case *rsa.PrivateKey:
return rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, hashed)
}
return nil, ErrPKCS7UnsupportedAlgorithm
} | go | func signAttributes(attrs []attribute, pkey crypto.PrivateKey, hash crypto.Hash) ([]byte, error) {
attrBytes, err := marshalAttributes(attrs)
if err != nil {
return nil, err
}
h := hash.New()
h.Write(attrBytes)
hashed := h.Sum(nil)
switch priv := pkey.(type) {
case *rsa.PrivateKey:
return rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, hashed)
}
return nil, ErrPKCS7UnsupportedAlgorithm
} | [
"func",
"signAttributes",
"(",
"attrs",
"[",
"]",
"attribute",
",",
"pkey",
"crypto",
".",
"PrivateKey",
",",
"hash",
"crypto",
".",
"Hash",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"attrBytes",
",",
"err",
":=",
"marshalAttributes",
"(",
"a... | // signs the DER encoded form of the attributes with the private key | [
"signs",
"the",
"DER",
"encoded",
"form",
"of",
"the",
"attributes",
"with",
"the",
"private",
"key"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/pkcs7.go#L710-L723 | train |
tjfoc/gmsm | sm2/pkcs7.go | marshalCertificates | func marshalCertificates(certs []*Certificate) rawCertificates {
var buf bytes.Buffer
for _, cert := range certs {
buf.Write(cert.Raw)
}
rawCerts, _ := marshalCertificateBytes(buf.Bytes())
return rawCerts
} | go | func marshalCertificates(certs []*Certificate) rawCertificates {
var buf bytes.Buffer
for _, cert := range certs {
buf.Write(cert.Raw)
}
rawCerts, _ := marshalCertificateBytes(buf.Bytes())
return rawCerts
} | [
"func",
"marshalCertificates",
"(",
"certs",
"[",
"]",
"*",
"Certificate",
")",
"rawCertificates",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"cert",
":=",
"range",
"certs",
"{",
"buf",
".",
"Write",
"(",
"cert",
".",
"Raw",
")",... | // concats and wraps the certificates in the RawValue structure | [
"concats",
"and",
"wraps",
"the",
"certificates",
"in",
"the",
"RawValue",
"structure"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/pkcs7.go#L726-L733 | train |
tjfoc/gmsm | sm2/pkcs7.go | DegenerateCertificate | func DegenerateCertificate(cert []byte) ([]byte, error) {
rawCert, err := marshalCertificateBytes(cert)
if err != nil {
return nil, err
}
emptyContent := contentInfo{ContentType: oidData}
sd := signedData{
Version: 1,
ContentInfo: emptyContent,
Certificates: rawCert,
CRLs: []pkix.CertificateList{},
}
content, err := asn1.Marshal(sd)
if err != nil {
return nil, err
}
signedContent := contentInfo{
ContentType: oidSignedData,
Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: content, IsCompound: true},
}
return asn1.Marshal(signedContent)
} | go | func DegenerateCertificate(cert []byte) ([]byte, error) {
rawCert, err := marshalCertificateBytes(cert)
if err != nil {
return nil, err
}
emptyContent := contentInfo{ContentType: oidData}
sd := signedData{
Version: 1,
ContentInfo: emptyContent,
Certificates: rawCert,
CRLs: []pkix.CertificateList{},
}
content, err := asn1.Marshal(sd)
if err != nil {
return nil, err
}
signedContent := contentInfo{
ContentType: oidSignedData,
Content: asn1.RawValue{Class: 2, Tag: 0, Bytes: content, IsCompound: true},
}
return asn1.Marshal(signedContent)
} | [
"func",
"DegenerateCertificate",
"(",
"cert",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"rawCert",
",",
"err",
":=",
"marshalCertificateBytes",
"(",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"... | // DegenerateCertificate creates a signed data structure containing only the
// provided certificate or certificate chain. | [
"DegenerateCertificate",
"creates",
"a",
"signed",
"data",
"structure",
"containing",
"only",
"the",
"provided",
"certificate",
"or",
"certificate",
"chain",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/pkcs7.go#L749-L770 | train |
tjfoc/gmsm | sm2/pkcs1.go | MarshalPKCS1PrivateKey | func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
key.Precompute()
version := 0
if len(key.Primes) > 2 {
version = 1
}
priv := pkcs1PrivateKey{
Version: version,
N: key.N,
E: key.PublicKey.E,
D: key.D,
P: key.Primes[0],
Q: key.Primes[1],
Dp: key.Precomputed.Dp,
Dq: key.Precomputed.Dq,
Qinv: key.Precomputed.Qinv,
}
priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
for i, values := range key.Precomputed.CRTValues {
priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
priv.AdditionalPrimes[i].Exp = values.Exp
priv.AdditionalPrimes[i].Coeff = values.Coeff
}
b, _ := asn1.Marshal(priv)
return b
} | go | func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
key.Precompute()
version := 0
if len(key.Primes) > 2 {
version = 1
}
priv := pkcs1PrivateKey{
Version: version,
N: key.N,
E: key.PublicKey.E,
D: key.D,
P: key.Primes[0],
Q: key.Primes[1],
Dp: key.Precomputed.Dp,
Dq: key.Precomputed.Dq,
Qinv: key.Precomputed.Qinv,
}
priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
for i, values := range key.Precomputed.CRTValues {
priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
priv.AdditionalPrimes[i].Exp = values.Exp
priv.AdditionalPrimes[i].Coeff = values.Coeff
}
b, _ := asn1.Marshal(priv)
return b
} | [
"func",
"MarshalPKCS1PrivateKey",
"(",
"key",
"*",
"rsa",
".",
"PrivateKey",
")",
"[",
"]",
"byte",
"{",
"key",
".",
"Precompute",
"(",
")",
"\n\n",
"version",
":=",
"0",
"\n",
"if",
"len",
"(",
"key",
".",
"Primes",
")",
">",
"2",
"{",
"version",
... | // MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form. | [
"MarshalPKCS1PrivateKey",
"converts",
"a",
"private",
"key",
"to",
"ASN",
".",
"1",
"DER",
"encoded",
"form",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/pkcs1.go#L97-L126 | train |
tjfoc/gmsm | sm2/p256.go | IsOnCurve | func (curve sm2P256Curve) IsOnCurve(X, Y *big.Int) bool {
var a, x, y, y2, x3 sm2P256FieldElement
sm2P256FromBig(&x, X)
sm2P256FromBig(&y, Y)
sm2P256Square(&x3, &x) // x3 = x ^ 2
sm2P256Mul(&x3, &x3, &x) // x3 = x ^ 2 * x
sm2P256Mul(&a, &curve.a, &x) // a = a * x
sm2P256Add(&x3, &x3, &a)
sm2P256Add(&x3, &x3, &curve.b)
sm2P256Square(&y2, &y) // y2 = y ^ 2
return sm2P256ToBig(&x3).Cmp(sm2P256ToBig(&y2)) == 0
} | go | func (curve sm2P256Curve) IsOnCurve(X, Y *big.Int) bool {
var a, x, y, y2, x3 sm2P256FieldElement
sm2P256FromBig(&x, X)
sm2P256FromBig(&y, Y)
sm2P256Square(&x3, &x) // x3 = x ^ 2
sm2P256Mul(&x3, &x3, &x) // x3 = x ^ 2 * x
sm2P256Mul(&a, &curve.a, &x) // a = a * x
sm2P256Add(&x3, &x3, &a)
sm2P256Add(&x3, &x3, &curve.b)
sm2P256Square(&y2, &y) // y2 = y ^ 2
return sm2P256ToBig(&x3).Cmp(sm2P256ToBig(&y2)) == 0
} | [
"func",
"(",
"curve",
"sm2P256Curve",
")",
"IsOnCurve",
"(",
"X",
",",
"Y",
"*",
"big",
".",
"Int",
")",
"bool",
"{",
"var",
"a",
",",
"x",
",",
"y",
",",
"y2",
",",
"x3",
"sm2P256FieldElement",
"\n\n",
"sm2P256FromBig",
"(",
"&",
"x",
",",
"X",
... | // y^2 = x^3 + ax + b | [
"y^2",
"=",
"x^3",
"+",
"ax",
"+",
"b"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/p256.go#L93-L107 | train |
tjfoc/gmsm | sm2/p256.go | sm2P256GetBit | func sm2P256GetBit(scalar *[32]uint8, bit uint) uint32 {
return uint32(((scalar[bit>>3]) >> (bit & 7)) & 1)
} | go | func sm2P256GetBit(scalar *[32]uint8, bit uint) uint32 {
return uint32(((scalar[bit>>3]) >> (bit & 7)) & 1)
} | [
"func",
"sm2P256GetBit",
"(",
"scalar",
"*",
"[",
"32",
"]",
"uint8",
",",
"bit",
"uint",
")",
"uint32",
"{",
"return",
"uint32",
"(",
"(",
"(",
"scalar",
"[",
"bit",
">>",
"3",
"]",
")",
">>",
"(",
"bit",
"&",
"7",
")",
")",
"&",
"1",
")",
"... | // sm2P256GetBit returns the bit'th bit of scalar. | [
"sm2P256GetBit",
"returns",
"the",
"bit",
"th",
"bit",
"of",
"scalar",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/p256.go#L343-L345 | train |
tjfoc/gmsm | sm2/p256.go | sm2P256Add | func sm2P256Add(c, a, b *sm2P256FieldElement) {
carry := uint32(0)
for i := 0; ; i++ {
c[i] = a[i] + b[i]
c[i] += carry
carry = c[i] >> 29
c[i] &= bottom29Bits
i++
if i == 9 {
break
}
c[i] = a[i] + b[i]
c[i] += carry
carry = c[i] >> 28
c[i] &= bottom28Bits
}
sm2P256ReduceCarry(c, carry)
} | go | func sm2P256Add(c, a, b *sm2P256FieldElement) {
carry := uint32(0)
for i := 0; ; i++ {
c[i] = a[i] + b[i]
c[i] += carry
carry = c[i] >> 29
c[i] &= bottom29Bits
i++
if i == 9 {
break
}
c[i] = a[i] + b[i]
c[i] += carry
carry = c[i] >> 28
c[i] &= bottom28Bits
}
sm2P256ReduceCarry(c, carry)
} | [
"func",
"sm2P256Add",
"(",
"c",
",",
"a",
",",
"b",
"*",
"sm2P256FieldElement",
")",
"{",
"carry",
":=",
"uint32",
"(",
"0",
")",
"\n",
"for",
"i",
":=",
"0",
";",
";",
"i",
"++",
"{",
"c",
"[",
"i",
"]",
"=",
"a",
"[",
"i",
"]",
"+",
"b",
... | // c = a + b | [
"c",
"=",
"a",
"+",
"b"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/p256.go#L602-L619 | train |
tjfoc/gmsm | sm2/p256.go | sm2P256Sub | func sm2P256Sub(c, a, b *sm2P256FieldElement) {
var carry uint32
for i := 0; ; i++ {
c[i] = a[i] - b[i]
c[i] += sm2P256Zero31[i]
c[i] += carry
carry = c[i] >> 29
c[i] &= bottom29Bits
i++
if i == 9 {
break
}
c[i] = a[i] - b[i]
c[i] += sm2P256Zero31[i]
c[i] += carry
carry = c[i] >> 28
c[i] &= bottom28Bits
}
sm2P256ReduceCarry(c, carry)
} | go | func sm2P256Sub(c, a, b *sm2P256FieldElement) {
var carry uint32
for i := 0; ; i++ {
c[i] = a[i] - b[i]
c[i] += sm2P256Zero31[i]
c[i] += carry
carry = c[i] >> 29
c[i] &= bottom29Bits
i++
if i == 9 {
break
}
c[i] = a[i] - b[i]
c[i] += sm2P256Zero31[i]
c[i] += carry
carry = c[i] >> 28
c[i] &= bottom28Bits
}
sm2P256ReduceCarry(c, carry)
} | [
"func",
"sm2P256Sub",
"(",
"c",
",",
"a",
",",
"b",
"*",
"sm2P256FieldElement",
")",
"{",
"var",
"carry",
"uint32",
"\n\n",
"for",
"i",
":=",
"0",
";",
";",
"i",
"++",
"{",
"c",
"[",
"i",
"]",
"=",
"a",
"[",
"i",
"]",
"-",
"b",
"[",
"i",
"]... | // c = a - b | [
"c",
"=",
"a",
"-",
"b"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/p256.go#L622-L642 | train |
tjfoc/gmsm | sm2/p256.go | sm2P256ReduceCarry | func sm2P256ReduceCarry(a *sm2P256FieldElement, carry uint32) {
a[0] += sm2P256Carry[carry*9+0]
a[2] += sm2P256Carry[carry*9+2]
a[3] += sm2P256Carry[carry*9+3]
a[7] += sm2P256Carry[carry*9+7]
} | go | func sm2P256ReduceCarry(a *sm2P256FieldElement, carry uint32) {
a[0] += sm2P256Carry[carry*9+0]
a[2] += sm2P256Carry[carry*9+2]
a[3] += sm2P256Carry[carry*9+3]
a[7] += sm2P256Carry[carry*9+7]
} | [
"func",
"sm2P256ReduceCarry",
"(",
"a",
"*",
"sm2P256FieldElement",
",",
"carry",
"uint32",
")",
"{",
"a",
"[",
"0",
"]",
"+=",
"sm2P256Carry",
"[",
"carry",
"*",
"9",
"+",
"0",
"]",
"\n",
"a",
"[",
"2",
"]",
"+=",
"sm2P256Carry",
"[",
"carry",
"*",
... | // carry < 2 ^ 3 | [
"carry",
"<",
"2",
"^",
"3"
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/p256.go#L807-L812 | train |
tjfoc/gmsm | sm3/sm3.go | Sum | func (sm3 *SM3) Sum(in []byte) []byte {
sm3.Write(in)
msg := sm3.pad()
// Finialize
sm3.update(msg, len(msg)/sm3.BlockSize())
// save hash to in
needed := sm3.Size()
if cap(in)-len(in) < needed {
newIn := make([]byte, len(in), len(in)+needed)
copy(newIn, in)
in = newIn
}
out := in[len(in) : len(in)+needed]
for i := 0; i < 8; i++ {
binary.BigEndian.PutUint32(out[i*4:], sm3.digest[i])
}
return out
} | go | func (sm3 *SM3) Sum(in []byte) []byte {
sm3.Write(in)
msg := sm3.pad()
// Finialize
sm3.update(msg, len(msg)/sm3.BlockSize())
// save hash to in
needed := sm3.Size()
if cap(in)-len(in) < needed {
newIn := make([]byte, len(in), len(in)+needed)
copy(newIn, in)
in = newIn
}
out := in[len(in) : len(in)+needed]
for i := 0; i < 8; i++ {
binary.BigEndian.PutUint32(out[i*4:], sm3.digest[i])
}
return out
} | [
"func",
"(",
"sm3",
"*",
"SM3",
")",
"Sum",
"(",
"in",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"sm3",
".",
"Write",
"(",
"in",
")",
"\n",
"msg",
":=",
"sm3",
".",
"pad",
"(",
")",
"\n\n",
"// Finialize",
"sm3",
".",
"update",
"(",
"msg"... | // Sum, required by the hash.Hash interface.
// Sum appends the current hash to b and returns the resulting slice.
// It does not change the underlying hash state. | [
"Sum",
"required",
"by",
"the",
"hash",
".",
"Hash",
"interface",
".",
"Sum",
"appends",
"the",
"current",
"hash",
"to",
"b",
"and",
"returns",
"the",
"resulting",
"slice",
".",
"It",
"does",
"not",
"change",
"the",
"underlying",
"hash",
"state",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm3/sm3.go#L178-L199 | train |
tjfoc/gmsm | sm4/sm4.go | NewCipher | func NewCipher(key []byte) (cipher.Block, error) {
if len(key) != BlockSize {
return nil, KeySizeError(len(key))
}
c := new(Sm4Cipher)
c.subkeys = generateSubKeys(key)
c.block1 = make([]uint32, 4)
c.block2 = make([]byte, 16)
return c, nil
} | go | func NewCipher(key []byte) (cipher.Block, error) {
if len(key) != BlockSize {
return nil, KeySizeError(len(key))
}
c := new(Sm4Cipher)
c.subkeys = generateSubKeys(key)
c.block1 = make([]uint32, 4)
c.block2 = make([]byte, 16)
return c, nil
} | [
"func",
"NewCipher",
"(",
"key",
"[",
"]",
"byte",
")",
"(",
"cipher",
".",
"Block",
",",
"error",
")",
"{",
"if",
"len",
"(",
"key",
")",
"!=",
"BlockSize",
"{",
"return",
"nil",
",",
"KeySizeError",
"(",
"len",
"(",
"key",
")",
")",
"\n",
"}",
... | // NewCipher creates and returns a new cipher.Block. | [
"NewCipher",
"creates",
"and",
"returns",
"a",
"new",
"cipher",
".",
"Block",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm4/sm4.go#L321-L330 | train |
tjfoc/gmsm | sm2/cert_pool.go | NewCertPool | func NewCertPool() *CertPool {
return &CertPool{
bySubjectKeyId: make(map[string][]int),
byName: make(map[string][]int),
}
} | go | func NewCertPool() *CertPool {
return &CertPool{
bySubjectKeyId: make(map[string][]int),
byName: make(map[string][]int),
}
} | [
"func",
"NewCertPool",
"(",
")",
"*",
"CertPool",
"{",
"return",
"&",
"CertPool",
"{",
"bySubjectKeyId",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"int",
")",
",",
"byName",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"int",... | // NewCertPool returns a new, empty CertPool. | [
"NewCertPool",
"returns",
"a",
"new",
"empty",
"CertPool",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/cert_pool.go#L44-L49 | train |
tjfoc/gmsm | sm2/cert_pool.go | findVerifiedParents | func (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int, errCert *Certificate, err error) {
if s == nil {
return
}
var candidates []int
if len(cert.AuthorityKeyId) > 0 {
candidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)]
}
if len(candidates) == 0 {
candidates = s.byName[string(cert.RawIssuer)]
}
for _, c := range candidates {
if err = cert.CheckSignatureFrom(s.certs[c]); err == nil {
parents = append(parents, c)
} else {
errCert = s.certs[c]
}
}
return
} | go | func (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int, errCert *Certificate, err error) {
if s == nil {
return
}
var candidates []int
if len(cert.AuthorityKeyId) > 0 {
candidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)]
}
if len(candidates) == 0 {
candidates = s.byName[string(cert.RawIssuer)]
}
for _, c := range candidates {
if err = cert.CheckSignatureFrom(s.certs[c]); err == nil {
parents = append(parents, c)
} else {
errCert = s.certs[c]
}
}
return
} | [
"func",
"(",
"s",
"*",
"CertPool",
")",
"findVerifiedParents",
"(",
"cert",
"*",
"Certificate",
")",
"(",
"parents",
"[",
"]",
"int",
",",
"errCert",
"*",
"Certificate",
",",
"err",
"error",
")",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"\n",
"}",... | // findVerifiedParents attempts to find certificates in s which have signed the
// given certificate. If any candidates were rejected then errCert will be set
// to one of them, arbitrarily, and err will contain the reason that it was
// rejected. | [
"findVerifiedParents",
"attempts",
"to",
"find",
"certificates",
"in",
"s",
"which",
"have",
"signed",
"the",
"given",
"certificate",
".",
"If",
"any",
"candidates",
"were",
"rejected",
"then",
"errCert",
"will",
"be",
"set",
"to",
"one",
"of",
"them",
"arbitr... | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/cert_pool.go#L131-L153 | train |
tjfoc/gmsm | sm2/cert_pool.go | AddCert | func (s *CertPool) AddCert(cert *Certificate) {
if cert == nil {
panic("adding nil Certificate to CertPool")
}
// Check that the certificate isn't being added twice.
if s.contains(cert) {
return
}
n := len(s.certs)
s.certs = append(s.certs, cert)
if len(cert.SubjectKeyId) > 0 {
keyId := string(cert.SubjectKeyId)
s.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n)
}
name := string(cert.RawSubject)
s.byName[name] = append(s.byName[name], n)
} | go | func (s *CertPool) AddCert(cert *Certificate) {
if cert == nil {
panic("adding nil Certificate to CertPool")
}
// Check that the certificate isn't being added twice.
if s.contains(cert) {
return
}
n := len(s.certs)
s.certs = append(s.certs, cert)
if len(cert.SubjectKeyId) > 0 {
keyId := string(cert.SubjectKeyId)
s.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n)
}
name := string(cert.RawSubject)
s.byName[name] = append(s.byName[name], n)
} | [
"func",
"(",
"s",
"*",
"CertPool",
")",
"AddCert",
"(",
"cert",
"*",
"Certificate",
")",
"{",
"if",
"cert",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Check that the certificate isn't being added twice.",
"if",
"s",
".",
"conta... | // AddCert adds a certificate to a pool. | [
"AddCert",
"adds",
"a",
"certificate",
"to",
"a",
"pool",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/cert_pool.go#L171-L190 | train |
tjfoc/gmsm | sm2/cert_pool.go | Subjects | func (s *CertPool) Subjects() [][]byte {
res := make([][]byte, len(s.certs))
for i, c := range s.certs {
res[i] = c.RawSubject
}
return res
} | go | func (s *CertPool) Subjects() [][]byte {
res := make([][]byte, len(s.certs))
for i, c := range s.certs {
res[i] = c.RawSubject
}
return res
} | [
"func",
"(",
"s",
"*",
"CertPool",
")",
"Subjects",
"(",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"res",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"len",
"(",
"s",
".",
"certs",
")",
")",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
... | // Subjects returns a list of the DER-encoded subjects of
// all of the certificates in the pool. | [
"Subjects",
"returns",
"a",
"list",
"of",
"the",
"DER",
"-",
"encoded",
"subjects",
"of",
"all",
"of",
"the",
"certificates",
"in",
"the",
"pool",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/cert_pool.go#L223-L229 | train |
tjfoc/gmsm | sm2/verify.go | isValid | func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
if len(currentChain) > 0 {
child := currentChain[len(currentChain)-1]
if !bytes.Equal(child.RawIssuer, c.RawSubject) {
return CertificateInvalidError{c, NameMismatch}
}
}
now := opts.CurrentTime
if now.IsZero() {
now = time.Now()
}
if now.Before(c.NotBefore) || now.After(c.NotAfter) {
return CertificateInvalidError{c, Expired}
}
if len(c.PermittedDNSDomains) > 0 {
ok := false
for _, constraint := range c.PermittedDNSDomains {
ok = matchNameConstraint(opts.DNSName, constraint)
if ok {
break
}
}
if !ok {
return CertificateInvalidError{c, CANotAuthorizedForThisName}
}
}
// KeyUsage status flags are ignored. From Engineering Security, Peter
// Gutmann: A European government CA marked its signing certificates as
// being valid for encryption only, but no-one noticed. Another
// European CA marked its signature keys as not being valid for
// signatures. A different CA marked its own trusted root certificate
// as being invalid for certificate signing. Another national CA
// distributed a certificate to be used to encrypt data for the
// country’s tax authority that was marked as only being usable for
// digital signatures but not for encryption. Yet another CA reversed
// the order of the bit flags in the keyUsage due to confusion over
// encoding endianness, essentially setting a random keyUsage in
// certificates that it issued. Another CA created a self-invalidating
// certificate by adding a certificate policy statement stipulating
// that the certificate had to be used strictly as specified in the
// keyUsage, and a keyUsage containing a flag indicating that the RSA
// encryption key could only be used for Diffie-Hellman key agreement.
if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
return CertificateInvalidError{c, NotAuthorizedToSign}
}
if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
numIntermediates := len(currentChain) - 1
if numIntermediates > c.MaxPathLen {
return CertificateInvalidError{c, TooManyIntermediates}
}
}
return nil
} | go | func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
if len(currentChain) > 0 {
child := currentChain[len(currentChain)-1]
if !bytes.Equal(child.RawIssuer, c.RawSubject) {
return CertificateInvalidError{c, NameMismatch}
}
}
now := opts.CurrentTime
if now.IsZero() {
now = time.Now()
}
if now.Before(c.NotBefore) || now.After(c.NotAfter) {
return CertificateInvalidError{c, Expired}
}
if len(c.PermittedDNSDomains) > 0 {
ok := false
for _, constraint := range c.PermittedDNSDomains {
ok = matchNameConstraint(opts.DNSName, constraint)
if ok {
break
}
}
if !ok {
return CertificateInvalidError{c, CANotAuthorizedForThisName}
}
}
// KeyUsage status flags are ignored. From Engineering Security, Peter
// Gutmann: A European government CA marked its signing certificates as
// being valid for encryption only, but no-one noticed. Another
// European CA marked its signature keys as not being valid for
// signatures. A different CA marked its own trusted root certificate
// as being invalid for certificate signing. Another national CA
// distributed a certificate to be used to encrypt data for the
// country’s tax authority that was marked as only being usable for
// digital signatures but not for encryption. Yet another CA reversed
// the order of the bit flags in the keyUsage due to confusion over
// encoding endianness, essentially setting a random keyUsage in
// certificates that it issued. Another CA created a self-invalidating
// certificate by adding a certificate policy statement stipulating
// that the certificate had to be used strictly as specified in the
// keyUsage, and a keyUsage containing a flag indicating that the RSA
// encryption key could only be used for Diffie-Hellman key agreement.
if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
return CertificateInvalidError{c, NotAuthorizedToSign}
}
if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
numIntermediates := len(currentChain) - 1
if numIntermediates > c.MaxPathLen {
return CertificateInvalidError{c, TooManyIntermediates}
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"isValid",
"(",
"certType",
"int",
",",
"currentChain",
"[",
"]",
"*",
"Certificate",
",",
"opts",
"*",
"VerifyOptions",
")",
"error",
"{",
"if",
"len",
"(",
"currentChain",
")",
">",
"0",
"{",
"child",
":=",
... | // isValid performs validity checks on the c. | [
"isValid",
"performs",
"validity",
"checks",
"on",
"the",
"c",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/verify.go#L204-L261 | train |
tjfoc/gmsm | sm2/verify.go | toLowerCaseASCII | func toLowerCaseASCII(in string) string {
// If the string is already lower-case then there's nothing to do.
isAlreadyLowerCase := true
for _, c := range in {
if c == utf8.RuneError {
// If we get a UTF-8 error then there might be
// upper-case ASCII bytes in the invalid sequence.
isAlreadyLowerCase = false
break
}
if 'A' <= c && c <= 'Z' {
isAlreadyLowerCase = false
break
}
}
if isAlreadyLowerCase {
return in
}
out := []byte(in)
for i, c := range out {
if 'A' <= c && c <= 'Z' {
out[i] += 'a' - 'A'
}
}
return string(out)
} | go | func toLowerCaseASCII(in string) string {
// If the string is already lower-case then there's nothing to do.
isAlreadyLowerCase := true
for _, c := range in {
if c == utf8.RuneError {
// If we get a UTF-8 error then there might be
// upper-case ASCII bytes in the invalid sequence.
isAlreadyLowerCase = false
break
}
if 'A' <= c && c <= 'Z' {
isAlreadyLowerCase = false
break
}
}
if isAlreadyLowerCase {
return in
}
out := []byte(in)
for i, c := range out {
if 'A' <= c && c <= 'Z' {
out[i] += 'a' - 'A'
}
}
return string(out)
} | [
"func",
"toLowerCaseASCII",
"(",
"in",
"string",
")",
"string",
"{",
"// If the string is already lower-case then there's nothing to do.",
"isAlreadyLowerCase",
":=",
"true",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"in",
"{",
"if",
"c",
"==",
"utf8",
".",
"Rune... | // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
// an explicitly ASCII function to avoid any sharp corners resulting from
// performing Unicode operations on DNS labels. | [
"toLowerCaseASCII",
"returns",
"a",
"lower",
"-",
"case",
"version",
"of",
"in",
".",
"See",
"RFC",
"6125",
"6",
".",
"4",
".",
"1",
".",
"We",
"use",
"an",
"explicitly",
"ASCII",
"function",
"to",
"avoid",
"any",
"sharp",
"corners",
"resulting",
"from",... | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/verify.go#L444-L471 | train |
tjfoc/gmsm | sm2/verify.go | VerifyHostname | func (c *Certificate) VerifyHostname(h string) error {
// IP addresses may be written in [ ].
candidateIP := h
if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
candidateIP = h[1 : len(h)-1]
}
if ip := net.ParseIP(candidateIP); ip != nil {
// We only match IP addresses against IP SANs.
// https://tools.ietf.org/html/rfc6125#appendix-B.2
for _, candidate := range c.IPAddresses {
if ip.Equal(candidate) {
return nil
}
}
return HostnameError{c, candidateIP}
}
lowered := toLowerCaseASCII(h)
if len(c.DNSNames) > 0 {
for _, match := range c.DNSNames {
if matchHostnames(toLowerCaseASCII(match), lowered) {
return nil
}
}
// If Subject Alt Name is given, we ignore the common name.
} else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) {
return nil
}
return HostnameError{c, h}
} | go | func (c *Certificate) VerifyHostname(h string) error {
// IP addresses may be written in [ ].
candidateIP := h
if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
candidateIP = h[1 : len(h)-1]
}
if ip := net.ParseIP(candidateIP); ip != nil {
// We only match IP addresses against IP SANs.
// https://tools.ietf.org/html/rfc6125#appendix-B.2
for _, candidate := range c.IPAddresses {
if ip.Equal(candidate) {
return nil
}
}
return HostnameError{c, candidateIP}
}
lowered := toLowerCaseASCII(h)
if len(c.DNSNames) > 0 {
for _, match := range c.DNSNames {
if matchHostnames(toLowerCaseASCII(match), lowered) {
return nil
}
}
// If Subject Alt Name is given, we ignore the common name.
} else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) {
return nil
}
return HostnameError{c, h}
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"VerifyHostname",
"(",
"h",
"string",
")",
"error",
"{",
"// IP addresses may be written in [ ].",
"candidateIP",
":=",
"h",
"\n",
"if",
"len",
"(",
"h",
")",
">=",
"3",
"&&",
"h",
"[",
"0",
"]",
"==",
"'['",
... | // VerifyHostname returns nil if c is a valid certificate for the named host.
// Otherwise it returns an error describing the mismatch. | [
"VerifyHostname",
"returns",
"nil",
"if",
"c",
"is",
"a",
"valid",
"certificate",
"for",
"the",
"named",
"host",
".",
"Otherwise",
"it",
"returns",
"an",
"error",
"describing",
"the",
"mismatch",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/verify.go#L475-L506 | train |
tjfoc/gmsm | sm2/x509.go | MarshalPKIXPublicKey | func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
var publicKeyBytes []byte
var publicKeyAlgorithm pkix.AlgorithmIdentifier
var err error
if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
return nil, err
}
pkix := pkixPublicKey{
Algo: publicKeyAlgorithm,
BitString: asn1.BitString{
Bytes: publicKeyBytes,
BitLength: 8 * len(publicKeyBytes),
},
}
ret, _ := asn1.Marshal(pkix)
return ret, nil
} | go | func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
var publicKeyBytes []byte
var publicKeyAlgorithm pkix.AlgorithmIdentifier
var err error
if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
return nil, err
}
pkix := pkixPublicKey{
Algo: publicKeyAlgorithm,
BitString: asn1.BitString{
Bytes: publicKeyBytes,
BitLength: 8 * len(publicKeyBytes),
},
}
ret, _ := asn1.Marshal(pkix)
return ret, nil
} | [
"func",
"MarshalPKIXPublicKey",
"(",
"pub",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"publicKeyBytes",
"[",
"]",
"byte",
"\n",
"var",
"publicKeyAlgorithm",
"pkix",
".",
"AlgorithmIdentifier",
"\n",
"var",
"err",
"er... | // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format. | [
"MarshalPKIXPublicKey",
"serialises",
"a",
"public",
"key",
"to",
"DER",
"-",
"encoded",
"PKIX",
"format",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L130-L149 | train |
tjfoc/gmsm | sm2/x509.go | rsaPSSParameters | func rsaPSSParameters(hashFunc Hash) asn1.RawValue {
var hashOID asn1.ObjectIdentifier
switch hashFunc {
case SHA256:
hashOID = oidSHA256
case SHA384:
hashOID = oidSHA384
case SHA512:
hashOID = oidSHA512
}
params := pssParameters{
Hash: pkix.AlgorithmIdentifier{
Algorithm: hashOID,
Parameters: asn1.RawValue{
Tag: 5, /* ASN.1 NULL */
},
},
MGF: pkix.AlgorithmIdentifier{
Algorithm: oidMGF1,
},
SaltLength: hashFunc.Size(),
TrailerField: 1,
}
mgf1Params := pkix.AlgorithmIdentifier{
Algorithm: hashOID,
Parameters: asn1.RawValue{
Tag: 5, /* ASN.1 NULL */
},
}
var err error
params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
if err != nil {
panic(err)
}
serialized, err := asn1.Marshal(params)
if err != nil {
panic(err)
}
return asn1.RawValue{FullBytes: serialized}
} | go | func rsaPSSParameters(hashFunc Hash) asn1.RawValue {
var hashOID asn1.ObjectIdentifier
switch hashFunc {
case SHA256:
hashOID = oidSHA256
case SHA384:
hashOID = oidSHA384
case SHA512:
hashOID = oidSHA512
}
params := pssParameters{
Hash: pkix.AlgorithmIdentifier{
Algorithm: hashOID,
Parameters: asn1.RawValue{
Tag: 5, /* ASN.1 NULL */
},
},
MGF: pkix.AlgorithmIdentifier{
Algorithm: oidMGF1,
},
SaltLength: hashFunc.Size(),
TrailerField: 1,
}
mgf1Params := pkix.AlgorithmIdentifier{
Algorithm: hashOID,
Parameters: asn1.RawValue{
Tag: 5, /* ASN.1 NULL */
},
}
var err error
params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
if err != nil {
panic(err)
}
serialized, err := asn1.Marshal(params)
if err != nil {
panic(err)
}
return asn1.RawValue{FullBytes: serialized}
} | [
"func",
"rsaPSSParameters",
"(",
"hashFunc",
"Hash",
")",
"asn1",
".",
"RawValue",
"{",
"var",
"hashOID",
"asn1",
".",
"ObjectIdentifier",
"\n\n",
"switch",
"hashFunc",
"{",
"case",
"SHA256",
":",
"hashOID",
"=",
"oidSHA256",
"\n",
"case",
"SHA384",
":",
"ha... | // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
// in an AlgorithmIdentifier that specifies RSA PSS. | [
"rsaPSSParameters",
"returns",
"an",
"asn1",
".",
"RawValue",
"suitable",
"for",
"use",
"as",
"the",
"Parameters",
"in",
"an",
"AlgorithmIdentifier",
"that",
"specifies",
"RSA",
"PSS",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L500-L545 | train |
tjfoc/gmsm | sm2/x509.go | CheckSignatureFrom | func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
// RFC 5280, 4.2.1.9:
// "If the basic constraints extension is not present in a version 3
// certificate, or the extension is present but the cA boolean is not
// asserted, then the certified public key MUST NOT be used to verify
// certificate signatures."
// (except for Entrust, see comment above entrustBrokenSPKI)
if (parent.Version == 3 && !parent.BasicConstraintsValid ||
parent.BasicConstraintsValid && !parent.IsCA) &&
!bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
return ConstraintViolationError{}
}
if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
return ConstraintViolationError{}
}
if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
return ErrUnsupportedAlgorithm
}
// TODO(agl): don't ignore the path length constraint.
return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
} | go | func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
// RFC 5280, 4.2.1.9:
// "If the basic constraints extension is not present in a version 3
// certificate, or the extension is present but the cA boolean is not
// asserted, then the certified public key MUST NOT be used to verify
// certificate signatures."
// (except for Entrust, see comment above entrustBrokenSPKI)
if (parent.Version == 3 && !parent.BasicConstraintsValid ||
parent.BasicConstraintsValid && !parent.IsCA) &&
!bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
return ConstraintViolationError{}
}
if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
return ConstraintViolationError{}
}
if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
return ErrUnsupportedAlgorithm
}
// TODO(agl): don't ignore the path length constraint.
return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"CheckSignatureFrom",
"(",
"parent",
"*",
"Certificate",
")",
"error",
"{",
"// RFC 5280, 4.2.1.9:",
"// \"If the basic constraints extension is not present in a version 3",
"// certificate, or the extension is present but the cA boolean is ... | // CheckSignatureFrom verifies that the signature on c is a valid signature
// from parent. | [
"CheckSignatureFrom",
"verifies",
"that",
"the",
"signature",
"on",
"c",
"is",
"a",
"valid",
"signature",
"from",
"parent",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L937-L961 | train |
tjfoc/gmsm | sm2/x509.go | CheckSignature | func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
return checkSignature(algo, signed, signature, c.PublicKey)
} | go | func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
return checkSignature(algo, signed, signature, c.PublicKey)
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"CheckSignature",
"(",
"algo",
"SignatureAlgorithm",
",",
"signed",
",",
"signature",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"checkSignature",
"(",
"algo",
",",
"signed",
",",
"signature",
",",
"c",
".",
... | // CheckSignature verifies that signature is a valid signature over signed from
// c's public key. | [
"CheckSignature",
"verifies",
"that",
"signature",
"is",
"a",
"valid",
"signature",
"over",
"signed",
"from",
"c",
"s",
"public",
"key",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L965-L967 | train |
tjfoc/gmsm | sm2/x509.go | CheckCRLSignature | func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
} | go | func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"CheckCRLSignature",
"(",
"crl",
"*",
"pkix",
".",
"CertificateList",
")",
"error",
"{",
"algo",
":=",
"getSignatureAlgorithmFromAI",
"(",
"crl",
".",
"SignatureAlgorithm",
")",
"\n",
"return",
"c",
".",
"CheckSignatu... | // CheckCRLSignature checks that the signature in crl is from c. | [
"CheckCRLSignature",
"checks",
"that",
"the",
"signature",
"in",
"crl",
"is",
"from",
"c",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1050-L1053 | train |
tjfoc/gmsm | sm2/x509.go | ParseCertificate | func ParseCertificate(asn1Data []byte) (*Certificate, error) {
var cert certificate
rest, err := asn1.Unmarshal(asn1Data, &cert)
if err != nil {
return nil, err
}
if len(rest) > 0 {
return nil, asn1.SyntaxError{Msg: "trailing data"}
}
return parseCertificate(&cert)
} | go | func ParseCertificate(asn1Data []byte) (*Certificate, error) {
var cert certificate
rest, err := asn1.Unmarshal(asn1Data, &cert)
if err != nil {
return nil, err
}
if len(rest) > 0 {
return nil, asn1.SyntaxError{Msg: "trailing data"}
}
return parseCertificate(&cert)
} | [
"func",
"ParseCertificate",
"(",
"asn1Data",
"[",
"]",
"byte",
")",
"(",
"*",
"Certificate",
",",
"error",
")",
"{",
"var",
"cert",
"certificate",
"\n",
"rest",
",",
"err",
":=",
"asn1",
".",
"Unmarshal",
"(",
"asn1Data",
",",
"&",
"cert",
")",
"\n",
... | // ParseCertificate parses a single certificate from the given ASN.1 DER data. | [
"ParseCertificate",
"parses",
"a",
"single",
"certificate",
"from",
"the",
"given",
"ASN",
".",
"1",
"DER",
"data",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1510-L1521 | train |
tjfoc/gmsm | sm2/x509.go | ParseCertificates | func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
var v []*certificate
for len(asn1Data) > 0 {
cert := new(certificate)
var err error
asn1Data, err = asn1.Unmarshal(asn1Data, cert)
if err != nil {
return nil, err
}
v = append(v, cert)
}
ret := make([]*Certificate, len(v))
for i, ci := range v {
cert, err := parseCertificate(ci)
if err != nil {
return nil, err
}
ret[i] = cert
}
return ret, nil
} | go | func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
var v []*certificate
for len(asn1Data) > 0 {
cert := new(certificate)
var err error
asn1Data, err = asn1.Unmarshal(asn1Data, cert)
if err != nil {
return nil, err
}
v = append(v, cert)
}
ret := make([]*Certificate, len(v))
for i, ci := range v {
cert, err := parseCertificate(ci)
if err != nil {
return nil, err
}
ret[i] = cert
}
return ret, nil
} | [
"func",
"ParseCertificates",
"(",
"asn1Data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"*",
"Certificate",
",",
"error",
")",
"{",
"var",
"v",
"[",
"]",
"*",
"certificate",
"\n\n",
"for",
"len",
"(",
"asn1Data",
")",
">",
"0",
"{",
"cert",
":=",
"new"... | // ParseCertificates parses one or more certificates from the given ASN.1 DER
// data. The certificates must be concatenated with no intermediate padding. | [
"ParseCertificates",
"parses",
"one",
"or",
"more",
"certificates",
"from",
"the",
"given",
"ASN",
".",
"1",
"DER",
"data",
".",
"The",
"certificates",
"must",
"be",
"concatenated",
"with",
"no",
"intermediate",
"padding",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1525-L1548 | train |
tjfoc/gmsm | sm2/x509.go | asn1BitLength | func asn1BitLength(bitString []byte) int {
bitLen := len(bitString) * 8
for i := range bitString {
b := bitString[len(bitString)-i-1]
for bit := uint(0); bit < 8; bit++ {
if (b>>bit)&1 == 1 {
return bitLen
}
bitLen--
}
}
return 0
} | go | func asn1BitLength(bitString []byte) int {
bitLen := len(bitString) * 8
for i := range bitString {
b := bitString[len(bitString)-i-1]
for bit := uint(0); bit < 8; bit++ {
if (b>>bit)&1 == 1 {
return bitLen
}
bitLen--
}
}
return 0
} | [
"func",
"asn1BitLength",
"(",
"bitString",
"[",
"]",
"byte",
")",
"int",
"{",
"bitLen",
":=",
"len",
"(",
"bitString",
")",
"*",
"8",
"\n\n",
"for",
"i",
":=",
"range",
"bitString",
"{",
"b",
":=",
"bitString",
"[",
"len",
"(",
"bitString",
")",
"-",... | // asn1BitLength returns the bit-length of bitString by considering the
// most-significant bit in a byte to be the "first" bit. This convention
// matches ASN.1, but differs from almost everything else. | [
"asn1BitLength",
"returns",
"the",
"bit",
"-",
"length",
"of",
"bitString",
"by",
"considering",
"the",
"most",
"-",
"significant",
"bit",
"in",
"a",
"byte",
"to",
"be",
"the",
"first",
"bit",
".",
"This",
"convention",
"matches",
"ASN",
".",
"1",
"but",
... | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1560-L1575 | train |
tjfoc/gmsm | sm2/x509.go | marshalSANs | func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) {
var rawValues []asn1.RawValue
for _, name := range dnsNames {
rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
}
for _, email := range emailAddresses {
rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
}
for _, rawIP := range ipAddresses {
// If possible, we always want to encode IPv4 addresses in 4 bytes.
ip := rawIP.To4()
if ip == nil {
ip = rawIP
}
rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
}
return asn1.Marshal(rawValues)
} | go | func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) {
var rawValues []asn1.RawValue
for _, name := range dnsNames {
rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
}
for _, email := range emailAddresses {
rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
}
for _, rawIP := range ipAddresses {
// If possible, we always want to encode IPv4 addresses in 4 bytes.
ip := rawIP.To4()
if ip == nil {
ip = rawIP
}
rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
}
return asn1.Marshal(rawValues)
} | [
"func",
"marshalSANs",
"(",
"dnsNames",
",",
"emailAddresses",
"[",
"]",
"string",
",",
"ipAddresses",
"[",
"]",
"net",
".",
"IP",
")",
"(",
"derBytes",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"var",
"rawValues",
"[",
"]",
"asn1",
".",
"RawV... | // marshalSANs marshals a list of addresses into a the contents of an X.509
// SubjectAlternativeName extension. | [
"marshalSANs",
"marshals",
"a",
"list",
"of",
"addresses",
"into",
"a",
"the",
"contents",
"of",
"an",
"X",
".",
"509",
"SubjectAlternativeName",
"extension",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1608-L1625 | train |
tjfoc/gmsm | sm2/x509.go | signingParamsForPublicKey | func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
var pubType PublicKeyAlgorithm
switch pub := pub.(type) {
case *rsa.PublicKey:
pubType = RSA
hashFunc = SHA256
sigAlgo.Algorithm = oidSignatureSHA256WithRSA
sigAlgo.Parameters = asn1.RawValue{
Tag: 5,
}
case *ecdsa.PublicKey:
pubType = ECDSA
switch pub.Curve {
case elliptic.P224(), elliptic.P256():
hashFunc = SHA256
sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
case elliptic.P384():
hashFunc = SHA384
sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
case elliptic.P521():
hashFunc = SHA512
sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
default:
err = errors.New("x509: unknown elliptic curve")
}
case *PublicKey:
pubType = ECDSA
switch pub.Curve {
case P256Sm2():
hashFunc = SM3
sigAlgo.Algorithm = oidSignatureSM2WithSM3
default:
err = errors.New("x509: unknown SM2 curve")
}
default:
err = errors.New("x509: only RSA and ECDSA keys supported")
}
if err != nil {
return
}
if requestedSigAlgo == 0 {
return
}
found := false
for _, details := range signatureAlgorithmDetails {
if details.algo == requestedSigAlgo {
if details.pubKeyAlgo != pubType {
err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
return
}
sigAlgo.Algorithm, hashFunc = details.oid, details.hash
if hashFunc == 0 {
err = errors.New("x509: cannot sign with hash function requested")
return
}
if requestedSigAlgo.isRSAPSS() {
sigAlgo.Parameters = rsaPSSParameters(hashFunc)
}
found = true
break
}
}
if !found {
err = errors.New("x509: unknown SignatureAlgorithm")
}
return
} | go | func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
var pubType PublicKeyAlgorithm
switch pub := pub.(type) {
case *rsa.PublicKey:
pubType = RSA
hashFunc = SHA256
sigAlgo.Algorithm = oidSignatureSHA256WithRSA
sigAlgo.Parameters = asn1.RawValue{
Tag: 5,
}
case *ecdsa.PublicKey:
pubType = ECDSA
switch pub.Curve {
case elliptic.P224(), elliptic.P256():
hashFunc = SHA256
sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
case elliptic.P384():
hashFunc = SHA384
sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
case elliptic.P521():
hashFunc = SHA512
sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
default:
err = errors.New("x509: unknown elliptic curve")
}
case *PublicKey:
pubType = ECDSA
switch pub.Curve {
case P256Sm2():
hashFunc = SM3
sigAlgo.Algorithm = oidSignatureSM2WithSM3
default:
err = errors.New("x509: unknown SM2 curve")
}
default:
err = errors.New("x509: only RSA and ECDSA keys supported")
}
if err != nil {
return
}
if requestedSigAlgo == 0 {
return
}
found := false
for _, details := range signatureAlgorithmDetails {
if details.algo == requestedSigAlgo {
if details.pubKeyAlgo != pubType {
err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
return
}
sigAlgo.Algorithm, hashFunc = details.oid, details.hash
if hashFunc == 0 {
err = errors.New("x509: cannot sign with hash function requested")
return
}
if requestedSigAlgo.isRSAPSS() {
sigAlgo.Parameters = rsaPSSParameters(hashFunc)
}
found = true
break
}
}
if !found {
err = errors.New("x509: unknown SignatureAlgorithm")
}
return
} | [
"func",
"signingParamsForPublicKey",
"(",
"pub",
"interface",
"{",
"}",
",",
"requestedSigAlgo",
"SignatureAlgorithm",
")",
"(",
"hashFunc",
"Hash",
",",
"sigAlgo",
"pkix",
".",
"AlgorithmIdentifier",
",",
"err",
"error",
")",
"{",
"var",
"pubType",
"PublicKeyAlgo... | // signingParamsForPublicKey returns the parameters to use for signing with
// priv. If requestedSigAlgo is not zero then it overrides the default
// signature algorithm. | [
"signingParamsForPublicKey",
"returns",
"the",
"parameters",
"to",
"use",
"for",
"signing",
"with",
"priv",
".",
"If",
"requestedSigAlgo",
"is",
"not",
"zero",
"then",
"it",
"overrides",
"the",
"default",
"signature",
"algorithm",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1814-L1887 | train |
tjfoc/gmsm | sm2/x509.go | ParseCRL | func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
block, _ := pem.Decode(crlBytes)
if block != nil && block.Type == pemType {
crlBytes = block.Bytes
}
}
return ParseDERCRL(crlBytes)
} | go | func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
block, _ := pem.Decode(crlBytes)
if block != nil && block.Type == pemType {
crlBytes = block.Bytes
}
}
return ParseDERCRL(crlBytes)
} | [
"func",
"ParseCRL",
"(",
"crlBytes",
"[",
"]",
"byte",
")",
"(",
"*",
"pkix",
".",
"CertificateList",
",",
"error",
")",
"{",
"if",
"bytes",
".",
"HasPrefix",
"(",
"crlBytes",
",",
"pemCRLPrefix",
")",
"{",
"block",
",",
"_",
":=",
"pem",
".",
"Decod... | // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
// encoded CRLs will appear where they should be DER encoded, so this function
// will transparently handle PEM encoding as long as there isn't any leading
// garbage. | [
"ParseCRL",
"parses",
"a",
"CRL",
"from",
"the",
"given",
"bytes",
".",
"It",
"s",
"often",
"the",
"case",
"that",
"PEM",
"encoded",
"CRLs",
"will",
"appear",
"where",
"they",
"should",
"be",
"DER",
"encoded",
"so",
"this",
"function",
"will",
"transparent... | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2003-L2011 | train |
tjfoc/gmsm | sm2/x509.go | ParseDERCRL | func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
certList := new(pkix.CertificateList)
if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
return nil, err
} else if len(rest) != 0 {
return nil, errors.New("x509: trailing data after CRL")
}
return certList, nil
} | go | func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
certList := new(pkix.CertificateList)
if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
return nil, err
} else if len(rest) != 0 {
return nil, errors.New("x509: trailing data after CRL")
}
return certList, nil
} | [
"func",
"ParseDERCRL",
"(",
"derBytes",
"[",
"]",
"byte",
")",
"(",
"*",
"pkix",
".",
"CertificateList",
",",
"error",
")",
"{",
"certList",
":=",
"new",
"(",
"pkix",
".",
"CertificateList",
")",
"\n",
"if",
"rest",
",",
"err",
":=",
"asn1",
".",
"Un... | // ParseDERCRL parses a DER encoded CRL from the given bytes. | [
"ParseDERCRL",
"parses",
"a",
"DER",
"encoded",
"CRL",
"from",
"the",
"given",
"bytes",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2014-L2022 | train |
tjfoc/gmsm | sm2/x509.go | CreateCRL | func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
key, ok := priv.(crypto.Signer)
if !ok {
return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
}
hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
if err != nil {
return nil, err
}
// Force revocation times to UTC per RFC 5280.
revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
for i, rc := range revokedCerts {
rc.RevocationTime = rc.RevocationTime.UTC()
revokedCertsUTC[i] = rc
}
tbsCertList := pkix.TBSCertificateList{
Version: 1,
Signature: signatureAlgorithm,
Issuer: c.Subject.ToRDNSequence(),
ThisUpdate: now.UTC(),
NextUpdate: expiry.UTC(),
RevokedCertificates: revokedCertsUTC,
}
// Authority Key Id
if len(c.SubjectKeyId) > 0 {
var aki pkix.Extension
aki.Id = oidExtensionAuthorityKeyId
aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
if err != nil {
return
}
tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
}
tbsCertListContents, err := asn1.Marshal(tbsCertList)
if err != nil {
return
}
digest := tbsCertListContents
switch hashFunc {
case SM3:
break
default:
h := hashFunc.New()
h.Write(tbsCertListContents)
digest = h.Sum(nil)
}
var signature []byte
signature, err = key.Sign(rand, digest, hashFunc)
if err != nil {
return
}
return asn1.Marshal(pkix.CertificateList{
TBSCertList: tbsCertList,
SignatureAlgorithm: signatureAlgorithm,
SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
})
} | go | func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
key, ok := priv.(crypto.Signer)
if !ok {
return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
}
hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
if err != nil {
return nil, err
}
// Force revocation times to UTC per RFC 5280.
revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
for i, rc := range revokedCerts {
rc.RevocationTime = rc.RevocationTime.UTC()
revokedCertsUTC[i] = rc
}
tbsCertList := pkix.TBSCertificateList{
Version: 1,
Signature: signatureAlgorithm,
Issuer: c.Subject.ToRDNSequence(),
ThisUpdate: now.UTC(),
NextUpdate: expiry.UTC(),
RevokedCertificates: revokedCertsUTC,
}
// Authority Key Id
if len(c.SubjectKeyId) > 0 {
var aki pkix.Extension
aki.Id = oidExtensionAuthorityKeyId
aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
if err != nil {
return
}
tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
}
tbsCertListContents, err := asn1.Marshal(tbsCertList)
if err != nil {
return
}
digest := tbsCertListContents
switch hashFunc {
case SM3:
break
default:
h := hashFunc.New()
h.Write(tbsCertListContents)
digest = h.Sum(nil)
}
var signature []byte
signature, err = key.Sign(rand, digest, hashFunc)
if err != nil {
return
}
return asn1.Marshal(pkix.CertificateList{
TBSCertList: tbsCertList,
SignatureAlgorithm: signatureAlgorithm,
SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
})
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"CreateCRL",
"(",
"rand",
"io",
".",
"Reader",
",",
"priv",
"interface",
"{",
"}",
",",
"revokedCerts",
"[",
"]",
"pkix",
".",
"RevokedCertificate",
",",
"now",
",",
"expiry",
"time",
".",
"Time",
")",
"(",
... | // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
// contains the given list of revoked certificates. | [
"CreateCRL",
"returns",
"a",
"DER",
"encoded",
"CRL",
"signed",
"by",
"this",
"Certificate",
"that",
"contains",
"the",
"given",
"list",
"of",
"revoked",
"certificates",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2026-L2090 | train |
tjfoc/gmsm | sm2/x509.go | newRawAttributes | func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
var rawAttributes []asn1.RawValue
b, err := asn1.Marshal(attributes)
if err != nil {
return nil, err
}
rest, err := asn1.Unmarshal(b, &rawAttributes)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
}
return rawAttributes, nil
} | go | func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
var rawAttributes []asn1.RawValue
b, err := asn1.Marshal(attributes)
if err != nil {
return nil, err
}
rest, err := asn1.Unmarshal(b, &rawAttributes)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
}
return rawAttributes, nil
} | [
"func",
"newRawAttributes",
"(",
"attributes",
"[",
"]",
"pkix",
".",
"AttributeTypeAndValueSET",
")",
"(",
"[",
"]",
"asn1",
".",
"RawValue",
",",
"error",
")",
"{",
"var",
"rawAttributes",
"[",
"]",
"asn1",
".",
"RawValue",
"\n",
"b",
",",
"err",
":=",... | // newRawAttributes converts AttributeTypeAndValueSETs from a template
// CertificateRequest's Attributes into tbsCertificateRequest RawAttributes. | [
"newRawAttributes",
"converts",
"AttributeTypeAndValueSETs",
"from",
"a",
"template",
"CertificateRequest",
"s",
"Attributes",
"into",
"tbsCertificateRequest",
"RawAttributes",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2155-L2169 | train |
tjfoc/gmsm | sm2/x509.go | parseRawAttributes | func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
var attributes []pkix.AttributeTypeAndValueSET
for _, rawAttr := range rawAttributes {
var attr pkix.AttributeTypeAndValueSET
rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
// Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
// (i.e.: challengePassword or unstructuredName).
if err == nil && len(rest) == 0 {
attributes = append(attributes, attr)
}
}
return attributes
} | go | func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
var attributes []pkix.AttributeTypeAndValueSET
for _, rawAttr := range rawAttributes {
var attr pkix.AttributeTypeAndValueSET
rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
// Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
// (i.e.: challengePassword or unstructuredName).
if err == nil && len(rest) == 0 {
attributes = append(attributes, attr)
}
}
return attributes
} | [
"func",
"parseRawAttributes",
"(",
"rawAttributes",
"[",
"]",
"asn1",
".",
"RawValue",
")",
"[",
"]",
"pkix",
".",
"AttributeTypeAndValueSET",
"{",
"var",
"attributes",
"[",
"]",
"pkix",
".",
"AttributeTypeAndValueSET",
"\n",
"for",
"_",
",",
"rawAttr",
":=",
... | // parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs. | [
"parseRawAttributes",
"Unmarshals",
"RawAttributes",
"intos",
"AttributeTypeAndValueSETs",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2172-L2184 | train |
tjfoc/gmsm | sm2/x509.go | parseCSRExtensions | func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
// pkcs10Attribute reflects the Attribute structure from section 4.1 of
// https://tools.ietf.org/html/rfc2986.
type pkcs10Attribute struct {
Id asn1.ObjectIdentifier
Values []asn1.RawValue `asn1:"set"`
}
var ret []pkix.Extension
for _, rawAttr := range rawAttributes {
var attr pkcs10Attribute
if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
// Ignore attributes that don't parse.
continue
}
if !attr.Id.Equal(oidExtensionRequest) {
continue
}
var extensions []pkix.Extension
if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
return nil, err
}
ret = append(ret, extensions...)
}
return ret, nil
} | go | func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
// pkcs10Attribute reflects the Attribute structure from section 4.1 of
// https://tools.ietf.org/html/rfc2986.
type pkcs10Attribute struct {
Id asn1.ObjectIdentifier
Values []asn1.RawValue `asn1:"set"`
}
var ret []pkix.Extension
for _, rawAttr := range rawAttributes {
var attr pkcs10Attribute
if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
// Ignore attributes that don't parse.
continue
}
if !attr.Id.Equal(oidExtensionRequest) {
continue
}
var extensions []pkix.Extension
if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
return nil, err
}
ret = append(ret, extensions...)
}
return ret, nil
} | [
"func",
"parseCSRExtensions",
"(",
"rawAttributes",
"[",
"]",
"asn1",
".",
"RawValue",
")",
"(",
"[",
"]",
"pkix",
".",
"Extension",
",",
"error",
")",
"{",
"// pkcs10Attribute reflects the Attribute structure from section 4.1 of",
"// https://tools.ietf.org/html/rfc2986.",... | // parseCSRExtensions parses the attributes from a CSR and extracts any
// requested extensions. | [
"parseCSRExtensions",
"parses",
"the",
"attributes",
"from",
"a",
"CSR",
"and",
"extracts",
"any",
"requested",
"extensions",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2188-L2216 | train |
tjfoc/gmsm | sm2/x509.go | ParseCertificateRequest | func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
var csr certificateRequest
rest, err := asn1.Unmarshal(asn1Data, &csr)
if err != nil {
return nil, err
} else if len(rest) != 0 {
return nil, asn1.SyntaxError{Msg: "trailing data"}
}
return parseCertificateRequest(&csr)
} | go | func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
var csr certificateRequest
rest, err := asn1.Unmarshal(asn1Data, &csr)
if err != nil {
return nil, err
} else if len(rest) != 0 {
return nil, asn1.SyntaxError{Msg: "trailing data"}
}
return parseCertificateRequest(&csr)
} | [
"func",
"ParseCertificateRequest",
"(",
"asn1Data",
"[",
"]",
"byte",
")",
"(",
"*",
"CertificateRequest",
",",
"error",
")",
"{",
"var",
"csr",
"certificateRequest",
"\n\n",
"rest",
",",
"err",
":=",
"asn1",
".",
"Unmarshal",
"(",
"asn1Data",
",",
"&",
"c... | // ParseCertificateRequest parses a single certificate request from the
// given ASN.1 DER data. | [
"ParseCertificateRequest",
"parses",
"a",
"single",
"certificate",
"request",
"from",
"the",
"given",
"ASN",
".",
"1",
"DER",
"data",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2382-L2393 | train |
tjfoc/gmsm | sm2/x509.go | CheckSignature | func (c *CertificateRequest) CheckSignature() error {
return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
} | go | func (c *CertificateRequest) CheckSignature() error {
return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
} | [
"func",
"(",
"c",
"*",
"CertificateRequest",
")",
"CheckSignature",
"(",
")",
"error",
"{",
"return",
"checkSignature",
"(",
"c",
".",
"SignatureAlgorithm",
",",
"c",
".",
"RawTBSCertificateRequest",
",",
"c",
".",
"Signature",
",",
"c",
".",
"PublicKey",
")... | // CheckSignature reports whether the signature on c is valid. | [
"CheckSignature",
"reports",
"whether",
"the",
"signature",
"on",
"c",
"is",
"valid",
"."
] | 18fd8096dc8a3dcd43e9eccbdb4ef598900ae252 | https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2443-L2445 | train |
vmihailenco/msgpack | decode.go | NewDecoder | func NewDecoder(r io.Reader) *Decoder {
d := &Decoder{
buf: makeBuffer(),
}
d.resetReader(r)
return d
} | go | func NewDecoder(r io.Reader) *Decoder {
d := &Decoder{
buf: makeBuffer(),
}
d.resetReader(r)
return d
} | [
"func",
"NewDecoder",
"(",
"r",
"io",
".",
"Reader",
")",
"*",
"Decoder",
"{",
"d",
":=",
"&",
"Decoder",
"{",
"buf",
":",
"makeBuffer",
"(",
")",
",",
"}",
"\n",
"d",
".",
"resetReader",
"(",
"r",
")",
"\n",
"return",
"d",
"\n",
"}"
] | // NewDecoder returns a new decoder that reads from r.
//
// The decoder introduces its own buffering and may read data from r
// beyond the MessagePack values requested. Buffering can be disabled
// by passing a reader that implements io.ByteScanner interface. | [
"NewDecoder",
"returns",
"a",
"new",
"decoder",
"that",
"reads",
"from",
"r",
".",
"The",
"decoder",
"introduces",
"its",
"own",
"buffering",
"and",
"may",
"read",
"data",
"from",
"r",
"beyond",
"the",
"MessagePack",
"values",
"requested",
".",
"Buffering",
... | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode.go#L58-L64 | train |
vmihailenco/msgpack | decode.go | UseJSONTag | func (d *Decoder) UseJSONTag(v bool) *Decoder {
d.useJSONTag = v
return d
} | go | func (d *Decoder) UseJSONTag(v bool) *Decoder {
d.useJSONTag = v
return d
} | [
"func",
"(",
"d",
"*",
"Decoder",
")",
"UseJSONTag",
"(",
"v",
"bool",
")",
"*",
"Decoder",
"{",
"d",
".",
"useJSONTag",
"=",
"v",
"\n",
"return",
"d",
"\n",
"}"
] | // UseJSONTag causes the Decoder to use json struct tag as fallback option
// if there is no msgpack tag. | [
"UseJSONTag",
"causes",
"the",
"Decoder",
"to",
"use",
"json",
"struct",
"tag",
"as",
"fallback",
"option",
"if",
"there",
"is",
"no",
"msgpack",
"tag",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode.go#L79-L82 | train |
vmihailenco/msgpack | decode.go | Skip | func (d *Decoder) Skip() error {
c, err := d.readCode()
if err != nil {
return err
}
if codes.IsFixedNum(c) {
return nil
} else if codes.IsFixedMap(c) {
return d.skipMap(c)
} else if codes.IsFixedArray(c) {
return d.skipSlice(c)
} else if codes.IsFixedString(c) {
return d.skipBytes(c)
}
switch c {
case codes.Nil, codes.False, codes.True:
return nil
case codes.Uint8, codes.Int8:
return d.skipN(1)
case codes.Uint16, codes.Int16:
return d.skipN(2)
case codes.Uint32, codes.Int32, codes.Float:
return d.skipN(4)
case codes.Uint64, codes.Int64, codes.Double:
return d.skipN(8)
case codes.Bin8, codes.Bin16, codes.Bin32:
return d.skipBytes(c)
case codes.Str8, codes.Str16, codes.Str32:
return d.skipBytes(c)
case codes.Array16, codes.Array32:
return d.skipSlice(c)
case codes.Map16, codes.Map32:
return d.skipMap(c)
case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16,
codes.Ext8, codes.Ext16, codes.Ext32:
return d.skipExt(c)
}
return fmt.Errorf("msgpack: unknown code %x", c)
} | go | func (d *Decoder) Skip() error {
c, err := d.readCode()
if err != nil {
return err
}
if codes.IsFixedNum(c) {
return nil
} else if codes.IsFixedMap(c) {
return d.skipMap(c)
} else if codes.IsFixedArray(c) {
return d.skipSlice(c)
} else if codes.IsFixedString(c) {
return d.skipBytes(c)
}
switch c {
case codes.Nil, codes.False, codes.True:
return nil
case codes.Uint8, codes.Int8:
return d.skipN(1)
case codes.Uint16, codes.Int16:
return d.skipN(2)
case codes.Uint32, codes.Int32, codes.Float:
return d.skipN(4)
case codes.Uint64, codes.Int64, codes.Double:
return d.skipN(8)
case codes.Bin8, codes.Bin16, codes.Bin32:
return d.skipBytes(c)
case codes.Str8, codes.Str16, codes.Str32:
return d.skipBytes(c)
case codes.Array16, codes.Array32:
return d.skipSlice(c)
case codes.Map16, codes.Map32:
return d.skipMap(c)
case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16,
codes.Ext8, codes.Ext16, codes.Ext32:
return d.skipExt(c)
}
return fmt.Errorf("msgpack: unknown code %x", c)
} | [
"func",
"(",
"d",
"*",
"Decoder",
")",
"Skip",
"(",
")",
"error",
"{",
"c",
",",
"err",
":=",
"d",
".",
"readCode",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"codes",
".",
"IsFixedNum",
"(",
"c",
... | // Skip skips next value. | [
"Skip",
"skips",
"next",
"value",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode.go#L408-L449 | train |
vmihailenco/msgpack | decode_map.go | DecodeMapLen | func (d *Decoder) DecodeMapLen() (int, error) {
c, err := d.readCode()
if err != nil {
return 0, err
}
if codes.IsExt(c) {
if err = d.skipExtHeader(c); err != nil {
return 0, err
}
c, err = d.readCode()
if err != nil {
return 0, err
}
}
return d.mapLen(c)
} | go | func (d *Decoder) DecodeMapLen() (int, error) {
c, err := d.readCode()
if err != nil {
return 0, err
}
if codes.IsExt(c) {
if err = d.skipExtHeader(c); err != nil {
return 0, err
}
c, err = d.readCode()
if err != nil {
return 0, err
}
}
return d.mapLen(c)
} | [
"func",
"(",
"d",
"*",
"Decoder",
")",
"DecodeMapLen",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"d",
".",
"readCode",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"if... | // DecodeMapLen decodes map length. Length is -1 when map is nil. | [
"DecodeMapLen",
"decodes",
"map",
"length",
".",
"Length",
"is",
"-",
"1",
"when",
"map",
"is",
"nil",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode_map.go#L66-L83 | train |
vmihailenco/msgpack | encode.go | StructAsArray | func (e *Encoder) StructAsArray(flag bool) *Encoder {
e.structAsArray = flag
return e
} | go | func (e *Encoder) StructAsArray(flag bool) *Encoder {
e.structAsArray = flag
return e
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"StructAsArray",
"(",
"flag",
"bool",
")",
"*",
"Encoder",
"{",
"e",
".",
"structAsArray",
"=",
"flag",
"\n",
"return",
"e",
"\n",
"}"
] | // StructAsArray causes the Encoder to encode Go structs as MessagePack arrays. | [
"StructAsArray",
"causes",
"the",
"Encoder",
"to",
"encode",
"Go",
"structs",
"as",
"MessagePack",
"arrays",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode.go#L91-L94 | train |
vmihailenco/msgpack | encode.go | UseJSONTag | func (e *Encoder) UseJSONTag(flag bool) *Encoder {
e.useJSONTag = flag
return e
} | go | func (e *Encoder) UseJSONTag(flag bool) *Encoder {
e.useJSONTag = flag
return e
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"UseJSONTag",
"(",
"flag",
"bool",
")",
"*",
"Encoder",
"{",
"e",
".",
"useJSONTag",
"=",
"flag",
"\n",
"return",
"e",
"\n",
"}"
] | // UseJSONTag causes the Encoder to use json struct tag as fallback option
// if there is no msgpack tag. | [
"UseJSONTag",
"causes",
"the",
"Encoder",
"to",
"use",
"json",
"struct",
"tag",
"as",
"fallback",
"option",
"if",
"there",
"is",
"no",
"msgpack",
"tag",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode.go#L98-L101 | train |
vmihailenco/msgpack | encode.go | UseCompactEncoding | func (e *Encoder) UseCompactEncoding(flag bool) *Encoder {
e.useCompact = flag
return e
} | go | func (e *Encoder) UseCompactEncoding(flag bool) *Encoder {
e.useCompact = flag
return e
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"UseCompactEncoding",
"(",
"flag",
"bool",
")",
"*",
"Encoder",
"{",
"e",
".",
"useCompact",
"=",
"flag",
"\n",
"return",
"e",
"\n",
"}"
] | // UseCompactEncoding causes the Encoder to chose the most compact encoding.
// For example, it allows to encode Go int64 as msgpack int8 saving 7 bytes. | [
"UseCompactEncoding",
"causes",
"the",
"Encoder",
"to",
"chose",
"the",
"most",
"compact",
"encoding",
".",
"For",
"example",
"it",
"allows",
"to",
"encode",
"Go",
"int64",
"as",
"msgpack",
"int8",
"saving",
"7",
"bytes",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode.go#L105-L108 | train |
vmihailenco/msgpack | decode_slice.go | DecodeArrayLen | func (d *Decoder) DecodeArrayLen() (int, error) {
c, err := d.readCode()
if err != nil {
return 0, err
}
return d.arrayLen(c)
} | go | func (d *Decoder) DecodeArrayLen() (int, error) {
c, err := d.readCode()
if err != nil {
return 0, err
}
return d.arrayLen(c)
} | [
"func",
"(",
"d",
"*",
"Decoder",
")",
"DecodeArrayLen",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"d",
".",
"readCode",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"re... | // DecodeArrayLen decodes array length. Length is -1 when array is nil. | [
"DecodeArrayLen",
"decodes",
"array",
"length",
".",
"Length",
"is",
"-",
"1",
"when",
"array",
"is",
"nil",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode_slice.go#L15-L21 | train |
vmihailenco/msgpack | encode_number.go | EncodeUint8 | func (e *Encoder) EncodeUint8(n uint8) error {
return e.write1(codes.Uint8, n)
} | go | func (e *Encoder) EncodeUint8(n uint8) error {
return e.write1(codes.Uint8, n)
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeUint8",
"(",
"n",
"uint8",
")",
"error",
"{",
"return",
"e",
".",
"write1",
"(",
"codes",
".",
"Uint8",
",",
"n",
")",
"\n",
"}"
] | // EncodeUint8 encodes an uint8 in 2 bytes preserving type of the number. | [
"EncodeUint8",
"encodes",
"an",
"uint8",
"in",
"2",
"bytes",
"preserving",
"type",
"of",
"the",
"number",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L11-L13 | train |
vmihailenco/msgpack | encode_number.go | EncodeUint16 | func (e *Encoder) EncodeUint16(n uint16) error {
return e.write2(codes.Uint16, n)
} | go | func (e *Encoder) EncodeUint16(n uint16) error {
return e.write2(codes.Uint16, n)
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeUint16",
"(",
"n",
"uint16",
")",
"error",
"{",
"return",
"e",
".",
"write2",
"(",
"codes",
".",
"Uint16",
",",
"n",
")",
"\n",
"}"
] | // EncodeUint16 encodes an uint16 in 3 bytes preserving type of the number. | [
"EncodeUint16",
"encodes",
"an",
"uint16",
"in",
"3",
"bytes",
"preserving",
"type",
"of",
"the",
"number",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L23-L25 | train |
vmihailenco/msgpack | encode_number.go | EncodeUint32 | func (e *Encoder) EncodeUint32(n uint32) error {
return e.write4(codes.Uint32, n)
} | go | func (e *Encoder) EncodeUint32(n uint32) error {
return e.write4(codes.Uint32, n)
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeUint32",
"(",
"n",
"uint32",
")",
"error",
"{",
"return",
"e",
".",
"write4",
"(",
"codes",
".",
"Uint32",
",",
"n",
")",
"\n",
"}"
] | // EncodeUint32 encodes an uint16 in 5 bytes preserving type of the number. | [
"EncodeUint32",
"encodes",
"an",
"uint16",
"in",
"5",
"bytes",
"preserving",
"type",
"of",
"the",
"number",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L35-L37 | train |
vmihailenco/msgpack | encode_number.go | EncodeUint64 | func (e *Encoder) EncodeUint64(n uint64) error {
return e.write8(codes.Uint64, n)
} | go | func (e *Encoder) EncodeUint64(n uint64) error {
return e.write8(codes.Uint64, n)
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeUint64",
"(",
"n",
"uint64",
")",
"error",
"{",
"return",
"e",
".",
"write8",
"(",
"codes",
".",
"Uint64",
",",
"n",
")",
"\n",
"}"
] | // EncodeUint64 encodes an uint16 in 9 bytes preserving type of the number. | [
"EncodeUint64",
"encodes",
"an",
"uint16",
"in",
"9",
"bytes",
"preserving",
"type",
"of",
"the",
"number",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L47-L49 | train |
vmihailenco/msgpack | encode_number.go | EncodeInt8 | func (e *Encoder) EncodeInt8(n int8) error {
return e.write1(codes.Int8, uint8(n))
} | go | func (e *Encoder) EncodeInt8(n int8) error {
return e.write1(codes.Int8, uint8(n))
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeInt8",
"(",
"n",
"int8",
")",
"error",
"{",
"return",
"e",
".",
"write1",
"(",
"codes",
".",
"Int8",
",",
"uint8",
"(",
"n",
")",
")",
"\n",
"}"
] | // EncodeInt8 encodes an int8 in 2 bytes preserving type of the number. | [
"EncodeInt8",
"encodes",
"an",
"int8",
"in",
"2",
"bytes",
"preserving",
"type",
"of",
"the",
"number",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L59-L61 | train |
vmihailenco/msgpack | encode_number.go | EncodeInt16 | func (e *Encoder) EncodeInt16(n int16) error {
return e.write2(codes.Int16, uint16(n))
} | go | func (e *Encoder) EncodeInt16(n int16) error {
return e.write2(codes.Int16, uint16(n))
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeInt16",
"(",
"n",
"int16",
")",
"error",
"{",
"return",
"e",
".",
"write2",
"(",
"codes",
".",
"Int16",
",",
"uint16",
"(",
"n",
")",
")",
"\n",
"}"
] | // EncodeInt16 encodes an int16 in 3 bytes preserving type of the number. | [
"EncodeInt16",
"encodes",
"an",
"int16",
"in",
"3",
"bytes",
"preserving",
"type",
"of",
"the",
"number",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L71-L73 | train |
vmihailenco/msgpack | encode_number.go | EncodeInt32 | func (e *Encoder) EncodeInt32(n int32) error {
return e.write4(codes.Int32, uint32(n))
} | go | func (e *Encoder) EncodeInt32(n int32) error {
return e.write4(codes.Int32, uint32(n))
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeInt32",
"(",
"n",
"int32",
")",
"error",
"{",
"return",
"e",
".",
"write4",
"(",
"codes",
".",
"Int32",
",",
"uint32",
"(",
"n",
")",
")",
"\n",
"}"
] | // EncodeInt32 encodes an int32 in 5 bytes preserving type of the number. | [
"EncodeInt32",
"encodes",
"an",
"int32",
"in",
"5",
"bytes",
"preserving",
"type",
"of",
"the",
"number",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L83-L85 | train |
vmihailenco/msgpack | encode_number.go | EncodeInt64 | func (e *Encoder) EncodeInt64(n int64) error {
return e.write8(codes.Int64, uint64(n))
} | go | func (e *Encoder) EncodeInt64(n int64) error {
return e.write8(codes.Int64, uint64(n))
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeInt64",
"(",
"n",
"int64",
")",
"error",
"{",
"return",
"e",
".",
"write8",
"(",
"codes",
".",
"Int64",
",",
"uint64",
"(",
"n",
")",
")",
"\n",
"}"
] | // EncodeInt64 encodes an int64 in 9 bytes preserving type of the number. | [
"EncodeInt64",
"encodes",
"an",
"int64",
"in",
"9",
"bytes",
"preserving",
"type",
"of",
"the",
"number",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L95-L97 | train |
vmihailenco/msgpack | encode_number.go | EncodeUint | func (e *Encoder) EncodeUint(n uint64) error {
if n <= math.MaxInt8 {
return e.w.WriteByte(byte(n))
}
if n <= math.MaxUint8 {
return e.EncodeUint8(uint8(n))
}
if n <= math.MaxUint16 {
return e.EncodeUint16(uint16(n))
}
if n <= math.MaxUint32 {
return e.EncodeUint32(uint32(n))
}
return e.EncodeUint64(uint64(n))
} | go | func (e *Encoder) EncodeUint(n uint64) error {
if n <= math.MaxInt8 {
return e.w.WriteByte(byte(n))
}
if n <= math.MaxUint8 {
return e.EncodeUint8(uint8(n))
}
if n <= math.MaxUint16 {
return e.EncodeUint16(uint16(n))
}
if n <= math.MaxUint32 {
return e.EncodeUint32(uint32(n))
}
return e.EncodeUint64(uint64(n))
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeUint",
"(",
"n",
"uint64",
")",
"error",
"{",
"if",
"n",
"<=",
"math",
".",
"MaxInt8",
"{",
"return",
"e",
".",
"w",
".",
"WriteByte",
"(",
"byte",
"(",
"n",
")",
")",
"\n",
"}",
"\n",
"if",
"n",
... | // EncodeUnsignedNumber encodes an uint64 in 1, 2, 3, 5, or 9 bytes.
// Type of the number is lost during encoding. | [
"EncodeUnsignedNumber",
"encodes",
"an",
"uint64",
"in",
"1",
"2",
"3",
"5",
"or",
"9",
"bytes",
".",
"Type",
"of",
"the",
"number",
"is",
"lost",
"during",
"encoding",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L108-L122 | train |
vmihailenco/msgpack | encode_number.go | EncodeInt | func (e *Encoder) EncodeInt(n int64) error {
if n >= 0 {
return e.EncodeUint(uint64(n))
}
if n >= int64(int8(codes.NegFixedNumLow)) {
return e.w.WriteByte(byte(n))
}
if n >= math.MinInt8 {
return e.EncodeInt8(int8(n))
}
if n >= math.MinInt16 {
return e.EncodeInt16(int16(n))
}
if n >= math.MinInt32 {
return e.EncodeInt32(int32(n))
}
return e.EncodeInt64(int64(n))
} | go | func (e *Encoder) EncodeInt(n int64) error {
if n >= 0 {
return e.EncodeUint(uint64(n))
}
if n >= int64(int8(codes.NegFixedNumLow)) {
return e.w.WriteByte(byte(n))
}
if n >= math.MinInt8 {
return e.EncodeInt8(int8(n))
}
if n >= math.MinInt16 {
return e.EncodeInt16(int16(n))
}
if n >= math.MinInt32 {
return e.EncodeInt32(int32(n))
}
return e.EncodeInt64(int64(n))
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"EncodeInt",
"(",
"n",
"int64",
")",
"error",
"{",
"if",
"n",
">=",
"0",
"{",
"return",
"e",
".",
"EncodeUint",
"(",
"uint64",
"(",
"n",
")",
")",
"\n",
"}",
"\n",
"if",
"n",
">=",
"int64",
"(",
"int8",
... | // EncodeNumber encodes an int64 in 1, 2, 3, 5, or 9 bytes.
// Type of number is lost during encoding. | [
"EncodeNumber",
"encodes",
"an",
"int64",
"in",
"1",
"2",
"3",
"5",
"or",
"9",
"bytes",
".",
"Type",
"of",
"number",
"is",
"lost",
"during",
"encoding",
"."
] | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L126-L143 | train |
vmihailenco/msgpack | ext.go | RegisterExt | func RegisterExt(id int8, value interface{}) {
typ := reflect.TypeOf(value)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
ptr := reflect.PtrTo(typ)
if _, ok := extTypes[id]; ok {
panic(fmt.Errorf("msgpack: ext with id=%d is already registered", id))
}
registerExt(id, ptr, getEncoder(ptr), getDecoder(ptr))
registerExt(id, typ, getEncoder(typ), getDecoder(typ))
} | go | func RegisterExt(id int8, value interface{}) {
typ := reflect.TypeOf(value)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
ptr := reflect.PtrTo(typ)
if _, ok := extTypes[id]; ok {
panic(fmt.Errorf("msgpack: ext with id=%d is already registered", id))
}
registerExt(id, ptr, getEncoder(ptr), getDecoder(ptr))
registerExt(id, typ, getEncoder(typ), getDecoder(typ))
} | [
"func",
"RegisterExt",
"(",
"id",
"int8",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"value",
")",
"\n",
"if",
"typ",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"typ",
"=",
"typ",
".",... | // RegisterExt records a type, identified by a value for that type,
// under the provided id. That id will identify the concrete type of a value
// sent or received as an interface variable. Only types that will be
// transferred as implementations of interface values need to be registered.
// Expecting to be used only during initialization, it panics if the mapping
// between types and ids is not a bijection. | [
"RegisterExt",
"records",
"a",
"type",
"identified",
"by",
"a",
"value",
"for",
"that",
"type",
"under",
"the",
"provided",
"id",
".",
"That",
"id",
"will",
"identify",
"the",
"concrete",
"type",
"of",
"a",
"value",
"sent",
"or",
"received",
"as",
"an",
... | 5467b4fb032b68b160f4acce954153280cf5e05b | https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/ext.go#L31-L44 | train |
minio/minio-go | bucket-notification.go | NewArn | func NewArn(partition, service, region, accountID, resource string) Arn {
return Arn{Partition: partition,
Service: service,
Region: region,
AccountID: accountID,
Resource: resource}
} | go | func NewArn(partition, service, region, accountID, resource string) Arn {
return Arn{Partition: partition,
Service: service,
Region: region,
AccountID: accountID,
Resource: resource}
} | [
"func",
"NewArn",
"(",
"partition",
",",
"service",
",",
"region",
",",
"accountID",
",",
"resource",
"string",
")",
"Arn",
"{",
"return",
"Arn",
"{",
"Partition",
":",
"partition",
",",
"Service",
":",
"service",
",",
"Region",
":",
"region",
",",
"Acco... | // NewArn creates new ARN based on the given partition, service, region, account id and resource | [
"NewArn",
"creates",
"new",
"ARN",
"based",
"on",
"the",
"given",
"partition",
"service",
"region",
"account",
"id",
"and",
"resource"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L76-L82 | train |
minio/minio-go | bucket-notification.go | String | func (arn Arn) String() string {
return "arn:" + arn.Partition + ":" + arn.Service + ":" + arn.Region + ":" + arn.AccountID + ":" + arn.Resource
} | go | func (arn Arn) String() string {
return "arn:" + arn.Partition + ":" + arn.Service + ":" + arn.Region + ":" + arn.AccountID + ":" + arn.Resource
} | [
"func",
"(",
"arn",
"Arn",
")",
"String",
"(",
")",
"string",
"{",
"return",
"\"",
"\"",
"+",
"arn",
".",
"Partition",
"+",
"\"",
"\"",
"+",
"arn",
".",
"Service",
"+",
"\"",
"\"",
"+",
"arn",
".",
"Region",
"+",
"\"",
"\"",
"+",
"arn",
".",
... | // Return the string format of the ARN | [
"Return",
"the",
"string",
"format",
"of",
"the",
"ARN"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L85-L87 | train |
minio/minio-go | bucket-notification.go | AddEvents | func (t *NotificationConfig) AddEvents(events ...NotificationEventType) {
t.Events = append(t.Events, events...)
} | go | func (t *NotificationConfig) AddEvents(events ...NotificationEventType) {
t.Events = append(t.Events, events...)
} | [
"func",
"(",
"t",
"*",
"NotificationConfig",
")",
"AddEvents",
"(",
"events",
"...",
"NotificationEventType",
")",
"{",
"t",
".",
"Events",
"=",
"append",
"(",
"t",
".",
"Events",
",",
"events",
"...",
")",
"\n",
"}"
] | // AddEvents adds one event to the current notification config | [
"AddEvents",
"adds",
"one",
"event",
"to",
"the",
"current",
"notification",
"config"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L104-L106 | train |
minio/minio-go | bucket-notification.go | AddFilterSuffix | func (t *NotificationConfig) AddFilterSuffix(suffix string) {
if t.Filter == nil {
t.Filter = &Filter{}
}
newFilterRule := FilterRule{Name: "suffix", Value: suffix}
// Replace any suffix rule if existing and add to the list otherwise
for index := range t.Filter.S3Key.FilterRules {
if t.Filter.S3Key.FilterRules[index].Name == "suffix" {
t.Filter.S3Key.FilterRules[index] = newFilterRule
return
}
}
t.Filter.S3Key.FilterRules = append(t.Filter.S3Key.FilterRules, newFilterRule)
} | go | func (t *NotificationConfig) AddFilterSuffix(suffix string) {
if t.Filter == nil {
t.Filter = &Filter{}
}
newFilterRule := FilterRule{Name: "suffix", Value: suffix}
// Replace any suffix rule if existing and add to the list otherwise
for index := range t.Filter.S3Key.FilterRules {
if t.Filter.S3Key.FilterRules[index].Name == "suffix" {
t.Filter.S3Key.FilterRules[index] = newFilterRule
return
}
}
t.Filter.S3Key.FilterRules = append(t.Filter.S3Key.FilterRules, newFilterRule)
} | [
"func",
"(",
"t",
"*",
"NotificationConfig",
")",
"AddFilterSuffix",
"(",
"suffix",
"string",
")",
"{",
"if",
"t",
".",
"Filter",
"==",
"nil",
"{",
"t",
".",
"Filter",
"=",
"&",
"Filter",
"{",
"}",
"\n",
"}",
"\n",
"newFilterRule",
":=",
"FilterRule",
... | // AddFilterSuffix sets the suffix configuration to the current notification config | [
"AddFilterSuffix",
"sets",
"the",
"suffix",
"configuration",
"to",
"the",
"current",
"notification",
"config"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L109-L122 | train |
minio/minio-go | bucket-notification.go | AddFilterPrefix | func (t *NotificationConfig) AddFilterPrefix(prefix string) {
if t.Filter == nil {
t.Filter = &Filter{}
}
newFilterRule := FilterRule{Name: "prefix", Value: prefix}
// Replace any prefix rule if existing and add to the list otherwise
for index := range t.Filter.S3Key.FilterRules {
if t.Filter.S3Key.FilterRules[index].Name == "prefix" {
t.Filter.S3Key.FilterRules[index] = newFilterRule
return
}
}
t.Filter.S3Key.FilterRules = append(t.Filter.S3Key.FilterRules, newFilterRule)
} | go | func (t *NotificationConfig) AddFilterPrefix(prefix string) {
if t.Filter == nil {
t.Filter = &Filter{}
}
newFilterRule := FilterRule{Name: "prefix", Value: prefix}
// Replace any prefix rule if existing and add to the list otherwise
for index := range t.Filter.S3Key.FilterRules {
if t.Filter.S3Key.FilterRules[index].Name == "prefix" {
t.Filter.S3Key.FilterRules[index] = newFilterRule
return
}
}
t.Filter.S3Key.FilterRules = append(t.Filter.S3Key.FilterRules, newFilterRule)
} | [
"func",
"(",
"t",
"*",
"NotificationConfig",
")",
"AddFilterPrefix",
"(",
"prefix",
"string",
")",
"{",
"if",
"t",
".",
"Filter",
"==",
"nil",
"{",
"t",
".",
"Filter",
"=",
"&",
"Filter",
"{",
"}",
"\n",
"}",
"\n",
"newFilterRule",
":=",
"FilterRule",
... | // AddFilterPrefix sets the prefix configuration to the current notification config | [
"AddFilterPrefix",
"sets",
"the",
"prefix",
"configuration",
"to",
"the",
"current",
"notification",
"config"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L125-L138 | train |
minio/minio-go | bucket-notification.go | AddTopic | func (b *BucketNotification) AddTopic(topicConfig NotificationConfig) bool {
newTopicConfig := TopicConfig{NotificationConfig: topicConfig, Topic: topicConfig.Arn.String()}
for _, n := range b.TopicConfigs {
// If new config matches existing one
if n.Topic == newTopicConfig.Arn.String() && newTopicConfig.Filter == n.Filter {
existingConfig := set.NewStringSet()
for _, v := range n.Events {
existingConfig.Add(string(v))
}
newConfig := set.NewStringSet()
for _, v := range topicConfig.Events {
newConfig.Add(string(v))
}
if !newConfig.Intersection(existingConfig).IsEmpty() {
return false
}
}
}
b.TopicConfigs = append(b.TopicConfigs, newTopicConfig)
return true
} | go | func (b *BucketNotification) AddTopic(topicConfig NotificationConfig) bool {
newTopicConfig := TopicConfig{NotificationConfig: topicConfig, Topic: topicConfig.Arn.String()}
for _, n := range b.TopicConfigs {
// If new config matches existing one
if n.Topic == newTopicConfig.Arn.String() && newTopicConfig.Filter == n.Filter {
existingConfig := set.NewStringSet()
for _, v := range n.Events {
existingConfig.Add(string(v))
}
newConfig := set.NewStringSet()
for _, v := range topicConfig.Events {
newConfig.Add(string(v))
}
if !newConfig.Intersection(existingConfig).IsEmpty() {
return false
}
}
}
b.TopicConfigs = append(b.TopicConfigs, newTopicConfig)
return true
} | [
"func",
"(",
"b",
"*",
"BucketNotification",
")",
"AddTopic",
"(",
"topicConfig",
"NotificationConfig",
")",
"bool",
"{",
"newTopicConfig",
":=",
"TopicConfig",
"{",
"NotificationConfig",
":",
"topicConfig",
",",
"Topic",
":",
"topicConfig",
".",
"Arn",
".",
"St... | // AddTopic adds a given topic config to the general bucket notification config | [
"AddTopic",
"adds",
"a",
"given",
"topic",
"config",
"to",
"the",
"general",
"bucket",
"notification",
"config"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L167-L190 | train |
minio/minio-go | bucket-notification.go | AddQueue | func (b *BucketNotification) AddQueue(queueConfig NotificationConfig) bool {
newQueueConfig := QueueConfig{NotificationConfig: queueConfig, Queue: queueConfig.Arn.String()}
for _, n := range b.QueueConfigs {
if n.Queue == newQueueConfig.Arn.String() && newQueueConfig.Filter == n.Filter {
existingConfig := set.NewStringSet()
for _, v := range n.Events {
existingConfig.Add(string(v))
}
newConfig := set.NewStringSet()
for _, v := range queueConfig.Events {
newConfig.Add(string(v))
}
if !newConfig.Intersection(existingConfig).IsEmpty() {
return false
}
}
}
b.QueueConfigs = append(b.QueueConfigs, newQueueConfig)
return true
} | go | func (b *BucketNotification) AddQueue(queueConfig NotificationConfig) bool {
newQueueConfig := QueueConfig{NotificationConfig: queueConfig, Queue: queueConfig.Arn.String()}
for _, n := range b.QueueConfigs {
if n.Queue == newQueueConfig.Arn.String() && newQueueConfig.Filter == n.Filter {
existingConfig := set.NewStringSet()
for _, v := range n.Events {
existingConfig.Add(string(v))
}
newConfig := set.NewStringSet()
for _, v := range queueConfig.Events {
newConfig.Add(string(v))
}
if !newConfig.Intersection(existingConfig).IsEmpty() {
return false
}
}
}
b.QueueConfigs = append(b.QueueConfigs, newQueueConfig)
return true
} | [
"func",
"(",
"b",
"*",
"BucketNotification",
")",
"AddQueue",
"(",
"queueConfig",
"NotificationConfig",
")",
"bool",
"{",
"newQueueConfig",
":=",
"QueueConfig",
"{",
"NotificationConfig",
":",
"queueConfig",
",",
"Queue",
":",
"queueConfig",
".",
"Arn",
".",
"St... | // AddQueue adds a given queue config to the general bucket notification config | [
"AddQueue",
"adds",
"a",
"given",
"queue",
"config",
"to",
"the",
"general",
"bucket",
"notification",
"config"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L193-L215 | train |
minio/minio-go | bucket-notification.go | AddLambda | func (b *BucketNotification) AddLambda(lambdaConfig NotificationConfig) bool {
newLambdaConfig := LambdaConfig{NotificationConfig: lambdaConfig, Lambda: lambdaConfig.Arn.String()}
for _, n := range b.LambdaConfigs {
if n.Lambda == newLambdaConfig.Arn.String() && newLambdaConfig.Filter == n.Filter {
existingConfig := set.NewStringSet()
for _, v := range n.Events {
existingConfig.Add(string(v))
}
newConfig := set.NewStringSet()
for _, v := range lambdaConfig.Events {
newConfig.Add(string(v))
}
if !newConfig.Intersection(existingConfig).IsEmpty() {
return false
}
}
}
b.LambdaConfigs = append(b.LambdaConfigs, newLambdaConfig)
return true
} | go | func (b *BucketNotification) AddLambda(lambdaConfig NotificationConfig) bool {
newLambdaConfig := LambdaConfig{NotificationConfig: lambdaConfig, Lambda: lambdaConfig.Arn.String()}
for _, n := range b.LambdaConfigs {
if n.Lambda == newLambdaConfig.Arn.String() && newLambdaConfig.Filter == n.Filter {
existingConfig := set.NewStringSet()
for _, v := range n.Events {
existingConfig.Add(string(v))
}
newConfig := set.NewStringSet()
for _, v := range lambdaConfig.Events {
newConfig.Add(string(v))
}
if !newConfig.Intersection(existingConfig).IsEmpty() {
return false
}
}
}
b.LambdaConfigs = append(b.LambdaConfigs, newLambdaConfig)
return true
} | [
"func",
"(",
"b",
"*",
"BucketNotification",
")",
"AddLambda",
"(",
"lambdaConfig",
"NotificationConfig",
")",
"bool",
"{",
"newLambdaConfig",
":=",
"LambdaConfig",
"{",
"NotificationConfig",
":",
"lambdaConfig",
",",
"Lambda",
":",
"lambdaConfig",
".",
"Arn",
"."... | // AddLambda adds a given lambda config to the general bucket notification config | [
"AddLambda",
"adds",
"a",
"given",
"lambda",
"config",
"to",
"the",
"general",
"bucket",
"notification",
"config"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L218-L240 | train |
minio/minio-go | bucket-notification.go | RemoveTopicByArn | func (b *BucketNotification) RemoveTopicByArn(arn Arn) {
var topics []TopicConfig
for _, topic := range b.TopicConfigs {
if topic.Topic != arn.String() {
topics = append(topics, topic)
}
}
b.TopicConfigs = topics
} | go | func (b *BucketNotification) RemoveTopicByArn(arn Arn) {
var topics []TopicConfig
for _, topic := range b.TopicConfigs {
if topic.Topic != arn.String() {
topics = append(topics, topic)
}
}
b.TopicConfigs = topics
} | [
"func",
"(",
"b",
"*",
"BucketNotification",
")",
"RemoveTopicByArn",
"(",
"arn",
"Arn",
")",
"{",
"var",
"topics",
"[",
"]",
"TopicConfig",
"\n",
"for",
"_",
",",
"topic",
":=",
"range",
"b",
".",
"TopicConfigs",
"{",
"if",
"topic",
".",
"Topic",
"!="... | // RemoveTopicByArn removes all topic configurations that match the exact specified ARN | [
"RemoveTopicByArn",
"removes",
"all",
"topic",
"configurations",
"that",
"match",
"the",
"exact",
"specified",
"ARN"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L243-L251 | train |
minio/minio-go | bucket-notification.go | RemoveQueueByArn | func (b *BucketNotification) RemoveQueueByArn(arn Arn) {
var queues []QueueConfig
for _, queue := range b.QueueConfigs {
if queue.Queue != arn.String() {
queues = append(queues, queue)
}
}
b.QueueConfigs = queues
} | go | func (b *BucketNotification) RemoveQueueByArn(arn Arn) {
var queues []QueueConfig
for _, queue := range b.QueueConfigs {
if queue.Queue != arn.String() {
queues = append(queues, queue)
}
}
b.QueueConfigs = queues
} | [
"func",
"(",
"b",
"*",
"BucketNotification",
")",
"RemoveQueueByArn",
"(",
"arn",
"Arn",
")",
"{",
"var",
"queues",
"[",
"]",
"QueueConfig",
"\n",
"for",
"_",
",",
"queue",
":=",
"range",
"b",
".",
"QueueConfigs",
"{",
"if",
"queue",
".",
"Queue",
"!="... | // RemoveQueueByArn removes all queue configurations that match the exact specified ARN | [
"RemoveQueueByArn",
"removes",
"all",
"queue",
"configurations",
"that",
"match",
"the",
"exact",
"specified",
"ARN"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L254-L262 | train |
minio/minio-go | bucket-notification.go | RemoveLambdaByArn | func (b *BucketNotification) RemoveLambdaByArn(arn Arn) {
var lambdas []LambdaConfig
for _, lambda := range b.LambdaConfigs {
if lambda.Lambda != arn.String() {
lambdas = append(lambdas, lambda)
}
}
b.LambdaConfigs = lambdas
} | go | func (b *BucketNotification) RemoveLambdaByArn(arn Arn) {
var lambdas []LambdaConfig
for _, lambda := range b.LambdaConfigs {
if lambda.Lambda != arn.String() {
lambdas = append(lambdas, lambda)
}
}
b.LambdaConfigs = lambdas
} | [
"func",
"(",
"b",
"*",
"BucketNotification",
")",
"RemoveLambdaByArn",
"(",
"arn",
"Arn",
")",
"{",
"var",
"lambdas",
"[",
"]",
"LambdaConfig",
"\n",
"for",
"_",
",",
"lambda",
":=",
"range",
"b",
".",
"LambdaConfigs",
"{",
"if",
"lambda",
".",
"Lambda",... | // RemoveLambdaByArn removes all lambda configurations that match the exact specified ARN | [
"RemoveLambdaByArn",
"removes",
"all",
"lambda",
"configurations",
"that",
"match",
"the",
"exact",
"specified",
"ARN"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L265-L273 | train |
minio/minio-go | retry.go | newRetryTimer | func (c Client) newRetryTimer(maxRetry int, unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
attemptCh := make(chan int)
// computes the exponential backoff duration according to
// https://www.awsarchitectureblog.com/2015/03/backoff.html
exponentialBackoffWait := func(attempt int) time.Duration {
// normalize jitter to the range [0, 1.0]
if jitter < NoJitter {
jitter = NoJitter
}
if jitter > MaxJitter {
jitter = MaxJitter
}
//sleep = random_between(0, min(cap, base * 2 ** attempt))
sleep := unit * time.Duration(1<<uint(attempt))
if sleep > cap {
sleep = cap
}
if jitter != NoJitter {
sleep -= time.Duration(c.random.Float64() * float64(sleep) * jitter)
}
return sleep
}
go func() {
defer close(attemptCh)
for i := 0; i < maxRetry; i++ {
select {
// Attempts start from 1.
case attemptCh <- i + 1:
case <-doneCh:
// Stop the routine.
return
}
time.Sleep(exponentialBackoffWait(i))
}
}()
return attemptCh
} | go | func (c Client) newRetryTimer(maxRetry int, unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
attemptCh := make(chan int)
// computes the exponential backoff duration according to
// https://www.awsarchitectureblog.com/2015/03/backoff.html
exponentialBackoffWait := func(attempt int) time.Duration {
// normalize jitter to the range [0, 1.0]
if jitter < NoJitter {
jitter = NoJitter
}
if jitter > MaxJitter {
jitter = MaxJitter
}
//sleep = random_between(0, min(cap, base * 2 ** attempt))
sleep := unit * time.Duration(1<<uint(attempt))
if sleep > cap {
sleep = cap
}
if jitter != NoJitter {
sleep -= time.Duration(c.random.Float64() * float64(sleep) * jitter)
}
return sleep
}
go func() {
defer close(attemptCh)
for i := 0; i < maxRetry; i++ {
select {
// Attempts start from 1.
case attemptCh <- i + 1:
case <-doneCh:
// Stop the routine.
return
}
time.Sleep(exponentialBackoffWait(i))
}
}()
return attemptCh
} | [
"func",
"(",
"c",
"Client",
")",
"newRetryTimer",
"(",
"maxRetry",
"int",
",",
"unit",
"time",
".",
"Duration",
",",
"cap",
"time",
".",
"Duration",
",",
"jitter",
"float64",
",",
"doneCh",
"chan",
"struct",
"{",
"}",
")",
"<-",
"chan",
"int",
"{",
"... | // newRetryTimer creates a timer with exponentially increasing
// delays until the maximum retry attempts are reached. | [
"newRetryTimer",
"creates",
"a",
"timer",
"with",
"exponentially",
"increasing",
"delays",
"until",
"the",
"maximum",
"retry",
"attempts",
"are",
"reached",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/retry.go#L47-L86 | train |
minio/minio-go | retry.go | isS3CodeRetryable | func isS3CodeRetryable(s3Code string) (ok bool) {
_, ok = retryableS3Codes[s3Code]
return ok
} | go | func isS3CodeRetryable(s3Code string) (ok bool) {
_, ok = retryableS3Codes[s3Code]
return ok
} | [
"func",
"isS3CodeRetryable",
"(",
"s3Code",
"string",
")",
"(",
"ok",
"bool",
")",
"{",
"_",
",",
"ok",
"=",
"retryableS3Codes",
"[",
"s3Code",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // isS3CodeRetryable - is s3 error code retryable. | [
"isS3CodeRetryable",
"-",
"is",
"s3",
"error",
"code",
"retryable",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/retry.go#L135-L138 | train |
minio/minio-go | retry.go | isHTTPStatusRetryable | func isHTTPStatusRetryable(httpStatusCode int) (ok bool) {
_, ok = retryableHTTPStatusCodes[httpStatusCode]
return ok
} | go | func isHTTPStatusRetryable(httpStatusCode int) (ok bool) {
_, ok = retryableHTTPStatusCodes[httpStatusCode]
return ok
} | [
"func",
"isHTTPStatusRetryable",
"(",
"httpStatusCode",
"int",
")",
"(",
"ok",
"bool",
")",
"{",
"_",
",",
"ok",
"=",
"retryableHTTPStatusCodes",
"[",
"httpStatusCode",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // isHTTPStatusRetryable - is HTTP error code retryable. | [
"isHTTPStatusRetryable",
"-",
"is",
"HTTP",
"error",
"code",
"retryable",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/retry.go#L150-L153 | train |
minio/minio-go | api-put-object-multipart.go | initiateMultipartUpload | func (c Client) initiateMultipartUpload(ctx context.Context, bucketName, objectName string, opts PutObjectOptions) (initiateMultipartUploadResult, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return initiateMultipartUploadResult{}, err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return initiateMultipartUploadResult{}, err
}
// Initialize url queries.
urlValues := make(url.Values)
urlValues.Set("uploads", "")
// Set ContentType header.
customHeader := opts.Header()
reqMetadata := requestMetadata{
bucketName: bucketName,
objectName: objectName,
queryValues: urlValues,
customHeader: customHeader,
}
// Execute POST on an objectName to initiate multipart upload.
resp, err := c.executeMethod(ctx, "POST", reqMetadata)
defer closeResponse(resp)
if err != nil {
return initiateMultipartUploadResult{}, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return initiateMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName)
}
}
// Decode xml for new multipart upload.
initiateMultipartUploadResult := initiateMultipartUploadResult{}
err = xmlDecoder(resp.Body, &initiateMultipartUploadResult)
if err != nil {
return initiateMultipartUploadResult, err
}
return initiateMultipartUploadResult, nil
} | go | func (c Client) initiateMultipartUpload(ctx context.Context, bucketName, objectName string, opts PutObjectOptions) (initiateMultipartUploadResult, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return initiateMultipartUploadResult{}, err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return initiateMultipartUploadResult{}, err
}
// Initialize url queries.
urlValues := make(url.Values)
urlValues.Set("uploads", "")
// Set ContentType header.
customHeader := opts.Header()
reqMetadata := requestMetadata{
bucketName: bucketName,
objectName: objectName,
queryValues: urlValues,
customHeader: customHeader,
}
// Execute POST on an objectName to initiate multipart upload.
resp, err := c.executeMethod(ctx, "POST", reqMetadata)
defer closeResponse(resp)
if err != nil {
return initiateMultipartUploadResult{}, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return initiateMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName)
}
}
// Decode xml for new multipart upload.
initiateMultipartUploadResult := initiateMultipartUploadResult{}
err = xmlDecoder(resp.Body, &initiateMultipartUploadResult)
if err != nil {
return initiateMultipartUploadResult, err
}
return initiateMultipartUploadResult, nil
} | [
"func",
"(",
"c",
"Client",
")",
"initiateMultipartUpload",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
",",
"objectName",
"string",
",",
"opts",
"PutObjectOptions",
")",
"(",
"initiateMultipartUploadResult",
",",
"error",
")",
"{",
"// Input validat... | // initiateMultipartUpload - Initiates a multipart upload and returns an upload ID. | [
"initiateMultipartUpload",
"-",
"Initiates",
"a",
"multipart",
"upload",
"and",
"returns",
"an",
"upload",
"ID",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-multipart.go#L187-L228 | train |
minio/minio-go | api-put-object-multipart.go | uploadPart | func (c Client) uploadPart(ctx context.Context, bucketName, objectName, uploadID string, reader io.Reader,
partNumber int, md5Base64, sha256Hex string, size int64, sse encrypt.ServerSide) (ObjectPart, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return ObjectPart{}, err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return ObjectPart{}, err
}
if size > maxPartSize {
return ObjectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName)
}
if size <= -1 {
return ObjectPart{}, ErrEntityTooSmall(size, bucketName, objectName)
}
if partNumber <= 0 {
return ObjectPart{}, ErrInvalidArgument("Part number cannot be negative or equal to zero.")
}
if uploadID == "" {
return ObjectPart{}, ErrInvalidArgument("UploadID cannot be empty.")
}
// Get resources properly escaped and lined up before using them in http request.
urlValues := make(url.Values)
// Set part number.
urlValues.Set("partNumber", strconv.Itoa(partNumber))
// Set upload id.
urlValues.Set("uploadId", uploadID)
// Set encryption headers, if any.
customHeader := make(http.Header)
// https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html
// Server-side encryption is supported by the S3 Multipart Upload actions.
// Unless you are using a customer-provided encryption key, you don't need
// to specify the encryption parameters in each UploadPart request.
if sse != nil && sse.Type() == encrypt.SSEC {
sse.Marshal(customHeader)
}
reqMetadata := requestMetadata{
bucketName: bucketName,
objectName: objectName,
queryValues: urlValues,
customHeader: customHeader,
contentBody: reader,
contentLength: size,
contentMD5Base64: md5Base64,
contentSHA256Hex: sha256Hex,
}
// Execute PUT on each part.
resp, err := c.executeMethod(ctx, "PUT", reqMetadata)
defer closeResponse(resp)
if err != nil {
return ObjectPart{}, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return ObjectPart{}, httpRespToErrorResponse(resp, bucketName, objectName)
}
}
// Once successfully uploaded, return completed part.
objPart := ObjectPart{}
objPart.Size = size
objPart.PartNumber = partNumber
// Trim off the odd double quotes from ETag in the beginning and end.
objPart.ETag = strings.TrimPrefix(resp.Header.Get("ETag"), "\"")
objPart.ETag = strings.TrimSuffix(objPart.ETag, "\"")
return objPart, nil
} | go | func (c Client) uploadPart(ctx context.Context, bucketName, objectName, uploadID string, reader io.Reader,
partNumber int, md5Base64, sha256Hex string, size int64, sse encrypt.ServerSide) (ObjectPart, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return ObjectPart{}, err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return ObjectPart{}, err
}
if size > maxPartSize {
return ObjectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName)
}
if size <= -1 {
return ObjectPart{}, ErrEntityTooSmall(size, bucketName, objectName)
}
if partNumber <= 0 {
return ObjectPart{}, ErrInvalidArgument("Part number cannot be negative or equal to zero.")
}
if uploadID == "" {
return ObjectPart{}, ErrInvalidArgument("UploadID cannot be empty.")
}
// Get resources properly escaped and lined up before using them in http request.
urlValues := make(url.Values)
// Set part number.
urlValues.Set("partNumber", strconv.Itoa(partNumber))
// Set upload id.
urlValues.Set("uploadId", uploadID)
// Set encryption headers, if any.
customHeader := make(http.Header)
// https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html
// Server-side encryption is supported by the S3 Multipart Upload actions.
// Unless you are using a customer-provided encryption key, you don't need
// to specify the encryption parameters in each UploadPart request.
if sse != nil && sse.Type() == encrypt.SSEC {
sse.Marshal(customHeader)
}
reqMetadata := requestMetadata{
bucketName: bucketName,
objectName: objectName,
queryValues: urlValues,
customHeader: customHeader,
contentBody: reader,
contentLength: size,
contentMD5Base64: md5Base64,
contentSHA256Hex: sha256Hex,
}
// Execute PUT on each part.
resp, err := c.executeMethod(ctx, "PUT", reqMetadata)
defer closeResponse(resp)
if err != nil {
return ObjectPart{}, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return ObjectPart{}, httpRespToErrorResponse(resp, bucketName, objectName)
}
}
// Once successfully uploaded, return completed part.
objPart := ObjectPart{}
objPart.Size = size
objPart.PartNumber = partNumber
// Trim off the odd double quotes from ETag in the beginning and end.
objPart.ETag = strings.TrimPrefix(resp.Header.Get("ETag"), "\"")
objPart.ETag = strings.TrimSuffix(objPart.ETag, "\"")
return objPart, nil
} | [
"func",
"(",
"c",
"Client",
")",
"uploadPart",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
",",
"objectName",
",",
"uploadID",
"string",
",",
"reader",
"io",
".",
"Reader",
",",
"partNumber",
"int",
",",
"md5Base64",
",",
"sha256Hex",
"string... | // uploadPart - Uploads a part in a multipart upload. | [
"uploadPart",
"-",
"Uploads",
"a",
"part",
"in",
"a",
"multipart",
"upload",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-multipart.go#L231-L300 | train |
minio/minio-go | api-put-object-multipart.go | completeMultipartUpload | func (c Client) completeMultipartUpload(ctx context.Context, bucketName, objectName, uploadID string,
complete completeMultipartUpload) (completeMultipartUploadResult, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return completeMultipartUploadResult{}, err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return completeMultipartUploadResult{}, err
}
// Initialize url queries.
urlValues := make(url.Values)
urlValues.Set("uploadId", uploadID)
// Marshal complete multipart body.
completeMultipartUploadBytes, err := xml.Marshal(complete)
if err != nil {
return completeMultipartUploadResult{}, err
}
// Instantiate all the complete multipart buffer.
completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes)
reqMetadata := requestMetadata{
bucketName: bucketName,
objectName: objectName,
queryValues: urlValues,
contentBody: completeMultipartUploadBuffer,
contentLength: int64(len(completeMultipartUploadBytes)),
contentSHA256Hex: sum256Hex(completeMultipartUploadBytes),
}
// Execute POST to complete multipart upload for an objectName.
resp, err := c.executeMethod(ctx, "POST", reqMetadata)
defer closeResponse(resp)
if err != nil {
return completeMultipartUploadResult{}, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return completeMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName)
}
}
// Read resp.Body into a []bytes to parse for Error response inside the body
var b []byte
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return completeMultipartUploadResult{}, err
}
// Decode completed multipart upload response on success.
completeMultipartUploadResult := completeMultipartUploadResult{}
err = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadResult)
if err != nil {
// xml parsing failure due to presence an ill-formed xml fragment
return completeMultipartUploadResult, err
} else if completeMultipartUploadResult.Bucket == "" {
// xml's Decode method ignores well-formed xml that don't apply to the type of value supplied.
// In this case, it would leave completeMultipartUploadResult with the corresponding zero-values
// of the members.
// Decode completed multipart upload response on failure
completeMultipartUploadErr := ErrorResponse{}
err = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadErr)
if err != nil {
// xml parsing failure due to presence an ill-formed xml fragment
return completeMultipartUploadResult, err
}
return completeMultipartUploadResult, completeMultipartUploadErr
}
return completeMultipartUploadResult, nil
} | go | func (c Client) completeMultipartUpload(ctx context.Context, bucketName, objectName, uploadID string,
complete completeMultipartUpload) (completeMultipartUploadResult, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return completeMultipartUploadResult{}, err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return completeMultipartUploadResult{}, err
}
// Initialize url queries.
urlValues := make(url.Values)
urlValues.Set("uploadId", uploadID)
// Marshal complete multipart body.
completeMultipartUploadBytes, err := xml.Marshal(complete)
if err != nil {
return completeMultipartUploadResult{}, err
}
// Instantiate all the complete multipart buffer.
completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes)
reqMetadata := requestMetadata{
bucketName: bucketName,
objectName: objectName,
queryValues: urlValues,
contentBody: completeMultipartUploadBuffer,
contentLength: int64(len(completeMultipartUploadBytes)),
contentSHA256Hex: sum256Hex(completeMultipartUploadBytes),
}
// Execute POST to complete multipart upload for an objectName.
resp, err := c.executeMethod(ctx, "POST", reqMetadata)
defer closeResponse(resp)
if err != nil {
return completeMultipartUploadResult{}, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return completeMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName)
}
}
// Read resp.Body into a []bytes to parse for Error response inside the body
var b []byte
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return completeMultipartUploadResult{}, err
}
// Decode completed multipart upload response on success.
completeMultipartUploadResult := completeMultipartUploadResult{}
err = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadResult)
if err != nil {
// xml parsing failure due to presence an ill-formed xml fragment
return completeMultipartUploadResult, err
} else if completeMultipartUploadResult.Bucket == "" {
// xml's Decode method ignores well-formed xml that don't apply to the type of value supplied.
// In this case, it would leave completeMultipartUploadResult with the corresponding zero-values
// of the members.
// Decode completed multipart upload response on failure
completeMultipartUploadErr := ErrorResponse{}
err = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadErr)
if err != nil {
// xml parsing failure due to presence an ill-formed xml fragment
return completeMultipartUploadResult, err
}
return completeMultipartUploadResult, completeMultipartUploadErr
}
return completeMultipartUploadResult, nil
} | [
"func",
"(",
"c",
"Client",
")",
"completeMultipartUpload",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
",",
"objectName",
",",
"uploadID",
"string",
",",
"complete",
"completeMultipartUpload",
")",
"(",
"completeMultipartUploadResult",
",",
"error",
... | // completeMultipartUpload - Completes a multipart upload by assembling previously uploaded parts. | [
"completeMultipartUpload",
"-",
"Completes",
"a",
"multipart",
"upload",
"by",
"assembling",
"previously",
"uploaded",
"parts",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-multipart.go#L303-L372 | train |
minio/minio-go | api-select.go | Header | func (o SelectObjectOptions) Header() http.Header {
headers := make(http.Header)
if o.ServerSideEncryption != nil && o.ServerSideEncryption.Type() == encrypt.SSEC {
o.ServerSideEncryption.Marshal(headers)
}
return headers
} | go | func (o SelectObjectOptions) Header() http.Header {
headers := make(http.Header)
if o.ServerSideEncryption != nil && o.ServerSideEncryption.Type() == encrypt.SSEC {
o.ServerSideEncryption.Marshal(headers)
}
return headers
} | [
"func",
"(",
"o",
"SelectObjectOptions",
")",
"Header",
"(",
")",
"http",
".",
"Header",
"{",
"headers",
":=",
"make",
"(",
"http",
".",
"Header",
")",
"\n",
"if",
"o",
".",
"ServerSideEncryption",
"!=",
"nil",
"&&",
"o",
".",
"ServerSideEncryption",
"."... | // Header returns the http.Header representation of the SelectObject options. | [
"Header",
"returns",
"the",
"http",
".",
"Header",
"representation",
"of",
"the",
"SelectObject",
"options",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L146-L152 | train |
minio/minio-go | api-select.go | Close | func (s *SelectResults) Close() error {
defer closeResponse(s.resp)
return s.pipeReader.Close()
} | go | func (s *SelectResults) Close() error {
defer closeResponse(s.resp)
return s.pipeReader.Close()
} | [
"func",
"(",
"s",
"*",
"SelectResults",
")",
"Close",
"(",
")",
"error",
"{",
"defer",
"closeResponse",
"(",
"s",
".",
"resp",
")",
"\n",
"return",
"s",
".",
"pipeReader",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close - closes the underlying response body and the stream reader. | [
"Close",
"-",
"closes",
"the",
"underlying",
"response",
"body",
"and",
"the",
"stream",
"reader",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L270-L273 | train |
minio/minio-go | api-select.go | Read | func (s *SelectResults) Read(b []byte) (n int, err error) {
return s.pipeReader.Read(b)
} | go | func (s *SelectResults) Read(b []byte) (n int, err error) {
return s.pipeReader.Read(b)
} | [
"func",
"(",
"s",
"*",
"SelectResults",
")",
"Read",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"return",
"s",
".",
"pipeReader",
".",
"Read",
"(",
"b",
")",
"\n",
"}"
] | // Read - is a reader compatible implementation for SelectObjectContent records. | [
"Read",
"-",
"is",
"a",
"reader",
"compatible",
"implementation",
"for",
"SelectObjectContent",
"records",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L276-L278 | train |
minio/minio-go | api-select.go | start | func (s *SelectResults) start(pipeWriter *io.PipeWriter) {
go func() {
for {
var prelude preludeInfo
var headers = make(http.Header)
var err error
// Create CRC code
crc := crc32.New(crc32.IEEETable)
crcReader := io.TeeReader(s.resp.Body, crc)
// Extract the prelude(12 bytes) into a struct to extract relevant information.
prelude, err = processPrelude(crcReader, crc)
if err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
// Extract the headers(variable bytes) into a struct to extract relevant information
if prelude.headerLen > 0 {
if err = extractHeader(io.LimitReader(crcReader, int64(prelude.headerLen)), headers); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
}
// Get the actual payload length so that the appropriate amount of
// bytes can be read or parsed.
payloadLen := prelude.PayloadLen()
m := messageType(headers.Get("message-type"))
switch m {
case errorMsg:
pipeWriter.CloseWithError(errors.New(headers.Get("error-code") + ":\"" + headers.Get("error-message") + "\""))
closeResponse(s.resp)
return
case commonMsg:
// Get content-type of the payload.
c := contentType(headers.Get("content-type"))
// Get event type of the payload.
e := eventType(headers.Get("event-type"))
// Handle all supported events.
switch e {
case endEvent:
pipeWriter.Close()
closeResponse(s.resp)
return
case recordsEvent:
if _, err = io.Copy(pipeWriter, io.LimitReader(crcReader, payloadLen)); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
case progressEvent:
switch c {
case xmlContent:
if err = xmlDecoder(io.LimitReader(crcReader, payloadLen), s.progress); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
default:
pipeWriter.CloseWithError(fmt.Errorf("Unexpected content-type %s sent for event-type %s", c, progressEvent))
closeResponse(s.resp)
return
}
case statsEvent:
switch c {
case xmlContent:
if err = xmlDecoder(io.LimitReader(crcReader, payloadLen), s.stats); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
default:
pipeWriter.CloseWithError(fmt.Errorf("Unexpected content-type %s sent for event-type %s", c, statsEvent))
closeResponse(s.resp)
return
}
}
}
// Ensures that the full message's CRC is correct and
// that the message is not corrupted
if err := checkCRC(s.resp.Body, crc.Sum32()); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
}
}()
} | go | func (s *SelectResults) start(pipeWriter *io.PipeWriter) {
go func() {
for {
var prelude preludeInfo
var headers = make(http.Header)
var err error
// Create CRC code
crc := crc32.New(crc32.IEEETable)
crcReader := io.TeeReader(s.resp.Body, crc)
// Extract the prelude(12 bytes) into a struct to extract relevant information.
prelude, err = processPrelude(crcReader, crc)
if err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
// Extract the headers(variable bytes) into a struct to extract relevant information
if prelude.headerLen > 0 {
if err = extractHeader(io.LimitReader(crcReader, int64(prelude.headerLen)), headers); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
}
// Get the actual payload length so that the appropriate amount of
// bytes can be read or parsed.
payloadLen := prelude.PayloadLen()
m := messageType(headers.Get("message-type"))
switch m {
case errorMsg:
pipeWriter.CloseWithError(errors.New(headers.Get("error-code") + ":\"" + headers.Get("error-message") + "\""))
closeResponse(s.resp)
return
case commonMsg:
// Get content-type of the payload.
c := contentType(headers.Get("content-type"))
// Get event type of the payload.
e := eventType(headers.Get("event-type"))
// Handle all supported events.
switch e {
case endEvent:
pipeWriter.Close()
closeResponse(s.resp)
return
case recordsEvent:
if _, err = io.Copy(pipeWriter, io.LimitReader(crcReader, payloadLen)); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
case progressEvent:
switch c {
case xmlContent:
if err = xmlDecoder(io.LimitReader(crcReader, payloadLen), s.progress); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
default:
pipeWriter.CloseWithError(fmt.Errorf("Unexpected content-type %s sent for event-type %s", c, progressEvent))
closeResponse(s.resp)
return
}
case statsEvent:
switch c {
case xmlContent:
if err = xmlDecoder(io.LimitReader(crcReader, payloadLen), s.stats); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
default:
pipeWriter.CloseWithError(fmt.Errorf("Unexpected content-type %s sent for event-type %s", c, statsEvent))
closeResponse(s.resp)
return
}
}
}
// Ensures that the full message's CRC is correct and
// that the message is not corrupted
if err := checkCRC(s.resp.Body, crc.Sum32()); err != nil {
pipeWriter.CloseWithError(err)
closeResponse(s.resp)
return
}
}
}()
} | [
"func",
"(",
"s",
"*",
"SelectResults",
")",
"start",
"(",
"pipeWriter",
"*",
"io",
".",
"PipeWriter",
")",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"var",
"prelude",
"preludeInfo",
"\n",
"var",
"headers",
"=",
"make",
"(",
"http",
".",
"Header"... | // start is the main function that decodes the large byte array into
// several events that are sent through the eventstream. | [
"start",
"is",
"the",
"main",
"function",
"that",
"decodes",
"the",
"large",
"byte",
"array",
"into",
"several",
"events",
"that",
"are",
"sent",
"through",
"the",
"eventstream",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L292-L389 | train |
minio/minio-go | api-select.go | processPrelude | func processPrelude(prelude io.Reader, crc hash.Hash32) (preludeInfo, error) {
var err error
var pInfo = preludeInfo{}
// reads total length of the message (first 4 bytes)
pInfo.totalLen, err = extractUint32(prelude)
if err != nil {
return pInfo, err
}
// reads total header length of the message (2nd 4 bytes)
pInfo.headerLen, err = extractUint32(prelude)
if err != nil {
return pInfo, err
}
// checks that the CRC is correct (3rd 4 bytes)
preCRC := crc.Sum32()
if err := checkCRC(prelude, preCRC); err != nil {
return pInfo, err
}
return pInfo, nil
} | go | func processPrelude(prelude io.Reader, crc hash.Hash32) (preludeInfo, error) {
var err error
var pInfo = preludeInfo{}
// reads total length of the message (first 4 bytes)
pInfo.totalLen, err = extractUint32(prelude)
if err != nil {
return pInfo, err
}
// reads total header length of the message (2nd 4 bytes)
pInfo.headerLen, err = extractUint32(prelude)
if err != nil {
return pInfo, err
}
// checks that the CRC is correct (3rd 4 bytes)
preCRC := crc.Sum32()
if err := checkCRC(prelude, preCRC); err != nil {
return pInfo, err
}
return pInfo, nil
} | [
"func",
"processPrelude",
"(",
"prelude",
"io",
".",
"Reader",
",",
"crc",
"hash",
".",
"Hash32",
")",
"(",
"preludeInfo",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"pInfo",
"=",
"preludeInfo",
"{",
"}",
"\n\n",
"// reads total length of ... | // processPrelude is the function that reads the 12 bytes of the prelude and
// ensures the CRC is correct while also extracting relevant information into
// the struct, | [
"processPrelude",
"is",
"the",
"function",
"that",
"reads",
"the",
"12",
"bytes",
"of",
"the",
"prelude",
"and",
"ensures",
"the",
"CRC",
"is",
"correct",
"while",
"also",
"extracting",
"relevant",
"information",
"into",
"the",
"struct"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L399-L422 | train |
minio/minio-go | api-select.go | extractHeader | func extractHeader(body io.Reader, myHeaders http.Header) error {
for {
// extracts the first part of the header,
headerTypeName, err := extractHeaderType(body)
if err != nil {
// Since end of file, we have read all of our headers
if err == io.EOF {
break
}
return err
}
// reads the 7 present in the header and ignores it.
extractUint8(body)
headerValueName, err := extractHeaderValue(body)
if err != nil {
return err
}
myHeaders.Set(headerTypeName, headerValueName)
}
return nil
} | go | func extractHeader(body io.Reader, myHeaders http.Header) error {
for {
// extracts the first part of the header,
headerTypeName, err := extractHeaderType(body)
if err != nil {
// Since end of file, we have read all of our headers
if err == io.EOF {
break
}
return err
}
// reads the 7 present in the header and ignores it.
extractUint8(body)
headerValueName, err := extractHeaderValue(body)
if err != nil {
return err
}
myHeaders.Set(headerTypeName, headerValueName)
}
return nil
} | [
"func",
"extractHeader",
"(",
"body",
"io",
".",
"Reader",
",",
"myHeaders",
"http",
".",
"Header",
")",
"error",
"{",
"for",
"{",
"// extracts the first part of the header,",
"headerTypeName",
",",
"err",
":=",
"extractHeaderType",
"(",
"body",
")",
"\n",
"if",... | // extracts the relevant information from the Headers. | [
"extracts",
"the",
"relevant",
"information",
"from",
"the",
"Headers",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L425-L449 | train |
minio/minio-go | api-select.go | extractHeaderType | func extractHeaderType(body io.Reader) (string, error) {
// extracts 2 bit integer
headerNameLen, err := extractUint8(body)
if err != nil {
return "", err
}
// extracts the string with the appropriate number of bytes
headerName, err := extractString(body, int(headerNameLen))
if err != nil {
return "", err
}
return strings.TrimPrefix(headerName, ":"), nil
} | go | func extractHeaderType(body io.Reader) (string, error) {
// extracts 2 bit integer
headerNameLen, err := extractUint8(body)
if err != nil {
return "", err
}
// extracts the string with the appropriate number of bytes
headerName, err := extractString(body, int(headerNameLen))
if err != nil {
return "", err
}
return strings.TrimPrefix(headerName, ":"), nil
} | [
"func",
"extractHeaderType",
"(",
"body",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"error",
")",
"{",
"// extracts 2 bit integer",
"headerNameLen",
",",
"err",
":=",
"extractUint8",
"(",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\""... | // extractHeaderType extracts the first half of the header message, the header type. | [
"extractHeaderType",
"extracts",
"the",
"first",
"half",
"of",
"the",
"header",
"message",
"the",
"header",
"type",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L452-L464 | train |
minio/minio-go | api-select.go | extractHeaderValue | func extractHeaderValue(body io.Reader) (string, error) {
bodyLen, err := extractUint16(body)
if err != nil {
return "", err
}
bodyName, err := extractString(body, int(bodyLen))
if err != nil {
return "", err
}
return bodyName, nil
} | go | func extractHeaderValue(body io.Reader) (string, error) {
bodyLen, err := extractUint16(body)
if err != nil {
return "", err
}
bodyName, err := extractString(body, int(bodyLen))
if err != nil {
return "", err
}
return bodyName, nil
} | [
"func",
"extractHeaderValue",
"(",
"body",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"error",
")",
"{",
"bodyLen",
",",
"err",
":=",
"extractUint16",
"(",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
... | // extractsHeaderValue extracts the second half of the header message, the
// header value | [
"extractsHeaderValue",
"extracts",
"the",
"second",
"half",
"of",
"the",
"header",
"message",
"the",
"header",
"value"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L468-L478 | train |
minio/minio-go | api-select.go | extractString | func extractString(source io.Reader, lenBytes int) (string, error) {
myVal := make([]byte, lenBytes)
_, err := source.Read(myVal)
if err != nil {
return "", err
}
return string(myVal), nil
} | go | func extractString(source io.Reader, lenBytes int) (string, error) {
myVal := make([]byte, lenBytes)
_, err := source.Read(myVal)
if err != nil {
return "", err
}
return string(myVal), nil
} | [
"func",
"extractString",
"(",
"source",
"io",
".",
"Reader",
",",
"lenBytes",
"int",
")",
"(",
"string",
",",
"error",
")",
"{",
"myVal",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"lenBytes",
")",
"\n",
"_",
",",
"err",
":=",
"source",
".",
"Read",... | // extracts a string from byte array of a particular number of bytes. | [
"extracts",
"a",
"string",
"from",
"byte",
"array",
"of",
"a",
"particular",
"number",
"of",
"bytes",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L481-L488 | train |
minio/minio-go | api-select.go | extractUint32 | func extractUint32(r io.Reader) (uint32, error) {
buf := make([]byte, 4)
_, err := io.ReadFull(r, buf)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint32(buf), nil
} | go | func extractUint32(r io.Reader) (uint32, error) {
buf := make([]byte, 4)
_, err := io.ReadFull(r, buf)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint32(buf), nil
} | [
"func",
"extractUint32",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"buf",
")",
"\n"... | // extractUint32 extracts a 4 byte integer from the byte array. | [
"extractUint32",
"extracts",
"a",
"4",
"byte",
"integer",
"from",
"the",
"byte",
"array",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L491-L498 | train |
minio/minio-go | api-select.go | extractUint16 | func extractUint16(r io.Reader) (uint16, error) {
buf := make([]byte, 2)
_, err := io.ReadFull(r, buf)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint16(buf), nil
} | go | func extractUint16(r io.Reader) (uint16, error) {
buf := make([]byte, 2)
_, err := io.ReadFull(r, buf)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint16(buf), nil
} | [
"func",
"extractUint16",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"2",
")",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"buf",
")",
"\n"... | // extractUint16 extracts a 2 byte integer from the byte array. | [
"extractUint16",
"extracts",
"a",
"2",
"byte",
"integer",
"from",
"the",
"byte",
"array",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L501-L508 | train |
minio/minio-go | api-select.go | extractUint8 | func extractUint8(r io.Reader) (uint8, error) {
buf := make([]byte, 1)
_, err := io.ReadFull(r, buf)
if err != nil {
return 0, err
}
return buf[0], nil
} | go | func extractUint8(r io.Reader) (uint8, error) {
buf := make([]byte, 1)
_, err := io.ReadFull(r, buf)
if err != nil {
return 0, err
}
return buf[0], nil
} | [
"func",
"extractUint8",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"uint8",
",",
"error",
")",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"1",
")",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"buf",
")",
"\n",
... | // extractUint8 extracts a 1 byte integer from the byte array. | [
"extractUint8",
"extracts",
"a",
"1",
"byte",
"integer",
"from",
"the",
"byte",
"array",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L511-L518 | train |
minio/minio-go | api-select.go | checkCRC | func checkCRC(r io.Reader, expect uint32) error {
msgCRC, err := extractUint32(r)
if err != nil {
return err
}
if msgCRC != expect {
return fmt.Errorf("Checksum Mismatch, MessageCRC of 0x%X does not equal expected CRC of 0x%X", msgCRC, expect)
}
return nil
} | go | func checkCRC(r io.Reader, expect uint32) error {
msgCRC, err := extractUint32(r)
if err != nil {
return err
}
if msgCRC != expect {
return fmt.Errorf("Checksum Mismatch, MessageCRC of 0x%X does not equal expected CRC of 0x%X", msgCRC, expect)
}
return nil
} | [
"func",
"checkCRC",
"(",
"r",
"io",
".",
"Reader",
",",
"expect",
"uint32",
")",
"error",
"{",
"msgCRC",
",",
"err",
":=",
"extractUint32",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"msgCRC",
"!="... | // checkCRC ensures that the CRC matches with the one from the reader. | [
"checkCRC",
"ensures",
"that",
"the",
"CRC",
"matches",
"with",
"the",
"one",
"from",
"the",
"reader",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L521-L532 | train |
minio/minio-go | api-stat.go | BucketExists | func (c Client) BucketExists(bucketName string) (bool, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return false, err
}
// Execute HEAD on bucketName.
resp, err := c.executeMethod(context.Background(), "HEAD", requestMetadata{
bucketName: bucketName,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
if ToErrorResponse(err).Code == "NoSuchBucket" {
return false, nil
}
return false, err
}
if resp != nil {
resperr := httpRespToErrorResponse(resp, bucketName, "")
if ToErrorResponse(resperr).Code == "NoSuchBucket" {
return false, nil
}
if resp.StatusCode != http.StatusOK {
return false, httpRespToErrorResponse(resp, bucketName, "")
}
}
return true, nil
} | go | func (c Client) BucketExists(bucketName string) (bool, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return false, err
}
// Execute HEAD on bucketName.
resp, err := c.executeMethod(context.Background(), "HEAD", requestMetadata{
bucketName: bucketName,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
if ToErrorResponse(err).Code == "NoSuchBucket" {
return false, nil
}
return false, err
}
if resp != nil {
resperr := httpRespToErrorResponse(resp, bucketName, "")
if ToErrorResponse(resperr).Code == "NoSuchBucket" {
return false, nil
}
if resp.StatusCode != http.StatusOK {
return false, httpRespToErrorResponse(resp, bucketName, "")
}
}
return true, nil
} | [
"func",
"(",
"c",
"Client",
")",
"BucketExists",
"(",
"bucketName",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"// Input validation.",
"if",
"err",
":=",
"s3utils",
".",
"CheckValidBucketName",
"(",
"bucketName",
")",
";",
"err",
"!=",
"nil",
"{",... | // BucketExists verify if bucket exists and you have permission to access it. | [
"BucketExists",
"verify",
"if",
"bucket",
"exists",
"and",
"you",
"have",
"permission",
"to",
"access",
"it",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-stat.go#L31-L59 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.