code
stringlengths
22
3.95M
docstring
stringlengths
20
17.8k
func_name
stringlengths
1
472
language
stringclasses
1 value
repo
stringlengths
6
57
path
stringlengths
4
226
url
stringlengths
43
277
license
stringclasses
7 values
func HasExtension(key string, value interface{}) EventMatcher { return HasExtensions(map[string]interface{}{key: value}) }
HasExtension checks if the event contains the provided extension
HasExtension
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasData(want []byte) EventMatcher { return func(have event.Event) error { if diff := cmp.Diff(string(want), string(have.Data())); diff != "" { return fmt.Errorf("data not matching (-want, +got) = %v", diff) } return nil } }
HasData checks if the event contains the provided data
HasData
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func DataContains(expectedContainedString string) EventMatcher { return func(have event.Event) error { dataAsString := string(have.Data()) if !strings.Contains(dataAsString, expectedContainedString) { return fmt.Errorf("data '%s' doesn't contain '%s'", dataAsString, expectedContainedString) } return nil } }
DataContains matches that the data field of the event, converted to a string, contains the provided string
DataContains
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasNoData() EventMatcher { return func(have event.Event) error { if have.Data() != nil { return fmt.Errorf("expecting nil data, got = '%v'", string(have.Data())) } return nil } }
HasNoData checks if the event doesn't contain data
HasNoData
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsEqualTo(want event.Event) EventMatcher { return AllOf(IsContextEqualTo(want.Context), IsDataEqualTo(want)) }
IsEqualTo performs a semantic equality check of the event (like AssertEventEquals)
IsEqualTo
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsContextEqualTo(want event.EventContext) EventMatcher { return AllOf(HasExactlyAttributesEqualTo(want), HasExactlyExtensions(want.GetExtensions())) }
IsContextEqualTo performs a semantic equality check of the event context, including extension attributes (like AssertEventContextEquals)
IsContextEqualTo
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsDataEqualTo(want event.Event) EventMatcher { if want.Data() == nil { return HasNoData() } else { return HasData(want.Data()) } }
IsDataEqualTo checks if the data field matches with want
IsDataEqualTo
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsValid() EventMatcher { return func(have event.Event) error { if err := have.Validate(); err != nil { return fmt.Errorf("expecting valid event: %s", err.Error()) } return nil } }
IsValid checks if the event is valid
IsValid
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsInvalid() EventMatcher { return func(have event.Event) error { if err := have.Validate(); err == nil { return fmt.Errorf("expecting invalid event") } return nil } }
IsInvalid checks if the event is invalid
IsInvalid
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func FullEvent() event.Event { e := event.Event{ Context: event.EventContextV1{ Type: "com.example.FullEvent", Source: Source, ID: "full-event", Time: &Timestamp, DataSchema: &Schema, Subject: strptr("topic"), }.AsV1(), } e.SetExtension("exbool", true) e.SetExtension("exint", 42) e.SetExtension("exstring", "exstring") e.SetExtension("exbinary", []byte{0, 1, 2, 3}) e.SetExtension("exurl", Source) e.SetExtension("extime", Timestamp) if err := e.SetData("text/json", "hello"); err != nil { panic(err) } return e }
FullEvent has all context attributes set and JSON string data.
FullEvent
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func MinEvent() event.Event { return event.Event{ Context: event.EventContextV1{ Type: "com.example.MinEvent", Source: Source, ID: "min-event", }.AsV1(), } }
MinEvent has only required attributes set.
MinEvent
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func FullMessage() binding.Message { ev := FullEvent() return binding.ToMessage(&ev) }
FullMessage returns the same event of FullEvent but wrapped as Message.
FullMessage
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func MinMessage() binding.Message { ev := MinEvent() return binding.ToMessage(&ev) }
MinMessage returns the same event of MinEvent but wrapped as Message.
MinMessage
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func AllVersions(events []event.Event) []event.Event { versions := spec.New() all := versions.Versions() result := make([]event.Event, len(events)*len(all)) i := 0 for _, e := range events { for _, v := range all { result[i] = e result[i].Context = v.Convert(e.Context) result[i].SetID(fmt.Sprintf("%v-%v", e.ID(), i)) // Unique IDs i++ } } return result }
AllVersions returns all versions of each event in events. ID gets a -number suffix so IDs are unique.
AllVersions
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func Events() []event.Event { return AllVersions([]event.Event{FullEvent(), MinEvent()}) }
Events is a set of test events that should be handled correctly by all event-processing code.
Events
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func WithoutExtensions(events []event.Event) []event.Event { result := make([]event.Event, len(events)) for i, e := range events { result[i] = e result[i].Context = e.Context.Clone() ctx := reflect.ValueOf(result[i].Context).Elem() ext := ctx.FieldByName("Extensions") ext.Set(reflect.Zero(ext.Type())) } return result }
WithoutExtensions returns a copy of events with no Extensions. Use for testing where extensions are not supported.
WithoutExtensions
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func MustJSON(t testing.TB, e event.Event) []byte { b, err := format.JSON.Marshal(&e) require.NoError(t, err) return b }
MustJSON marshals the event.Event to JSON structured representation or panics
MustJSON
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func MustToEvent(t testing.TB, ctx context.Context, m binding.Message) event.Event { e, err := binding.ToEvent(ctx, m) require.NoError(t, err) return *e }
MustToEvent converts a Message to event.Event
MustToEvent
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func ConvertEventExtensionsToString(t testing.TB, e event.Event) event.Event { out := e.Clone() for k, v := range e.Extensions() { var vParsed interface{} var err error switch v := v.(type) { case json.RawMessage: err = json.Unmarshal(v, &vParsed) require.NoError(t, err) default: vParsed, err = types.Format(v) require.NoError(t, err) } out.SetExtension(k, vParsed) } return out }
ConvertEventExtensionsToString returns a copy of the event.Event where all extensions are converted to strings. Fails the test if conversion fails
ConvertEventExtensionsToString
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func TestNameOf(x interface{}) string { switch x := x.(type) { case event.Event: b, err := json.Marshal(x) if err == nil { return fmt.Sprintf("Event%s", b) } case binding.Message: return fmt.Sprintf("Message{%s}", reflect.TypeOf(x).String()) } return fmt.Sprintf("%T(%#v)", x, x) }
TestNameOf generates a string test name from x, esp. for ce.Event and ce.Message.
TestNameOf
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func EachEvent(t *testing.T, events []event.Event, f func(*testing.T, event.Event)) { for _, e := range events { in := e t.Run(TestNameOf(in), func(t *testing.T) { f(t, in) }) } }
EachEvent runs f as a test for each event in events
EachEvent
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func EachMessage(t *testing.T, messages []binding.Message, f func(*testing.T, binding.Message)) { for _, m := range messages { in := m t.Run(TestNameOf(in), func(t *testing.T) { f(t, in) }) } }
EachMessage runs f as a test for each message in messages
EachMessage
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func Allocate(obj interface{}) (asPtr interface{}, asValue reflect.Value) { if obj == nil { return nil, reflect.Value{} } switch t := reflect.TypeOf(obj); t.Kind() { case reflect.Ptr: reflectPtr := reflect.New(t.Elem()) asPtr = reflectPtr.Interface() asValue = reflectPtr case reflect.Map: reflectPtr := reflect.MakeMap(t) asPtr = reflectPtr.Interface() asValue = reflectPtr case reflect.String: reflectPtr := reflect.New(t) asPtr = "" asValue = reflectPtr.Elem() case reflect.Slice: reflectPtr := reflect.MakeSlice(t, 0, 0) asPtr = reflectPtr.Interface() asValue = reflectPtr default: reflectPtr := reflect.New(t) asPtr = reflectPtr.Interface() asValue = reflectPtr.Elem() } return }
Allocate allocates a new instance of type t and returns: asPtr is of type t if t is a pointer type and of type &t otherwise asValue is a Value of type t pointing to the same data as asPtr
Allocate
go
cloudevents/sdk-go
v2/types/allocate.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/allocate.go
Apache-2.0
func ParseTimestamp(s string) (*Timestamp, error) { if s == "" { return nil, nil } tt, err := ParseTime(s) return &Timestamp{Time: tt}, err }
ParseTimestamp attempts to parse the given time assuming RFC3339 layout
ParseTimestamp
go
cloudevents/sdk-go
v2/types/timestamp.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/timestamp.go
Apache-2.0
func (t *Timestamp) MarshalJSON() ([]byte, error) { if t == nil || t.IsZero() { return []byte(`""`), nil } return []byte(fmt.Sprintf("%q", t)), nil }
MarshalJSON implements a custom json marshal method used when this type is marshaled using json.Marshal.
MarshalJSON
go
cloudevents/sdk-go
v2/types/timestamp.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/timestamp.go
Apache-2.0
func (t *Timestamp) UnmarshalJSON(b []byte) error { var timestamp string if err := json.Unmarshal(b, &timestamp); err != nil { return err } var err error t.Time, err = ParseTime(timestamp) return err }
UnmarshalJSON implements the json unmarshal method used when this type is unmarshaled using json.Unmarshal.
UnmarshalJSON
go
cloudevents/sdk-go
v2/types/timestamp.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/timestamp.go
Apache-2.0
func (t *Timestamp) MarshalXML(e *xml.Encoder, start xml.StartElement) error { if t == nil || t.IsZero() { return e.EncodeElement(nil, start) } return e.EncodeElement(t.String(), start) }
MarshalXML implements a custom xml marshal method used when this type is marshaled using xml.Marshal.
MarshalXML
go
cloudevents/sdk-go
v2/types/timestamp.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/timestamp.go
Apache-2.0
func (t *Timestamp) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { var timestamp string if err := d.DecodeElement(&timestamp, &start); err != nil { return err } var err error t.Time, err = ParseTime(timestamp) return err }
UnmarshalXML implements the xml unmarshal method used when this type is unmarshaled using xml.Unmarshal.
UnmarshalXML
go
cloudevents/sdk-go
v2/types/timestamp.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/timestamp.go
Apache-2.0
func ParseURI(u string) *URI { if u == "" { return nil } pu, err := url.Parse(u) if err != nil { return nil } return &URI{URL: *pu} }
ParseURI attempts to parse the given string as a URI.
ParseURI
go
cloudevents/sdk-go
v2/types/uri.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uri.go
Apache-2.0
func (u URI) MarshalJSON() ([]byte, error) { b := fmt.Sprintf("%q", u.String()) return []byte(b), nil }
MarshalJSON implements a custom json marshal method used when this type is marshaled using json.Marshal.
MarshalJSON
go
cloudevents/sdk-go
v2/types/uri.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uri.go
Apache-2.0
func (u *URI) UnmarshalJSON(b []byte) error { var ref string if err := json.Unmarshal(b, &ref); err != nil { return err } r := ParseURI(ref) if r != nil { *u = *r } return nil }
UnmarshalJSON implements the json unmarshal method used when this type is unmarshaled using json.Unmarshal.
UnmarshalJSON
go
cloudevents/sdk-go
v2/types/uri.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uri.go
Apache-2.0
func (u URI) MarshalXML(e *xml.Encoder, start xml.StartElement) error { return e.EncodeElement(u.String(), start) }
MarshalXML implements a custom xml marshal method used when this type is marshaled using xml.Marshal.
MarshalXML
go
cloudevents/sdk-go
v2/types/uri.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uri.go
Apache-2.0
func (u *URI) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { var ref string if err := d.DecodeElement(&ref, &start); err != nil { return err } r := ParseURI(ref) if r != nil { *u = *r } return nil }
UnmarshalXML implements the xml unmarshal method used when this type is unmarshaled using xml.Unmarshal.
UnmarshalXML
go
cloudevents/sdk-go
v2/types/uri.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uri.go
Apache-2.0
func (u *URI) String() string { if u == nil { return "" } return u.URL.String() }
String returns the full string representation of the URI-Reference.
String
go
cloudevents/sdk-go
v2/types/uri.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uri.go
Apache-2.0
func ParseURIRef(u string) *URIRef { if u == "" { return nil } pu, err := url.Parse(u) if err != nil { return nil } return &URIRef{URL: *pu} }
ParseURIRef attempts to parse the given string as a URI-Reference.
ParseURIRef
go
cloudevents/sdk-go
v2/types/uriref.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uriref.go
Apache-2.0
func (u URIRef) MarshalJSON() ([]byte, error) { b := fmt.Sprintf("%q", u.String()) return []byte(b), nil }
MarshalJSON implements a custom json marshal method used when this type is marshaled using json.Marshal.
MarshalJSON
go
cloudevents/sdk-go
v2/types/uriref.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uriref.go
Apache-2.0
func (u *URIRef) UnmarshalJSON(b []byte) error { var ref string if err := json.Unmarshal(b, &ref); err != nil { return err } r := ParseURIRef(ref) if r != nil { *u = *r } return nil }
UnmarshalJSON implements the json unmarshal method used when this type is unmarshaled using json.Unmarshal.
UnmarshalJSON
go
cloudevents/sdk-go
v2/types/uriref.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uriref.go
Apache-2.0
func (u URIRef) MarshalXML(e *xml.Encoder, start xml.StartElement) error { return e.EncodeElement(u.String(), start) }
MarshalXML implements a custom xml marshal method used when this type is marshaled using xml.Marshal.
MarshalXML
go
cloudevents/sdk-go
v2/types/uriref.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uriref.go
Apache-2.0
func (u *URIRef) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { var ref string if err := d.DecodeElement(&ref, &start); err != nil { return err } r := ParseURIRef(ref) if r != nil { *u = *r } return nil }
UnmarshalXML implements the xml unmarshal method used when this type is unmarshaled using xml.Unmarshal.
UnmarshalXML
go
cloudevents/sdk-go
v2/types/uriref.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uriref.go
Apache-2.0
func (u *URIRef) String() string { if u == nil { return "" } return u.URL.String() }
String returns the full string representation of the URI-Reference.
String
go
cloudevents/sdk-go
v2/types/uriref.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uriref.go
Apache-2.0
func ParseInteger(v string) (int32, error) { // Accept floating-point but truncate to int32 as per CE spec. f, err := strconv.ParseFloat(v, 64) if err != nil { return 0, err } if f > math.MaxInt32 || f < math.MinInt32 { return 0, rangeErr(v) } return int32(f), nil }
ParseInteger parse canonical string format: decimal notation.
ParseInteger
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ParseTime(v string) (time.Time, error) { t, err := time.Parse(time.RFC3339Nano, v) if err != nil { err := convertErr(time.Time{}, v) err.extra = ": not in RFC3339 format" return time.Time{}, err } return t, nil }
ParseTime parse canonical string format: RFC3339 with nanoseconds
ParseTime
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func Format(v interface{}) (string, error) { v, err := Validate(v) if err != nil { return "", err } switch v := v.(type) { case bool: return FormatBool(v), nil case int32: return FormatInteger(v), nil case string: return v, nil case []byte: return FormatBinary(v), nil case URI: return v.String(), nil case URIRef: // url.URL is often passed by pointer so allow both return v.String(), nil case Timestamp: return FormatTime(v.Time), nil default: return "", fmt.Errorf("%T is not a CloudEvents type", v) } }
Format returns the canonical string format of v, where v can be any type that is convertible to a CloudEvents type.
Format
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func Validate(v interface{}) (interface{}, error) { switch v := v.(type) { case bool, int32, string, []byte: return v, nil // Already a CloudEvents type, no validation needed. case uint, uintptr, uint8, uint16, uint32, uint64: u := reflect.ValueOf(v).Uint() if u > math.MaxInt32 { return nil, rangeErr(v) } return int32(u), nil case int, int8, int16, int64: i := reflect.ValueOf(v).Int() if i > math.MaxInt32 || i < math.MinInt32 { return nil, rangeErr(v) } return int32(i), nil case float32, float64: f := reflect.ValueOf(v).Float() if f > math.MaxInt32 || f < math.MinInt32 { return nil, rangeErr(v) } return int32(f), nil case *url.URL: if v == nil { break } return URI{URL: *v}, nil case url.URL: return URI{URL: v}, nil case *URIRef: if v != nil { return *v, nil } return nil, nil case URIRef: return v, nil case *URI: if v != nil { return *v, nil } return nil, nil case URI: return v, nil case time.Time: return Timestamp{Time: v}, nil case *time.Time: if v == nil { break } return Timestamp{Time: *v}, nil case Timestamp: return v, nil } rx := reflect.ValueOf(v) if rx.Kind() == reflect.Ptr && !rx.IsNil() { // Allow pointers-to convertible types return Validate(rx.Elem().Interface()) } return nil, fmt.Errorf("invalid CloudEvents value: %#v", v) }
Validate v is a valid CloudEvents attribute value, convert it to one of: bool, int32, string, []byte, types.URI, types.URIRef, types.Timestamp
Validate
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func Clone(v interface{}) interface{} { if v == nil { return nil } switch v := v.(type) { case bool, int32, string, nil: return v // Already a CloudEvents type, no validation needed. case []byte: clone := make([]byte, len(v)) copy(clone, v) return v case url.URL: return URI{v} case *url.URL: return &URI{*v} case URIRef: return v case *URIRef: return &URIRef{v.URL} case URI: return v case *URI: return &URI{v.URL} case time.Time: return Timestamp{v} case *time.Time: return &Timestamp{*v} case Timestamp: return v case *Timestamp: return &Timestamp{v.Time} } panic(fmt.Errorf("invalid CloudEvents value: %#v", v)) }
Clone v clones a CloudEvents attribute value, which is one of the valid types: bool, int32, string, []byte, types.URI, types.URIRef, types.Timestamp Returns the same type Panics if the type is not valid
Clone
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToBool(v interface{}) (bool, error) { v, err := Validate(v) if err != nil { return false, err } switch v := v.(type) { case bool: return v, nil case string: return ParseBool(v) default: return false, convertErr(true, v) } }
ToBool accepts a bool value or canonical "true"/"false" string.
ToBool
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToInteger(v interface{}) (int32, error) { v, err := Validate(v) if err != nil { return 0, err } switch v := v.(type) { case int32: return v, nil case string: return ParseInteger(v) default: return 0, convertErr(int32(0), v) } }
ToInteger accepts any numeric value in int32 range, or canonical string.
ToInteger
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToString(v interface{}) (string, error) { v, err := Validate(v) if err != nil { return "", err } switch v := v.(type) { case string: return v, nil default: return "", convertErr("", v) } }
ToString returns a string value unaltered. This function does not perform canonical string encoding, use one of the Format functions for that.
ToString
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToBinary(v interface{}) ([]byte, error) { v, err := Validate(v) if err != nil { return nil, err } switch v := v.(type) { case []byte: return v, nil case string: return base64.StdEncoding.DecodeString(v) default: return nil, convertErr([]byte(nil), v) } }
ToBinary returns a []byte value, decoding from base64 string if necessary.
ToBinary
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToURL(v interface{}) (*url.URL, error) { v, err := Validate(v) if err != nil { return nil, err } switch v := v.(type) { case *URI: return &v.URL, nil case URI: return &v.URL, nil case *URIRef: return &v.URL, nil case URIRef: return &v.URL, nil case string: u, err := url.Parse(v) if err != nil { return nil, err } return u, nil default: return nil, convertErr((*url.URL)(nil), v) } }
ToURL returns a *url.URL value, parsing from string if necessary.
ToURL
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToTime(v interface{}) (time.Time, error) { v, err := Validate(v) if err != nil { return time.Time{}, err } switch v := v.(type) { case Timestamp: return v.Time, nil case string: ts, err := time.Parse(time.RFC3339Nano, v) if err != nil { return time.Time{}, err } return ts, nil default: return time.Time{}, convertErr(time.Time{}, v) } }
ToTime returns a time.Time value, parsing from RFC3339 string if necessary.
ToTime
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func (t valueTester) convert(v interface{}) (interface{}, error) { rf := reflect.ValueOf(t.convertFn) args := []reflect.Value{reflect.ValueOf(v)} if v == nil { args[0] = reflect.Zero(rf.Type().In(0)) // Avoid the zero argument reflection trap. } result := rf.Call(args) err, _ := result[1].Interface().(error) return result[0].Interface(), err }
Call types.To... function, use reflection since return types differ.
convert
go
cloudevents/sdk-go
v2/types/value_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value_test.go
Apache-2.0
func (t *valueTester) ok(in, want interface{}, wantStr string) { t.Helper() got, err := types.Validate(in) require.NoError(t, err) assert.Equal(t, want, got) gotStr, err := types.Format(in) require.NoError(t, err) assert.Equal(t, wantStr, gotStr) x, err := t.convert(gotStr) assert.NoError(t, err) x2, err := types.Validate(x) assert.NoError(t, err) assert.Equal(t, want, x2) cloned := types.Clone(want) assert.Equal(t, want, cloned) }
Verify round trip: convertible -> wrapped -> string -> wrapped -> clone
ok
go
cloudevents/sdk-go
v2/types/value_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value_test.go
Apache-2.0
func (t *valueTester) okWithDifferentFromString(in, want interface{}, wantStr string, wantAfterStr interface{}) { t.Helper() got, err := types.Validate(in) require.NoError(t, err) assert.Equal(t, want, got) gotStr, err := types.Format(in) require.NoError(t, err) assert.Equal(t, wantStr, gotStr) x, err := t.convert(gotStr) assert.NoError(t, err) x2, err := types.Validate(x) assert.NoError(t, err) assert.Equal(t, wantAfterStr, x2) }
Verify round trip with exception: convertible -> wrapped -> string -> different wrapped
okWithDifferentFromString
go
cloudevents/sdk-go
v2/types/value_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value_test.go
Apache-2.0
func benchSimple(dbfile string, verbose bool, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db := makeDb(dbfile) defer db.Close() initSchema(db) // insert users var users []User base := time.Date(2023, 10, 1, 10, 0, 0, 0, time.Local) const nusers = 1_000_000 for i := 0; i < nusers; i++ { users = append(users, NewUser( i+1, // id, base.Add(time.Duration(i)*time.Minute), // created, fmt.Sprintf("user%08d@example.com", i+1), // email, true, // active, )) } t0 := time.Now() db.InsertUsers("INSERT INTO users(id,created,email,active) VALUES(?,?,?,?)", users) insertMillis := millisSince(t0) if verbose { log.Printf(" insert took %d ms", insertMillis) } // query users t0 = time.Now() users = db.FindUsers("SELECT id,created,email,active FROM users ORDER BY id") MustBeEqual(len(users), nusers) queryMillis := millisSince(t0) if verbose { log.Printf(" query took %d ms", queryMillis) } // validate query result for i, u := range users { MustBeEqual(i+1, u.Id) Must(2023 <= u.Created.Year() && u.Created.Year() <= 2025, "wrong created year in %v", u.Created) MustBeEqual("user0", u.Email[0:5]) MustBeEqual(true, u.Active) } // print results bench := "1_simple" log.Printf("%s - insert - %-10s - %10d", bench, db.DriverName(), insertMillis) log.Printf("%s - query - %-10s - %10d", bench, db.DriverName(), queryMillis) log.Printf("%s - dbsize - %-10s - %10d", bench, db.DriverName(), dbsize(dbfile)) }
Insert 1 million user rows in one database transaction. Then query all users once.
benchSimple
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func benchComplex(dbfile string, verbose bool, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db := makeDb(dbfile) defer db.Close() initSchema(db) const nusers = 200 const narticlesPerUser = 100 const ncommentsPerArticle = 20 if verbose { log.Printf("nusers = %d", nusers) log.Printf("narticlesPerUser = %d", narticlesPerUser) log.Printf("ncommentsPerArticle = %d", ncommentsPerArticle) } // make users, articles, comments var users []User var articles []Article var comments []Comment base := time.Date(2023, 10, 1, 10, 0, 0, 0, time.Local) var userId int var articleId int var commentId int for u := 0; u < nusers; u++ { userId++ user := NewUser( userId, // Id base.Add(time.Duration(u)*time.Minute), // Created fmt.Sprintf("user%08d@example.com", u+1), // Email u%2 == 0, // Active ) users = append(users, user) for a := 0; a < narticlesPerUser; a++ { articleId++ article := NewArticle( articleId, // Id base.Add(time.Duration(u)*time.Minute).Add(time.Duration(a)*time.Second), // Created userId, // UserId "article text", // Text ) articles = append(articles, article) for c := 0; c < ncommentsPerArticle; c++ { commentId++ comment := NewComment( commentId, base.Add(time.Duration(u)*time.Minute).Add(time.Duration(a)*time.Second).Add(time.Duration(c)*time.Millisecond), // created, articleId, "comment text", // text, ) comments = append(comments, comment) } } } // insert users, articles, comments t0 := time.Now() db.InsertUsers(insertUserSql, users) db.InsertArticles(insertArticleSql, articles) db.InsertComments(insertCommentSql, comments) insertMillis := millisSince(t0) if verbose { log.Printf(" insert took %d ms", insertMillis) } // query users, articles, comments in one big join querySql := "SELECT" + " users.id, users.created, users.email, users.active," + " articles.id, articles.created, articles.userId, articles.text," + " comments.id, comments.created, comments.articleId, comments.text" + " FROM users" + " LEFT JOIN articles ON articles.userId = users.id" + " LEFT JOIN comments ON comments.articleId = articles.id" + " ORDER BY users.created, articles.created, comments.created" t0 = time.Now() users, articles, comments = db.FindUsersArticlesComments(querySql) queryMillis := millisSince(t0) if verbose { log.Printf(" query took %d ms", queryMillis) } // validate query result MustBeEqual(nusers, len(users)) MustBeEqual(nusers*narticlesPerUser, len(articles)) MustBeEqual(nusers*narticlesPerUser*ncommentsPerArticle, len(comments)) for i, user := range users { MustBeEqual(i+1, user.Id) MustBeEqual(2023, user.Created.Year()) MustBeEqual("user0", user.Email[0:5]) MustBeEqual(i%2 == 0, user.Active) } for i, article := range articles { MustBeEqual(i+1, article.Id) MustBeEqual(2023, article.Created.Year()) MustBe(article.UserId >= 1) MustBe(article.UserId <= 1+nusers) MustBeEqual("article text", article.Text) if i > 0 { last := articles[i-1] MustBe(article.UserId >= last.UserId) } } for i, comment := range comments { MustBeEqual(i+1, comment.Id) MustBeEqual(2023, comment.Created.Year()) MustBe(comment.ArticleId >= 1) MustBe(comment.ArticleId <= 1+(nusers*narticlesPerUser)) MustBeEqual("comment text", comment.Text) if i > 0 { last := comments[i-1] MustBe(comment.ArticleId >= last.ArticleId) } } // print results bench := "2_complex" log.Printf("%s - insert - %-10s - %10d", bench, db.DriverName(), insertMillis) log.Printf("%s - query - %-10s - %10d", bench, db.DriverName(), queryMillis) log.Printf("%s - dbsize - %-10s - %10d", bench, db.DriverName(), dbsize(dbfile)) }
Insert 200 users in one database transaction. Then insert 20000 articles (100 articles for each user) in another transaction. Then insert 400000 articles (20 comments for each article) in another transaction. Then query all users, articles and comments in one big JOIN statement.
benchComplex
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func benchMany(dbfile string, verbose bool, nusers int, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db := makeDb(dbfile) defer db.Close() initSchema(db) // insert users var users []User base := time.Date(2023, 10, 1, 10, 0, 0, 0, time.Local) for i := 0; i < nusers; i++ { users = append(users, NewUser( i+1, // id, base.Add(time.Duration(i)*time.Minute), // created, fmt.Sprintf("user%08d@example.com", i+1), // email, true, // active, )) } t0 := time.Now() db.InsertUsers(insertUserSql, users) insertMillis := millisSince(t0) if verbose { log.Printf(" insert took %d ms", insertMillis) } // query users 1000 times t0 = time.Now() for i := 0; i < 1000; i++ { users = db.FindUsers("SELECT id,created,email,active FROM users ORDER BY id") MustBeEqual(len(users), nusers) } queryMillis := millisSince(t0) if verbose { log.Printf(" query took %d ms", queryMillis) } // validate query result for i, u := range users { MustBeEqual(i+1, u.Id) MustBeEqual(2023, u.Created.Year()) MustBeEqual("user0", u.Email[0:5]) MustBeEqual(true, u.Active) } // print results bench := fmt.Sprintf("3_many/%04d", nusers) log.Printf("%s - insert - %-10s - %10d", bench, db.DriverName(), insertMillis) log.Printf("%s - query - %-10s - %10d", bench, db.DriverName(), queryMillis) log.Printf("%s - dbsize - %-10s - %10d", bench, db.DriverName(), dbsize(dbfile)) }
Insert N users in one database transaction. Then query all users 1000 times. This benchmark is used to simluate a read-heavy use case.
benchMany
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func benchLarge(dbfile string, verbose bool, nsize int, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db := makeDb(dbfile) defer db.Close() initSchema(db) // insert user with large emails t0 := time.Now() base := time.Date(2023, 10, 1, 10, 0, 0, 0, time.Local) const nusers = 10_000 var users []User for i := 0; i < nusers; i++ { users = append(users, NewUser( i+1, // Id base.Add(time.Duration(i)*time.Second), // Created strings.Repeat("a", nsize), // Email true, // Active )) } db.InsertUsers(insertUserSql, users) insertMillis := millisSince(t0) // query users t0 = time.Now() users = db.FindUsers("SELECT id,created,email,active FROM users ORDER BY id") MustBeEqual(len(users), nusers) queryMillis := millisSince(t0) if verbose { log.Printf(" query took %d ms", queryMillis) } // validate query result for i, u := range users { MustBeEqual(i+1, u.Id) MustBeEqual(2023, u.Created.Year()) MustBeEqual("a", u.Email[0:1]) MustBeEqual(true, u.Active) } // print results bench := fmt.Sprintf("4_large/%06d", nsize) log.Printf("%s - insert - %-10s - %10d", bench, db.DriverName(), insertMillis) log.Printf("%s - query - %-10s - %10d", bench, db.DriverName(), queryMillis) log.Printf("%s - dbsize - %-10s - %10d", bench, db.DriverName(), dbsize(dbfile)) }
Insert 10000 users with N bytes of row content. Then query all users. This benchmark is used to simluate reading of large (gigabytes) databases.
benchLarge
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func benchConcurrent(dbfile string, verbose bool, ngoroutines int, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db1 := makeDb(dbfile) driverName := db1.DriverName() initSchema(db1) // insert many users base := time.Date(2023, 10, 1, 10, 0, 0, 0, time.Local) const nusers = 1_000_000 var users []User for i := 0; i < nusers; i++ { users = append(users, NewUser( i+1, // Id base.Add(time.Duration(i)*time.Second), // Created fmt.Sprintf("user%d@example.com", i+1), // Email true, // Active )) } t0 := time.Now() db1.InsertUsers(insertUserSql, users) db1.Close() insertMillis := millisSince(t0) // query users in N goroutines t0 = time.Now() var wg sync.WaitGroup for i := 0; i < ngoroutines; i++ { wg.Add(1) go func() { defer wg.Done() db := makeDb(dbfile) db.Exec( "PRAGMA foreign_keys=1", "PRAGMA busy_timeout=5000", // 5s busy timeout ) defer db.Close() users = db.FindUsers("SELECT id,created,email,active FROM users ORDER BY id") MustBeEqual(len(users), nusers) // validate query result for i, u := range users { MustBeEqual(i+1, u.Id) MustBeEqual(2023, u.Created.Year()) MustBeEqual("user", u.Email[0:4]) MustBeEqual(true, u.Active) } }() } // wait for completion wg.Wait() queryMillis := millisSince(t0) if verbose { log.Printf(" query took %d ms", queryMillis) } // print results bench := fmt.Sprintf("5_concurrent/%d", ngoroutines) log.Printf("%s - insert - %-10s - %10d", bench, driverName, insertMillis) log.Printf("%s - query - %-10s - %10d", bench, driverName, queryMillis) log.Printf("%s - dbsize - %-10s - %10d", bench, driverName, dbsize(dbfile)) }
Insert one million users. Then have N goroutines query all users. This benchmark is used to simulate concurrent reads.
benchConcurrent
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func ToCamelCase(str string) string { return toCamelCase(str, false) }
ToCamelCase is to convert words separated by space, underscore and hyphen to camel case. Some samples. "some_words" => "someWords" "http_server" => "httpServer" "no_https" => "noHttps" "_complex__case_" => "_complex_Case_" "some words" => "someWords" "GOLANG_IS_GREAT" => "golangIsGreat"
ToCamelCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func ToPascalCase(str string) string { return toCamelCase(str, true) }
ToPascalCase is to convert words separated by space, underscore and hyphen to pascal case. Some samples. "some_words" => "SomeWords" "http_server" => "HttpServer" "no_https" => "NoHttps" "_complex__case_" => "_Complex_Case_" "some words" => "SomeWords" "GOLANG_IS_GREAT" => "GolangIsGreat"
ToPascalCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func ToSnakeCase(str string) string { return camelCaseToLowerCase(str, '_') }
ToSnakeCase can convert all upper case characters in a string to snake case format. Some samples. "FirstName" => "first_name" "HTTPServer" => "http_server" "NoHTTPS" => "no_https" "GO_PATH" => "go_path" "GO PATH" => "go_path" // space is converted to underscore. "GO-PATH" => "go_path" // hyphen is converted to underscore. "http2xx" => "http_2xx" // insert an underscore before a number and after an alphabet. "HTTP20xOK" => "http_20x_ok" "Duration2m3s" => "duration_2m3s" "Bld4Floor3rd" => "bld4_floor_3rd"
ToSnakeCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func ToKebabCase(str string) string { return camelCaseToLowerCase(str, '-') }
ToKebabCase can convert all upper case characters in a string to kebab case format. Some samples. "FirstName" => "first-name" "HTTPServer" => "http-server" "NoHTTPS" => "no-https" "GO_PATH" => "go-path" "GO PATH" => "go-path" // space is converted to '-'. "GO-PATH" => "go-path" // hyphen is converted to '-'. "http2xx" => "http-2xx" // insert an underscore before a number and after an alphabet. "HTTP20xOK" => "http-20x-ok" "Duration2m3s" => "duration-2m3s" "Bld4Floor3rd" => "bld4-floor-3rd"
ToKebabCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func SwapCase(str string) string { var r rune var size int buf := &stringBuilder{} for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) switch { case unicode.IsUpper(r): buf.WriteRune(unicode.ToLower(r)) case unicode.IsLower(r): buf.WriteRune(unicode.ToUpper(r)) default: buf.WriteRune(r) } str = str[size:] } return buf.String() }
SwapCase will swap characters case from upper to lower or lower to upper.
SwapCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func FirstRuneToUpper(str string) string { if str == "" { return str } r, size := utf8.DecodeRuneInString(str) if !unicode.IsLower(r) { return str } buf := &stringBuilder{} buf.WriteRune(unicode.ToUpper(r)) buf.WriteString(str[size:]) return buf.String() }
FirstRuneToUpper converts first rune to upper case if necessary.
FirstRuneToUpper
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func FirstRuneToLower(str string) string { if str == "" { return str } r, size := utf8.DecodeRuneInString(str) if !unicode.IsUpper(r) { return str } buf := &stringBuilder{} buf.WriteRune(unicode.ToLower(r)) buf.WriteString(str[size:]) return buf.String() }
FirstRuneToLower converts first rune to lower case if necessary.
FirstRuneToLower
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func Shuffle(str string) string { if str == "" { return str } runes := []rune(str) index := 0 for i := len(runes) - 1; i > 0; i-- { index = rand.Intn(i + 1) if i != index { runes[i], runes[index] = runes[index], runes[i] } } return string(runes) }
Shuffle randomizes runes in a string and returns the result. It uses default random source in `math/rand`.
Shuffle
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func ShuffleSource(str string, src rand.Source) string { if str == "" { return str } runes := []rune(str) index := 0 r := rand.New(src) for i := len(runes) - 1; i > 0; i-- { index = r.Intn(i + 1) if i != index { runes[i], runes[index] = runes[index], runes[i] } } return string(runes) }
ShuffleSource randomizes runes in a string with given random source.
ShuffleSource
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func Successor(str string) string { if str == "" { return str } var r rune var i int carry := ' ' runes := []rune(str) l := len(runes) lastAlphanumeric := l for i = l - 1; i >= 0; i-- { r = runes[i] if ('a' <= r && r <= 'y') || ('A' <= r && r <= 'Y') || ('0' <= r && r <= '8') { runes[i]++ carry = ' ' lastAlphanumeric = i break } switch r { case 'z': runes[i] = 'a' carry = 'a' lastAlphanumeric = i case 'Z': runes[i] = 'A' carry = 'A' lastAlphanumeric = i case '9': runes[i] = '0' carry = '0' lastAlphanumeric = i } } // Needs to add one character for carry. if i < 0 && carry != ' ' { buf := &stringBuilder{} buf.Grow(l + 4) // Reserve enough space for write. if lastAlphanumeric != 0 { buf.WriteString(str[:lastAlphanumeric]) } buf.WriteRune(carry) for _, r = range runes[lastAlphanumeric:] { buf.WriteRune(r) } return buf.String() } // No alphanumeric character. Simply increase last rune's value. if lastAlphanumeric == l { runes[l-1]++ } return string(runes) }
Successor returns the successor to string. If there is one alphanumeric rune is found in string, increase the rune by 1. If increment generates a "carry", the rune to the left of it is incremented. This process repeats until there is no carry, adding an additional rune if necessary. If there is no alphanumeric rune, the rightmost rune will be increased by 1 regardless whether the result is a valid rune or not. Only following characters are alphanumeric. - a - z - A - Z - 0 - 9 Samples (borrowed from ruby's String#succ document): "abcd" => "abce" "THX1138" => "THX1139" "<<koala>>" => "<<koalb>>" "1999zzz" => "2000aaa" "ZZZ9999" => "AAAA0000" "***" => "**+"
Successor
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func WordCount(str string) int { var r rune var size, n int inWord := false for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) switch { case isAlphabet(r): if !inWord { inWord = true n++ } case inWord && (r == '\'' || r == '-'): // Still in word. default: inWord = false } str = str[size:] } return n }
WordCount returns number of words in a string. Word is defined as a locale dependent string containing alphabetic characters, which may also contain but not start with `'` and `-` characters.
WordCount
go
huandu/xstrings
count.go
https://github.com/huandu/xstrings/blob/master/count.go
MIT
func isAlphabet(r rune) bool { if !unicode.IsLetter(r) { return false } switch { // Quick check for non-CJK character. case r < minCJKCharacter: return true // Common CJK characters. case r >= '\u4E00' && r <= '\u9FCC': return false // Rare CJK characters. case r >= '\u3400' && r <= '\u4D85': return false // Rare and historic CJK characters. case r >= '\U00020000' && r <= '\U0002B81D': return false } return true }
Checks r is a letter but not CJK character.
isAlphabet
go
huandu/xstrings
count.go
https://github.com/huandu/xstrings/blob/master/count.go
MIT
func Width(str string) int { var r rune var size, n int for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) n += RuneWidth(r) str = str[size:] } return n }
Width returns string width in monotype font. Multi-byte characters are usually twice the width of single byte characters. Algorithm comes from `mb_strwidth` in PHP. http://php.net/manual/en/function.mb-strwidth.php
Width
go
huandu/xstrings
count.go
https://github.com/huandu/xstrings/blob/master/count.go
MIT
func RuneWidth(r rune) int { switch { case r == utf8.RuneError || r < '\x20': return 0 case '\x20' <= r && r < '\u2000': return 1 case '\u2000' <= r && r < '\uFF61': return 2 case '\uFF61' <= r && r < '\uFFA0': return 1 case '\uFFA0' <= r: return 2 } return 0 }
RuneWidth returns character width in monotype font. Multi-byte characters are usually twice the width of single byte characters. Algorithm comes from `mb_strwidth` in PHP. http://php.net/manual/en/function.mb-strwidth.php
RuneWidth
go
huandu/xstrings
count.go
https://github.com/huandu/xstrings/blob/master/count.go
MIT
func Slice(str string, start, end int) string { var size, startPos, endPos int origin := str if start < 0 || end > len(str) || (end >= 0 && start > end) { panic("out of range") } if end >= 0 { end -= start } for start > 0 && len(str) > 0 { _, size = utf8.DecodeRuneInString(str) start-- startPos += size str = str[size:] } if end < 0 { return origin[startPos:] } endPos = startPos for end > 0 && len(str) > 0 { _, size = utf8.DecodeRuneInString(str) end-- endPos += size str = str[size:] } if len(str) == 0 && (start > 0 || end > 0) { panic("out of range") } return origin[startPos:endPos] }
Slice a string by rune. Start must satisfy 0 <= start <= rune length. End can be positive, zero or negative. If end >= 0, start and end must satisfy start <= end <= rune length. If end < 0, it means slice to the end of string. Otherwise, Slice will panic as out of range.
Slice
go
huandu/xstrings
manipulate.go
https://github.com/huandu/xstrings/blob/master/manipulate.go
MIT
func Partition(str, sep string) (head, match, tail string) { index := strings.Index(str, sep) if index == -1 { head = str return } head = str[:index] match = str[index : index+len(sep)] tail = str[index+len(sep):] return }
Partition splits a string by sep into three parts. The return value is a slice of strings with head, match and tail. If str contains sep, for example "hello" and "l", Partition returns "he", "l", "lo" If str doesn't contain sep, for example "hello" and "x", Partition returns "hello", "", ""
Partition
go
huandu/xstrings
manipulate.go
https://github.com/huandu/xstrings/blob/master/manipulate.go
MIT
func LastPartition(str, sep string) (head, match, tail string) { index := strings.LastIndex(str, sep) if index == -1 { tail = str return } head = str[:index] match = str[index : index+len(sep)] tail = str[index+len(sep):] return }
LastPartition splits a string by last instance of sep into three parts. The return value is a slice of strings with head, match and tail. If str contains sep, for example "hello" and "l", LastPartition returns "hel", "l", "o" If str doesn't contain sep, for example "hello" and "x", LastPartition returns "", "", "hello"
LastPartition
go
huandu/xstrings
manipulate.go
https://github.com/huandu/xstrings/blob/master/manipulate.go
MIT
func Insert(dst, src string, index int) string { return Slice(dst, 0, index) + src + Slice(dst, index, -1) }
Insert src into dst at given rune index. Index is counted by runes instead of bytes. If index is out of range of dst, panic with out of range.
Insert
go
huandu/xstrings
manipulate.go
https://github.com/huandu/xstrings/blob/master/manipulate.go
MIT
func Scrub(str, repl string) string { var buf *stringBuilder var r rune var size, pos int var hasError bool origin := str for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) if r == utf8.RuneError { if !hasError { if buf == nil { buf = &stringBuilder{} } buf.WriteString(origin[:pos]) hasError = true } } else if hasError { hasError = false buf.WriteString(repl) origin = origin[pos:] pos = 0 } pos += size str = str[size:] } if buf != nil { buf.WriteString(origin) return buf.String() } // No invalid byte. return origin }
Scrub scrubs invalid utf8 bytes with repl string. Adjacent invalid bytes are replaced only once.
Scrub
go
huandu/xstrings
manipulate.go
https://github.com/huandu/xstrings/blob/master/manipulate.go
MIT
func WordSplit(str string) []string { var word string var words []string var r rune var size, pos int inWord := false for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) switch { case isAlphabet(r): if !inWord { inWord = true word = str pos = 0 } case inWord && (r == '\'' || r == '-'): // Still in word. default: if inWord { inWord = false words = append(words, word[:pos]) } } pos += size str = str[size:] } if inWord { words = append(words, word[:pos]) } return words }
WordSplit splits a string into words. Returns a slice of words. If there is no word in a string, return nil. Word is defined as a locale dependent string containing alphabetic characters, which may also contain but not start with `'` and `-` characters.
WordSplit
go
huandu/xstrings
manipulate.go
https://github.com/huandu/xstrings/blob/master/manipulate.go
MIT
func NewTranslator(from, to string) *Translator { tr := &Translator{} if from == "" { return tr } reverted := from[0] == '^' deletion := len(to) == 0 if reverted { from = from[1:] } var fromStart, fromEnd, fromRangeStep rune var toStart, toEnd, toRangeStep rune var fromRangeSize, toRangeSize rune var singleRunes []rune // Update the to rune range. updateRange := func() { // No more rune to read in the to rune pattern. if toEnd == utf8.RuneError { return } if toRangeStep == 0 { to, toStart, toEnd, toRangeStep = nextRuneRange(to, toEnd) return } // Current range is not empty. Consume 1 rune from start. if toStart != toEnd { toStart += toRangeStep return } // No more rune. Repeat the last rune. if to == "" { toEnd = utf8.RuneError return } // Both start and end are used. Read two more runes from the to pattern. to, toStart, toEnd, toRangeStep = nextRuneRange(to, utf8.RuneError) } if deletion { toStart = utf8.RuneError toEnd = utf8.RuneError } else { // If from pattern is reverted, only the last rune in the to pattern will be used. if reverted { var size int for len(to) > 0 { toStart, size = utf8.DecodeRuneInString(to) to = to[size:] } toEnd = utf8.RuneError } else { to, toStart, toEnd, toRangeStep = nextRuneRange(to, utf8.RuneError) } } fromEnd = utf8.RuneError for len(from) > 0 { from, fromStart, fromEnd, fromRangeStep = nextRuneRange(from, fromEnd) // fromStart is a single character. Just map it with a rune in the to pattern. if fromRangeStep == 0 { singleRunes = tr.addRune(fromStart, toStart, singleRunes) updateRange() continue } for toEnd != utf8.RuneError && fromStart != fromEnd { // If mapped rune is a single character instead of a range, simply shift first // rune in the range. if toRangeStep == 0 { singleRunes = tr.addRune(fromStart, toStart, singleRunes) updateRange() fromStart += fromRangeStep continue } fromRangeSize = (fromEnd - fromStart) * fromRangeStep toRangeSize = (toEnd - toStart) * toRangeStep // Not enough runes in the to pattern. Need to read more. if fromRangeSize > toRangeSize { fromStart, toStart = tr.addRuneRange(fromStart, fromStart+toRangeSize*fromRangeStep, toStart, toEnd, singleRunes) fromStart += fromRangeStep updateRange() // Edge case: If fromRangeSize == toRangeSize + 1, the last fromStart value needs be considered // as a single rune. if fromStart == fromEnd { singleRunes = tr.addRune(fromStart, toStart, singleRunes) updateRange() } continue } fromStart, toStart = tr.addRuneRange(fromStart, fromEnd, toStart, toStart+fromRangeSize*toRangeStep, singleRunes) updateRange() break } if fromStart == fromEnd { fromEnd = utf8.RuneError continue } _, toStart = tr.addRuneRange(fromStart, fromEnd, toStart, toStart, singleRunes) fromEnd = utf8.RuneError } if fromEnd != utf8.RuneError { tr.addRune(fromEnd, toStart, singleRunes) } tr.reverted = reverted tr.mappedRune = -1 tr.hasPattern = true // Translate RuneError only if in deletion or reverted mode. if deletion || reverted { tr.mappedRune = toStart } return tr }
NewTranslator creates new Translator through a from/to pattern pair.
NewTranslator
go
huandu/xstrings
translate.go
https://github.com/huandu/xstrings/blob/master/translate.go
MIT
func (tr *Translator) Translate(str string) string { if !tr.hasPattern || str == "" { return str } var r rune var size int var needTr bool orig := str var output *stringBuilder for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) r, needTr = tr.TranslateRune(r) if needTr && output == nil { output = allocBuffer(orig, str) } if r != utf8.RuneError && output != nil { output.WriteRune(r) } str = str[size:] } // No character is translated. if output == nil { return orig } return output.String() }
Translate str with a from/to pattern pair. See comment in Translate function for usage and samples.
Translate
go
huandu/xstrings
translate.go
https://github.com/huandu/xstrings/blob/master/translate.go
MIT
func (tr *Translator) TranslateRune(r rune) (result rune, translated bool) { switch { case tr.quickDict != nil: if r <= unicode.MaxASCII { result = tr.quickDict.Dict[r] if result != 0 { translated = true if tr.mappedRune >= 0 { result = tr.mappedRune } break } } fallthrough case tr.runeMap != nil: var ok bool if result, ok = tr.runeMap[r]; ok { translated = true if tr.mappedRune >= 0 { result = tr.mappedRune } break } fallthrough default: var rrm *runeRangeMap ranges := tr.ranges for i := len(ranges) - 1; i >= 0; i-- { rrm = ranges[i] if rrm.FromLo <= r && r <= rrm.FromHi { translated = true if tr.mappedRune >= 0 { result = tr.mappedRune break } if rrm.ToLo < rrm.ToHi { result = rrm.ToLo + r - rrm.FromLo } else if rrm.ToLo > rrm.ToHi { // ToHi can be smaller than ToLo if range is from higher to lower. result = rrm.ToLo - r + rrm.FromLo } else { result = rrm.ToLo } break } } } if tr.reverted { if !translated { result = tr.mappedRune } translated = !translated } if !translated { result = r } return }
TranslateRune return translated rune and true if r matches the from pattern. If r doesn't match the pattern, original r is returned and translated is false.
TranslateRune
go
huandu/xstrings
translate.go
https://github.com/huandu/xstrings/blob/master/translate.go
MIT
func (tr *Translator) HasPattern() bool { return tr.hasPattern }
HasPattern returns true if Translator has one pattern at least.
HasPattern
go
huandu/xstrings
translate.go
https://github.com/huandu/xstrings/blob/master/translate.go
MIT
func Translate(str, from, to string) string { tr := NewTranslator(from, to) return tr.Translate(str) }
Translate str with the characters defined in from replaced by characters defined in to. From and to are patterns representing a set of characters. Pattern is defined as following. Special characters: 1. '-' means a range of runes, e.g. "a-z" means all characters from 'a' to 'z' inclusive; "z-a" means all characters from 'z' to 'a' inclusive. 2. '^' as first character means a set of all runes excepted listed, e.g. "^a-z" means all characters except 'a' to 'z' inclusive. 3. '\' escapes special characters. Normal character represents itself, e.g. "abc" is a set including 'a', 'b' and 'c'. Translate will try to find a 1:1 mapping from from to to. If to is smaller than from, last rune in to will be used to map "out of range" characters in from. Note that '^' only works in the from pattern. It will be considered as a normal character in the to pattern. If the to pattern is an empty string, Translate works exactly the same as Delete. Samples: Translate("hello", "aeiou", "12345") => "h2ll4" Translate("hello", "a-z", "A-Z") => "HELLO" Translate("hello", "z-a", "a-z") => "svool" Translate("hello", "aeiou", "*") => "h*ll*" Translate("hello", "^l", "*") => "**ll*" Translate("hello ^ world", `\^lo`, "*") => "he*** * w*r*d"
Translate
go
huandu/xstrings
translate.go
https://github.com/huandu/xstrings/blob/master/translate.go
MIT
func Delete(str, pattern string) string { tr := NewTranslator(pattern, "") return tr.Translate(str) }
Delete runes in str matching the pattern. Pattern is defined in Translate function. Samples: Delete("hello", "aeiou") => "hll" Delete("hello", "a-k") => "llo" Delete("hello", "^a-k") => "he"
Delete
go
huandu/xstrings
translate.go
https://github.com/huandu/xstrings/blob/master/translate.go
MIT
func Count(str, pattern string) int { if pattern == "" || str == "" { return 0 } var r rune var size int var matched bool tr := NewTranslator(pattern, "") cnt := 0 for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) str = str[size:] if _, matched = tr.TranslateRune(r); matched { cnt++ } } return cnt }
Count how many runes in str match the pattern. Pattern is defined in Translate function. Samples: Count("hello", "aeiou") => 3 Count("hello", "a-k") => 3 Count("hello", "^a-k") => 2
Count
go
huandu/xstrings
translate.go
https://github.com/huandu/xstrings/blob/master/translate.go
MIT
func Squeeze(str, pattern string) string { var last, r rune var size int var skipSqueeze, matched bool var tr *Translator var output *stringBuilder orig := str last = -1 if len(pattern) > 0 { tr = NewTranslator(pattern, "") } for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) // Need to squeeze the str. if last == r && !skipSqueeze { if tr != nil { if _, matched = tr.TranslateRune(r); !matched { skipSqueeze = true } } if output == nil { output = allocBuffer(orig, str) } if skipSqueeze { output.WriteRune(r) } } else { if output != nil { output.WriteRune(r) } last = r skipSqueeze = false } str = str[size:] } if output == nil { return orig } return output.String() }
Squeeze deletes adjacent repeated runes in str. If pattern is not empty, only runes matching the pattern will be squeezed. Samples: Squeeze("hello", "") => "helo" Squeeze("hello", "m-z") => "hello" Squeeze("hello world", " ") => "hello world"
Squeeze
go
huandu/xstrings
translate.go
https://github.com/huandu/xstrings/blob/master/translate.go
MIT
func NewClient(server string, opts ...ClientOption) (*Client, error) { // create a client with sane default values client := Client{ Server: server, } // mutate client and add all optional params for _, o := range opts { if err := o(&client); err != nil { return nil, err } } // ensure the server URL always has a trailing slash if !strings.HasSuffix(client.Server, "/") { client.Server += "/" } // create httpClient, if not already present if client.Client == nil { client.Client = &http.Client{} } return &client, nil }
Creates a new Client, with reasonable defaults
NewClient
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func WithHTTPClient(doer HttpRequestDoer) ClientOption { return func(c *Client) error { c.Client = doer return nil } }
WithHTTPClient allows overriding the default Doer, which is automatically created using http.Client. This is useful for tests.
WithHTTPClient
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func WithRequestEditorFn(fn RequestEditorFn) ClientOption { return func(c *Client) error { c.RequestEditors = append(c.RequestEditors, fn) return nil } }
WithRequestEditorFn allows setting up a callback function, which will be called right before sending the request. This can be used to mutate the request.
WithRequestEditorFn
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPostAdminGenerateLinkRequest(server string, body PostAdminGenerateLinkJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) return NewPostAdminGenerateLinkRequestWithBody(server, "application/json", bodyReader) }
NewPostAdminGenerateLinkRequest calls the generic PostAdminGenerateLink builder with application/json body
NewPostAdminGenerateLinkRequest
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPostAdminGenerateLinkRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { var err error serverURL, err := url.Parse(server) if err != nil { return nil, err } operationPath := fmt.Sprintf("/admin/generate_link") if operationPath[0] == '/' { operationPath = "." + operationPath } queryURL, err := serverURL.Parse(operationPath) if err != nil { return nil, err } req, err := http.NewRequest("POST", queryURL.String(), body) if err != nil { return nil, err } req.Header.Add("Content-Type", contentType) return req, nil }
NewPostAdminGenerateLinkRequestWithBody generates requests for PostAdminGenerateLink with any type of body
NewPostAdminGenerateLinkRequestWithBody
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPostAdminSsoProvidersRequest(server string, body PostAdminSsoProvidersJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) return NewPostAdminSsoProvidersRequestWithBody(server, "application/json", bodyReader) }
NewPostAdminSsoProvidersRequest calls the generic PostAdminSsoProviders builder with application/json body
NewPostAdminSsoProvidersRequest
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPostAdminSsoProvidersRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { var err error serverURL, err := url.Parse(server) if err != nil { return nil, err } operationPath := fmt.Sprintf("/admin/sso/providers") if operationPath[0] == '/' { operationPath = "." + operationPath } queryURL, err := serverURL.Parse(operationPath) if err != nil { return nil, err } req, err := http.NewRequest("POST", queryURL.String(), body) if err != nil { return nil, err } req.Header.Add("Content-Type", contentType) return req, nil }
NewPostAdminSsoProvidersRequestWithBody generates requests for PostAdminSsoProviders with any type of body
NewPostAdminSsoProvidersRequestWithBody
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPutAdminSsoProvidersSsoProviderIdRequest(server string, ssoProviderId openapi_types.UUID, body PutAdminSsoProvidersSsoProviderIdJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) return NewPutAdminSsoProvidersSsoProviderIdRequestWithBody(server, ssoProviderId, "application/json", bodyReader) }
NewPutAdminSsoProvidersSsoProviderIdRequest calls the generic PutAdminSsoProvidersSsoProviderId builder with application/json body
NewPutAdminSsoProvidersSsoProviderIdRequest
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPutAdminSsoProvidersSsoProviderIdRequestWithBody(server string, ssoProviderId openapi_types.UUID, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string pathParam0, err = runtime.StyleParamWithLocation("simple", false, "ssoProviderId", runtime.ParamLocationPath, ssoProviderId) if err != nil { return nil, err } serverURL, err := url.Parse(server) if err != nil { return nil, err } operationPath := fmt.Sprintf("/admin/sso/providers/%s", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } queryURL, err := serverURL.Parse(operationPath) if err != nil { return nil, err } req, err := http.NewRequest("PUT", queryURL.String(), body) if err != nil { return nil, err } req.Header.Add("Content-Type", contentType) return req, nil }
NewPutAdminSsoProvidersSsoProviderIdRequestWithBody generates requests for PutAdminSsoProvidersSsoProviderId with any type of body
NewPutAdminSsoProvidersSsoProviderIdRequestWithBody
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPutAdminUsersUserIdRequest(server string, userId openapi_types.UUID, body PutAdminUsersUserIdJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) return NewPutAdminUsersUserIdRequestWithBody(server, userId, "application/json", bodyReader) }
NewPutAdminUsersUserIdRequest calls the generic PutAdminUsersUserId builder with application/json body
NewPutAdminUsersUserIdRequest
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPutAdminUsersUserIdRequestWithBody(server string, userId openapi_types.UUID, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) if err != nil { return nil, err } serverURL, err := url.Parse(server) if err != nil { return nil, err } operationPath := fmt.Sprintf("/admin/users/%s", pathParam0) if operationPath[0] == '/' { operationPath = "." + operationPath } queryURL, err := serverURL.Parse(operationPath) if err != nil { return nil, err } req, err := http.NewRequest("PUT", queryURL.String(), body) if err != nil { return nil, err } req.Header.Add("Content-Type", contentType) return req, nil }
NewPutAdminUsersUserIdRequestWithBody generates requests for PutAdminUsersUserId with any type of body
NewPutAdminUsersUserIdRequestWithBody
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPutAdminUsersUserIdFactorsFactorIdRequest(server string, userId openapi_types.UUID, factorId openapi_types.UUID, body PutAdminUsersUserIdFactorsFactorIdJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) return NewPutAdminUsersUserIdFactorsFactorIdRequestWithBody(server, userId, factorId, "application/json", bodyReader) }
NewPutAdminUsersUserIdFactorsFactorIdRequest calls the generic PutAdminUsersUserIdFactorsFactorId builder with application/json body
NewPutAdminUsersUserIdFactorsFactorIdRequest
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT
func NewPutAdminUsersUserIdFactorsFactorIdRequestWithBody(server string, userId openapi_types.UUID, factorId openapi_types.UUID, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string pathParam0, err = runtime.StyleParamWithLocation("simple", false, "userId", runtime.ParamLocationPath, userId) if err != nil { return nil, err } var pathParam1 string pathParam1, err = runtime.StyleParamWithLocation("simple", false, "factorId", runtime.ParamLocationPath, factorId) if err != nil { return nil, err } serverURL, err := url.Parse(server) if err != nil { return nil, err } operationPath := fmt.Sprintf("/admin/users/%s/factors/%s", pathParam0, pathParam1) if operationPath[0] == '/' { operationPath = "." + operationPath } queryURL, err := serverURL.Parse(operationPath) if err != nil { return nil, err } req, err := http.NewRequest("PUT", queryURL.String(), body) if err != nil { return nil, err } req.Header.Add("Content-Type", contentType) return req, nil }
NewPutAdminUsersUserIdFactorsFactorIdRequestWithBody generates requests for PutAdminUsersUserIdFactorsFactorId with any type of body
NewPutAdminUsersUserIdFactorsFactorIdRequestWithBody
go
supabase/auth
client/admin/client.go
https://github.com/supabase/auth/blob/master/client/admin/client.go
MIT