id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens listlengths 21 1.41k | docstring stringlengths 6 2.61k | docstring_tokens listlengths 3 215 | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9,600 | couchbase/gocb | error.go | IsHTTPError | func IsHTTPError(err error) bool {
cause := errors.Cause(err)
if nErr, ok := cause.(HTTPError); ok {
return nErr.HTTPError()
}
return false
} | go | func IsHTTPError(err error) bool {
cause := errors.Cause(err)
if nErr, ok := cause.(HTTPError); ok {
return nErr.HTTPError()
}
return false
} | [
"func",
"IsHTTPError",
"(",
"err",
"error",
")",
"bool",
"{",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n",
"if",
"nErr",
",",
"ok",
":=",
"cause",
".",
"(",
"HTTPError",
")",
";",
"ok",
"{",
"return",
"nErr",
".",
"HTTPError",
"(",... | // IsHTTPError indicates whether the passed error is a
// HTTP error. | [
"IsHTTPError",
"indicates",
"whether",
"the",
"passed",
"error",
"is",
"a",
"HTTP",
"error",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L182-L189 |
9,601 | couchbase/gocb | error.go | IsNetworkError | func IsNetworkError(err error) bool {
cause := errors.Cause(err)
if nErr, ok := cause.(NetworkError); ok {
return nErr.NetworkError()
}
return false
} | go | func IsNetworkError(err error) bool {
cause := errors.Cause(err)
if nErr, ok := cause.(NetworkError); ok {
return nErr.NetworkError()
}
return false
} | [
"func",
"IsNetworkError",
"(",
"err",
"error",
")",
"bool",
"{",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n",
"if",
"nErr",
",",
"ok",
":=",
"cause",
".",
"(",
"NetworkError",
")",
";",
"ok",
"{",
"return",
"nErr",
".",
"NetworkError... | // IsNetworkError indicates whether the passed error is a
// network error. | [
"IsNetworkError",
"indicates",
"whether",
"the",
"passed",
"error",
"is",
"a",
"network",
"error",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L193-L200 |
9,602 | couchbase/gocb | error.go | IsServiceNotFoundError | func IsServiceNotFoundError(err error) bool {
cause := errors.Cause(err)
if nErr, ok := cause.(ServiceNotFoundError); ok {
return nErr.ServiceNotFoundError()
}
return false
} | go | func IsServiceNotFoundError(err error) bool {
cause := errors.Cause(err)
if nErr, ok := cause.(ServiceNotFoundError); ok {
return nErr.ServiceNotFoundError()
}
return false
} | [
"func",
"IsServiceNotFoundError",
"(",
"err",
"error",
")",
"bool",
"{",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n",
"if",
"nErr",
",",
"ok",
":=",
"cause",
".",
"(",
"ServiceNotFoundError",
")",
";",
"ok",
"{",
"return",
"nErr",
".",... | // IsServiceNotFoundError indicates whether the passed error occurred due to
// the requested service not being found. | [
"IsServiceNotFoundError",
"indicates",
"whether",
"the",
"passed",
"error",
"occurred",
"due",
"to",
"the",
"requested",
"service",
"not",
"being",
"found",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L204-L211 |
9,603 | couchbase/gocb | error.go | IsTimeoutError | func IsTimeoutError(err error) bool {
switch errType := errors.Cause(err).(type) {
case TimeoutError:
return errType.Timeout()
default:
return false
}
} | go | func IsTimeoutError(err error) bool {
switch errType := errors.Cause(err).(type) {
case TimeoutError:
return errType.Timeout()
default:
return false
}
} | [
"func",
"IsTimeoutError",
"(",
"err",
"error",
")",
"bool",
"{",
"switch",
"errType",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"type",
")",
"{",
"case",
"TimeoutError",
":",
"return",
"errType",
".",
"Timeout",
"(",
")",
"\n",
"default"... | // IsTimeoutError verifies whether or not the cause for an error is a timeout. | [
"IsTimeoutError",
"verifies",
"whether",
"or",
"not",
"the",
"cause",
"for",
"an",
"error",
"is",
"a",
"timeout",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L214-L221 |
9,604 | couchbase/gocb | error.go | IsAuthenticationError | func IsAuthenticationError(err error) bool {
cause := errors.Cause(err)
if kvErr, ok := cause.(KeyValueError); ok && kvErr.KVError() {
return kvErr.StatusCode() == int(gocbcore.StatusAuthError)
}
return false
} | go | func IsAuthenticationError(err error) bool {
cause := errors.Cause(err)
if kvErr, ok := cause.(KeyValueError); ok && kvErr.KVError() {
return kvErr.StatusCode() == int(gocbcore.StatusAuthError)
}
return false
} | [
"func",
"IsAuthenticationError",
"(",
"err",
"error",
")",
"bool",
"{",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n",
"if",
"kvErr",
",",
"ok",
":=",
"cause",
".",
"(",
"KeyValueError",
")",
";",
"ok",
"&&",
"kvErr",
".",
"KVError",
"... | // IsAuthenticationError verifies whether or not the cause for an error is an authentication error. | [
"IsAuthenticationError",
"verifies",
"whether",
"or",
"not",
"the",
"cause",
"for",
"an",
"error",
"is",
"an",
"authentication",
"error",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L224-L231 |
9,605 | couchbase/gocb | error.go | IsBucketMissingError | func IsBucketMissingError(err error) bool {
cause := errors.Cause(err)
if kvErr, ok := cause.(KeyValueError); ok && kvErr.KVError() {
return kvErr.StatusCode() == int(gocbcore.StatusNoBucket)
}
return false
} | go | func IsBucketMissingError(err error) bool {
cause := errors.Cause(err)
if kvErr, ok := cause.(KeyValueError); ok && kvErr.KVError() {
return kvErr.StatusCode() == int(gocbcore.StatusNoBucket)
}
return false
} | [
"func",
"IsBucketMissingError",
"(",
"err",
"error",
")",
"bool",
"{",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n",
"if",
"kvErr",
",",
"ok",
":=",
"cause",
".",
"(",
"KeyValueError",
")",
";",
"ok",
"&&",
"kvErr",
".",
"KVError",
"(... | // IsBucketMissingError verifies whether or not the cause for an error is a bucket missing error. | [
"IsBucketMissingError",
"verifies",
"whether",
"or",
"not",
"the",
"cause",
"for",
"an",
"error",
"is",
"a",
"bucket",
"missing",
"error",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L234-L241 |
9,606 | couchbase/gocb | error.go | IsAccessError | func IsAccessError(err error) bool {
cause := errors.Cause(err)
if kvErr, ok := cause.(KeyValueError); ok && kvErr.KVError() {
return kvErr.StatusCode() == int(gocbcore.StatusAccessError)
}
return false
} | go | func IsAccessError(err error) bool {
cause := errors.Cause(err)
if kvErr, ok := cause.(KeyValueError); ok && kvErr.KVError() {
return kvErr.StatusCode() == int(gocbcore.StatusAccessError)
}
return false
} | [
"func",
"IsAccessError",
"(",
"err",
"error",
")",
"bool",
"{",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n",
"if",
"kvErr",
",",
"ok",
":=",
"cause",
".",
"(",
"KeyValueError",
")",
";",
"ok",
"&&",
"kvErr",
".",
"KVError",
"(",
")... | // IsAccessError verifies whether or not the cause for an error is an access error. | [
"IsAccessError",
"verifies",
"whether",
"or",
"not",
"the",
"cause",
"for",
"an",
"error",
"is",
"an",
"access",
"error",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L244-L251 |
9,607 | couchbase/gocb | error.go | IsConfigurationError | func IsConfigurationError(err error) bool {
switch errType := errors.Cause(err).(type) {
case ConfigurationError:
return errType.ConfigurationError()
default:
return false
}
} | go | func IsConfigurationError(err error) bool {
switch errType := errors.Cause(err).(type) {
case ConfigurationError:
return errType.ConfigurationError()
default:
return false
}
} | [
"func",
"IsConfigurationError",
"(",
"err",
"error",
")",
"bool",
"{",
"switch",
"errType",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"type",
")",
"{",
"case",
"ConfigurationError",
":",
"return",
"errType",
".",
"ConfigurationError",
"(",
"... | // IsConfigurationError verifies whether or not the cause for an error is a configuration error. | [
"IsConfigurationError",
"verifies",
"whether",
"or",
"not",
"the",
"cause",
"for",
"an",
"error",
"is",
"a",
"configuration",
"error",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L254-L261 |
9,608 | couchbase/gocb | error.go | IsSubdocPathNotFoundError | func IsSubdocPathNotFoundError(err error) bool {
cause := errors.Cause(err)
if kvErr, ok := cause.(KeyValueError); ok && kvErr.KVError() {
return kvErr.StatusCode() == int(gocbcore.StatusSubDocPathNotFound)
}
return false
} | go | func IsSubdocPathNotFoundError(err error) bool {
cause := errors.Cause(err)
if kvErr, ok := cause.(KeyValueError); ok && kvErr.KVError() {
return kvErr.StatusCode() == int(gocbcore.StatusSubDocPathNotFound)
}
return false
} | [
"func",
"IsSubdocPathNotFoundError",
"(",
"err",
"error",
")",
"bool",
"{",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n",
"if",
"kvErr",
",",
"ok",
":=",
"cause",
".",
"(",
"KeyValueError",
")",
";",
"ok",
"&&",
"kvErr",
".",
"KVError",... | // IsSubdocPathNotFoundError verifies whether or not the cause for an error is due to a subdoc operation path not found. | [
"IsSubdocPathNotFoundError",
"verifies",
"whether",
"or",
"not",
"the",
"cause",
"for",
"an",
"error",
"is",
"due",
"to",
"a",
"subdoc",
"operation",
"path",
"not",
"found",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L264-L271 |
9,609 | couchbase/gocb | error.go | IsDurabilityError | func IsDurabilityError(err error) bool {
switch errType := errors.Cause(err).(type) {
case DurabilityError:
return errType.DurabilityError()
default:
return false
}
} | go | func IsDurabilityError(err error) bool {
switch errType := errors.Cause(err).(type) {
case DurabilityError:
return errType.DurabilityError()
default:
return false
}
} | [
"func",
"IsDurabilityError",
"(",
"err",
"error",
")",
"bool",
"{",
"switch",
"errType",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"type",
")",
"{",
"case",
"DurabilityError",
":",
"return",
"errType",
".",
"DurabilityError",
"(",
")",
"\n... | // IsDurabilityError verifies whether or not the cause for an error is due to a durability error. | [
"IsDurabilityError",
"verifies",
"whether",
"or",
"not",
"the",
"cause",
"for",
"an",
"error",
"is",
"due",
"to",
"a",
"durability",
"error",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L284-L291 |
9,610 | couchbase/gocb | error.go | IsNoResultsError | func IsNoResultsError(err error) bool {
switch errType := errors.Cause(err).(type) {
case NoResultsError:
return errType.NoResultsError()
default:
return false
}
} | go | func IsNoResultsError(err error) bool {
switch errType := errors.Cause(err).(type) {
case NoResultsError:
return errType.NoResultsError()
default:
return false
}
} | [
"func",
"IsNoResultsError",
"(",
"err",
"error",
")",
"bool",
"{",
"switch",
"errType",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"type",
")",
"{",
"case",
"NoResultsError",
":",
"return",
"errType",
".",
"NoResultsError",
"(",
")",
"\n",
... | // IsNoResultsError verifies whether or not the cause for an error is due no results being available to a query. | [
"IsNoResultsError",
"verifies",
"whether",
"or",
"not",
"the",
"cause",
"for",
"an",
"error",
"is",
"due",
"no",
"results",
"being",
"available",
"to",
"a",
"query",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/error.go#L294-L301 |
9,611 | couchbase/gocb | cluster_analyticsquery.go | NextBytes | func (r *AnalyticsResults) NextBytes() []byte {
if r.streamResult.Closed() {
return nil
}
raw, err := r.streamResult.NextBytes()
if err != nil {
r.err = err
return nil
}
return raw
} | go | func (r *AnalyticsResults) NextBytes() []byte {
if r.streamResult.Closed() {
return nil
}
raw, err := r.streamResult.NextBytes()
if err != nil {
r.err = err
return nil
}
return raw
} | [
"func",
"(",
"r",
"*",
"AnalyticsResults",
")",
"NextBytes",
"(",
")",
"[",
"]",
"byte",
"{",
"if",
"r",
".",
"streamResult",
".",
"Closed",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"raw",
",",
"err",
":=",
"r",
".",
"streamResult",
".",
... | // NextBytes returns the next result from the results as a byte array. | [
"NextBytes",
"returns",
"the",
"next",
"result",
"from",
"the",
"results",
"as",
"a",
"byte",
"array",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/cluster_analyticsquery.go#L103-L115 |
9,612 | couchbase/gocb | cluster_analyticsquery.go | AnalyticsQuery | func (c *Cluster) AnalyticsQuery(statement string, opts *AnalyticsQueryOptions) (*AnalyticsResults, error) {
if opts == nil {
opts = &AnalyticsQueryOptions{}
}
ctx := opts.Context
if ctx == nil {
ctx = context.Background()
}
var span opentracing.Span
if opts.ParentSpanContext == nil {
span = opentracing.GlobalTracer().StartSpan("ExecuteAnalyticsQuery",
opentracing.Tag{Key: "couchbase.service", Value: "cbas"})
} else {
span = opentracing.GlobalTracer().StartSpan("ExecuteAnalyticsQuery",
opentracing.Tag{Key: "couchbase.service", Value: "cbas"}, opentracing.ChildOf(opts.ParentSpanContext))
}
defer span.Finish()
provider, err := c.getHTTPProvider()
if err != nil {
return nil, err
}
return c.analyticsQuery(ctx, span.Context(), statement, opts, provider)
} | go | func (c *Cluster) AnalyticsQuery(statement string, opts *AnalyticsQueryOptions) (*AnalyticsResults, error) {
if opts == nil {
opts = &AnalyticsQueryOptions{}
}
ctx := opts.Context
if ctx == nil {
ctx = context.Background()
}
var span opentracing.Span
if opts.ParentSpanContext == nil {
span = opentracing.GlobalTracer().StartSpan("ExecuteAnalyticsQuery",
opentracing.Tag{Key: "couchbase.service", Value: "cbas"})
} else {
span = opentracing.GlobalTracer().StartSpan("ExecuteAnalyticsQuery",
opentracing.Tag{Key: "couchbase.service", Value: "cbas"}, opentracing.ChildOf(opts.ParentSpanContext))
}
defer span.Finish()
provider, err := c.getHTTPProvider()
if err != nil {
return nil, err
}
return c.analyticsQuery(ctx, span.Context(), statement, opts, provider)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"AnalyticsQuery",
"(",
"statement",
"string",
",",
"opts",
"*",
"AnalyticsQueryOptions",
")",
"(",
"*",
"AnalyticsResults",
",",
"error",
")",
"{",
"if",
"opts",
"==",
"nil",
"{",
"opts",
"=",
"&",
"AnalyticsQueryOpti... | // AnalyticsQuery performs an analytics query and returns a list of rows or an error. | [
"AnalyticsQuery",
"performs",
"an",
"analytics",
"query",
"and",
"returns",
"a",
"list",
"of",
"rows",
"or",
"an",
"error",
"."
] | bca37798dd8f7c60a98041ed7089d39290c71718 | https://github.com/couchbase/gocb/blob/bca37798dd8f7c60a98041ed7089d39290c71718/cluster_analyticsquery.go#L319-L344 |
9,613 | apex/gateway | gateway.go | ListenAndServe | func ListenAndServe(addr string, h http.Handler) error {
if h == nil {
h = http.DefaultServeMux
}
lambda.Start(func(ctx context.Context, e events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
r, err := NewRequest(ctx, e)
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
w := NewResponse()
h.ServeHTTP(w, r)
return w.End(), nil
})
return nil
} | go | func ListenAndServe(addr string, h http.Handler) error {
if h == nil {
h = http.DefaultServeMux
}
lambda.Start(func(ctx context.Context, e events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
r, err := NewRequest(ctx, e)
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
w := NewResponse()
h.ServeHTTP(w, r)
return w.End(), nil
})
return nil
} | [
"func",
"ListenAndServe",
"(",
"addr",
"string",
",",
"h",
"http",
".",
"Handler",
")",
"error",
"{",
"if",
"h",
"==",
"nil",
"{",
"h",
"=",
"http",
".",
"DefaultServeMux",
"\n",
"}",
"\n\n",
"lambda",
".",
"Start",
"(",
"func",
"(",
"ctx",
"context"... | // ListenAndServe is a drop-in replacement for
// http.ListenAndServe for use within AWS Lambda.
//
// ListenAndServe always returns a non-nil error. | [
"ListenAndServe",
"is",
"a",
"drop",
"-",
"in",
"replacement",
"for",
"http",
".",
"ListenAndServe",
"for",
"use",
"within",
"AWS",
"Lambda",
".",
"ListenAndServe",
"always",
"returns",
"a",
"non",
"-",
"nil",
"error",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/gateway.go#L16-L33 |
9,614 | apex/gateway | context.go | newContext | func newContext(ctx context.Context, e events.APIGatewayProxyRequest) context.Context {
return context.WithValue(ctx, requestContextKey, e.RequestContext)
} | go | func newContext(ctx context.Context, e events.APIGatewayProxyRequest) context.Context {
return context.WithValue(ctx, requestContextKey, e.RequestContext)
} | [
"func",
"newContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"e",
"events",
".",
"APIGatewayProxyRequest",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"requestContextKey",
",",
"e",
".",
"RequestContext",
... | // newContext returns a new Context with specific api gateway proxy values. | [
"newContext",
"returns",
"a",
"new",
"Context",
"with",
"specific",
"api",
"gateway",
"proxy",
"values",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/context.go#L16-L18 |
9,615 | apex/gateway | context.go | RequestContext | func RequestContext(ctx context.Context) (events.APIGatewayProxyRequestContext, bool) {
c, ok := ctx.Value(requestContextKey).(events.APIGatewayProxyRequestContext)
return c, ok
} | go | func RequestContext(ctx context.Context) (events.APIGatewayProxyRequestContext, bool) {
c, ok := ctx.Value(requestContextKey).(events.APIGatewayProxyRequestContext)
return c, ok
} | [
"func",
"RequestContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"events",
".",
"APIGatewayProxyRequestContext",
",",
"bool",
")",
"{",
"c",
",",
"ok",
":=",
"ctx",
".",
"Value",
"(",
"requestContextKey",
")",
".",
"(",
"events",
".",
"APIGateway... | // RequestContext returns the APIGatewayProxyRequestContext value stored in ctx. | [
"RequestContext",
"returns",
"the",
"APIGatewayProxyRequestContext",
"value",
"stored",
"in",
"ctx",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/context.go#L21-L24 |
9,616 | apex/gateway | response.go | Header | func (w *ResponseWriter) Header() http.Header {
if w.header == nil {
w.header = make(http.Header)
}
return w.header
} | go | func (w *ResponseWriter) Header() http.Header {
if w.header == nil {
w.header = make(http.Header)
}
return w.header
} | [
"func",
"(",
"w",
"*",
"ResponseWriter",
")",
"Header",
"(",
")",
"http",
".",
"Header",
"{",
"if",
"w",
".",
"header",
"==",
"nil",
"{",
"w",
".",
"header",
"=",
"make",
"(",
"http",
".",
"Header",
")",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"... | // Header implementation. | [
"Header",
"implementation",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/response.go#L31-L37 |
9,617 | apex/gateway | response.go | Write | func (w *ResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
return w.buf.Write(b)
} | go | func (w *ResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
return w.buf.Write(b)
} | [
"func",
"(",
"w",
"*",
"ResponseWriter",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"!",
"w",
".",
"wroteHeader",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"\n\n",
... | // Write implementation. | [
"Write",
"implementation",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/response.go#L40-L46 |
9,618 | apex/gateway | response.go | WriteHeader | func (w *ResponseWriter) WriteHeader(status int) {
if w.wroteHeader {
return
}
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "text/plain; charset=utf8")
}
w.out.StatusCode = status
h := make(map[string]string)
for k, v := range w.Header() {
if len(v) > 0 {
h[k] = v[len(v)-1]
}
}
w.out.Headers = h
w.wroteHeader = true
} | go | func (w *ResponseWriter) WriteHeader(status int) {
if w.wroteHeader {
return
}
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "text/plain; charset=utf8")
}
w.out.StatusCode = status
h := make(map[string]string)
for k, v := range w.Header() {
if len(v) > 0 {
h[k] = v[len(v)-1]
}
}
w.out.Headers = h
w.wroteHeader = true
} | [
"func",
"(",
"w",
"*",
"ResponseWriter",
")",
"WriteHeader",
"(",
"status",
"int",
")",
"{",
"if",
"w",
".",
"wroteHeader",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"w",
".",
"Header",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
... | // WriteHeader implementation. | [
"WriteHeader",
"implementation",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/response.go#L49-L70 |
9,619 | apex/gateway | response.go | End | func (w *ResponseWriter) End() events.APIGatewayProxyResponse {
w.out.IsBase64Encoded = isBinary(w.header)
if w.out.IsBase64Encoded {
w.out.Body = base64.StdEncoding.EncodeToString(w.buf.Bytes())
} else {
w.out.Body = w.buf.String()
}
// notify end
w.closeNotifyCh <- true
return w.out
} | go | func (w *ResponseWriter) End() events.APIGatewayProxyResponse {
w.out.IsBase64Encoded = isBinary(w.header)
if w.out.IsBase64Encoded {
w.out.Body = base64.StdEncoding.EncodeToString(w.buf.Bytes())
} else {
w.out.Body = w.buf.String()
}
// notify end
w.closeNotifyCh <- true
return w.out
} | [
"func",
"(",
"w",
"*",
"ResponseWriter",
")",
"End",
"(",
")",
"events",
".",
"APIGatewayProxyResponse",
"{",
"w",
".",
"out",
".",
"IsBase64Encoded",
"=",
"isBinary",
"(",
"w",
".",
"header",
")",
"\n\n",
"if",
"w",
".",
"out",
".",
"IsBase64Encoded",
... | // End the request. | [
"End",
"the",
"request",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/response.go#L78-L91 |
9,620 | apex/gateway | response.go | isBinary | func isBinary(h http.Header) bool {
switch {
case !isTextMime(h.Get("Content-Type")):
return true
case h.Get("Content-Encoding") == "gzip":
return true
default:
return false
}
} | go | func isBinary(h http.Header) bool {
switch {
case !isTextMime(h.Get("Content-Type")):
return true
case h.Get("Content-Encoding") == "gzip":
return true
default:
return false
}
} | [
"func",
"isBinary",
"(",
"h",
"http",
".",
"Header",
")",
"bool",
"{",
"switch",
"{",
"case",
"!",
"isTextMime",
"(",
"h",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
":",
"return",
"true",
"\n",
"case",
"h",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
... | // isBinary returns true if the response reprensents binary. | [
"isBinary",
"returns",
"true",
"if",
"the",
"response",
"reprensents",
"binary",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/response.go#L94-L103 |
9,621 | apex/gateway | response.go | isTextMime | func isTextMime(kind string) bool {
mt, _, err := mime.ParseMediaType(kind)
if err != nil {
return false
}
if strings.HasPrefix(mt, "text/") {
return true
}
switch mt {
case "image/svg+xml":
return true
case "application/json":
return true
case "application/xml":
return true
default:
return false
}
} | go | func isTextMime(kind string) bool {
mt, _, err := mime.ParseMediaType(kind)
if err != nil {
return false
}
if strings.HasPrefix(mt, "text/") {
return true
}
switch mt {
case "image/svg+xml":
return true
case "application/json":
return true
case "application/xml":
return true
default:
return false
}
} | [
"func",
"isTextMime",
"(",
"kind",
"string",
")",
"bool",
"{",
"mt",
",",
"_",
",",
"err",
":=",
"mime",
".",
"ParseMediaType",
"(",
"kind",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"strings",
".",
"HasP... | // isTextMime returns true if the content type represents textual data. | [
"isTextMime",
"returns",
"true",
"if",
"the",
"content",
"type",
"represents",
"textual",
"data",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/response.go#L106-L126 |
9,622 | apex/gateway | request.go | NewRequest | func NewRequest(ctx context.Context, e events.APIGatewayProxyRequest) (*http.Request, error) {
// path
u, err := url.Parse(e.Path)
if err != nil {
return nil, errors.Wrap(err, "parsing path")
}
// querystring
q := u.Query()
for k, v := range e.QueryStringParameters {
q.Set(k, v)
}
u.RawQuery = q.Encode()
// base64 encoded body
body := e.Body
if e.IsBase64Encoded {
b, err := base64.StdEncoding.DecodeString(body)
if err != nil {
return nil, errors.Wrap(err, "decoding base64 body")
}
body = string(b)
}
// new request
req, err := http.NewRequest(e.HTTPMethod, u.String(), strings.NewReader(body))
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
// remote addr
req.RemoteAddr = e.RequestContext.Identity.SourceIP
// header fields
for k, v := range e.Headers {
req.Header.Set(k, v)
}
// content-length
if req.Header.Get("Content-Length") == "" && body != "" {
req.Header.Set("Content-Length", strconv.Itoa(len(body)))
}
// custom fields
req.Header.Set("X-Request-Id", e.RequestContext.RequestID)
req.Header.Set("X-Stage", e.RequestContext.Stage)
// custom context values
req = req.WithContext(newContext(ctx, e))
// xray support
if traceID := ctx.Value("x-amzn-trace-id"); traceID != nil {
req.Header.Set("X-Amzn-Trace-Id", fmt.Sprintf("%v", traceID))
}
// host
req.URL.Host = req.Header.Get("Host")
req.Host = req.URL.Host
return req, nil
} | go | func NewRequest(ctx context.Context, e events.APIGatewayProxyRequest) (*http.Request, error) {
// path
u, err := url.Parse(e.Path)
if err != nil {
return nil, errors.Wrap(err, "parsing path")
}
// querystring
q := u.Query()
for k, v := range e.QueryStringParameters {
q.Set(k, v)
}
u.RawQuery = q.Encode()
// base64 encoded body
body := e.Body
if e.IsBase64Encoded {
b, err := base64.StdEncoding.DecodeString(body)
if err != nil {
return nil, errors.Wrap(err, "decoding base64 body")
}
body = string(b)
}
// new request
req, err := http.NewRequest(e.HTTPMethod, u.String(), strings.NewReader(body))
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
// remote addr
req.RemoteAddr = e.RequestContext.Identity.SourceIP
// header fields
for k, v := range e.Headers {
req.Header.Set(k, v)
}
// content-length
if req.Header.Get("Content-Length") == "" && body != "" {
req.Header.Set("Content-Length", strconv.Itoa(len(body)))
}
// custom fields
req.Header.Set("X-Request-Id", e.RequestContext.RequestID)
req.Header.Set("X-Stage", e.RequestContext.Stage)
// custom context values
req = req.WithContext(newContext(ctx, e))
// xray support
if traceID := ctx.Value("x-amzn-trace-id"); traceID != nil {
req.Header.Set("X-Amzn-Trace-Id", fmt.Sprintf("%v", traceID))
}
// host
req.URL.Host = req.Header.Get("Host")
req.Host = req.URL.Host
return req, nil
} | [
"func",
"NewRequest",
"(",
"ctx",
"context",
".",
"Context",
",",
"e",
"events",
".",
"APIGatewayProxyRequest",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"// path",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"e",
".",
"Path... | // NewRequest returns a new http.Request from the given Lambda event. | [
"NewRequest",
"returns",
"a",
"new",
"http",
".",
"Request",
"from",
"the",
"given",
"Lambda",
"event",
"."
] | 21c9971861be4e8be9352e7a2540710b0c46610f | https://github.com/apex/gateway/blob/21c9971861be4e8be9352e7a2540710b0c46610f/request.go#L17-L77 |
9,623 | dsnet/compress | internal/prefix/writer.go | BitsWritten | func (pw *Writer) BitsWritten() int64 {
return 8*pw.Offset + 8*int64(pw.cntBuf) + int64(pw.numBits)
} | go | func (pw *Writer) BitsWritten() int64 {
return 8*pw.Offset + 8*int64(pw.cntBuf) + int64(pw.numBits)
} | [
"func",
"(",
"pw",
"*",
"Writer",
")",
"BitsWritten",
"(",
")",
"int64",
"{",
"return",
"8",
"*",
"pw",
".",
"Offset",
"+",
"8",
"*",
"int64",
"(",
"pw",
".",
"cntBuf",
")",
"+",
"int64",
"(",
"pw",
".",
"numBits",
")",
"\n",
"}"
] | // BitsWritten reports the total number of bits issued to any Write method. | [
"BitsWritten",
"reports",
"the",
"total",
"number",
"of",
"bits",
"issued",
"to",
"any",
"Write",
"method",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/writer.go#L38-L40 |
9,624 | dsnet/compress | internal/prefix/writer.go | WritePads | func (pw *Writer) WritePads(v uint) {
nb := -pw.numBits & 7
pw.bufBits |= uint64(v) << pw.numBits
pw.numBits += nb
} | go | func (pw *Writer) WritePads(v uint) {
nb := -pw.numBits & 7
pw.bufBits |= uint64(v) << pw.numBits
pw.numBits += nb
} | [
"func",
"(",
"pw",
"*",
"Writer",
")",
"WritePads",
"(",
"v",
"uint",
")",
"{",
"nb",
":=",
"-",
"pw",
".",
"numBits",
"&",
"7",
"\n",
"pw",
".",
"bufBits",
"|=",
"uint64",
"(",
"v",
")",
"<<",
"pw",
".",
"numBits",
"\n",
"pw",
".",
"numBits",
... | // WritePads writes 0-7 bits to the bit buffer to achieve byte-alignment. | [
"WritePads",
"writes",
"0",
"-",
"7",
"bits",
"to",
"the",
"bit",
"buffer",
"to",
"achieve",
"byte",
"-",
"alignment",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/writer.go#L43-L47 |
9,625 | dsnet/compress | internal/prefix/writer.go | Write | func (pw *Writer) Write(buf []byte) (cnt int, err error) {
if pw.numBits > 0 || pw.cntBuf > 0 {
if pw.numBits%8 != 0 {
return 0, errorf(errors.Invalid, "non-aligned bit buffer")
}
if _, err := pw.Flush(); err != nil {
return 0, err
}
}
cnt, err = pw.wr.Write(buf)
pw.Offset += int64(cnt)
return cnt, err
} | go | func (pw *Writer) Write(buf []byte) (cnt int, err error) {
if pw.numBits > 0 || pw.cntBuf > 0 {
if pw.numBits%8 != 0 {
return 0, errorf(errors.Invalid, "non-aligned bit buffer")
}
if _, err := pw.Flush(); err != nil {
return 0, err
}
}
cnt, err = pw.wr.Write(buf)
pw.Offset += int64(cnt)
return cnt, err
} | [
"func",
"(",
"pw",
"*",
"Writer",
")",
"Write",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"cnt",
"int",
",",
"err",
"error",
")",
"{",
"if",
"pw",
".",
"numBits",
">",
"0",
"||",
"pw",
".",
"cntBuf",
">",
"0",
"{",
"if",
"pw",
".",
"numBits",
... | // Write writes bytes from buf.
// The bit-ordering mode does not affect this method. | [
"Write",
"writes",
"bytes",
"from",
"buf",
".",
"The",
"bit",
"-",
"ordering",
"mode",
"does",
"not",
"affect",
"this",
"method",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/writer.go#L51-L63 |
9,626 | dsnet/compress | internal/prefix/writer.go | TryWriteBits | func (pw *Writer) TryWriteBits(v, nb uint) bool {
if 64-pw.numBits < nb {
return false
}
pw.bufBits |= uint64(v) << pw.numBits
pw.numBits += nb
return true
} | go | func (pw *Writer) TryWriteBits(v, nb uint) bool {
if 64-pw.numBits < nb {
return false
}
pw.bufBits |= uint64(v) << pw.numBits
pw.numBits += nb
return true
} | [
"func",
"(",
"pw",
"*",
"Writer",
")",
"TryWriteBits",
"(",
"v",
",",
"nb",
"uint",
")",
"bool",
"{",
"if",
"64",
"-",
"pw",
".",
"numBits",
"<",
"nb",
"{",
"return",
"false",
"\n",
"}",
"\n",
"pw",
".",
"bufBits",
"|=",
"uint64",
"(",
"v",
")"... | // TryWriteBits attempts to write nb bits using the contents of the bit buffer
// alone. It reports whether it succeeded.
//
// This method is designed to be inlined for performance reasons. | [
"TryWriteBits",
"attempts",
"to",
"write",
"nb",
"bits",
"using",
"the",
"contents",
"of",
"the",
"bit",
"buffer",
"alone",
".",
"It",
"reports",
"whether",
"it",
"succeeded",
".",
"This",
"method",
"is",
"designed",
"to",
"be",
"inlined",
"for",
"performanc... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/writer.go#L78-L85 |
9,627 | dsnet/compress | internal/prefix/writer.go | WriteBits | func (pw *Writer) WriteBits(v, nb uint) {
if _, err := pw.PushBits(); err != nil {
errors.Panic(err)
}
pw.bufBits |= uint64(v) << pw.numBits
pw.numBits += nb
} | go | func (pw *Writer) WriteBits(v, nb uint) {
if _, err := pw.PushBits(); err != nil {
errors.Panic(err)
}
pw.bufBits |= uint64(v) << pw.numBits
pw.numBits += nb
} | [
"func",
"(",
"pw",
"*",
"Writer",
")",
"WriteBits",
"(",
"v",
",",
"nb",
"uint",
")",
"{",
"if",
"_",
",",
"err",
":=",
"pw",
".",
"PushBits",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Panic",
"(",
"err",
")",
"\n",
"}",
"\n",
... | // WriteBits writes nb bits of v to the underlying writer. | [
"WriteBits",
"writes",
"nb",
"bits",
"of",
"v",
"to",
"the",
"underlying",
"writer",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/writer.go#L88-L94 |
9,628 | dsnet/compress | internal/prefix/writer.go | TryWriteSymbol | func (pw *Writer) TryWriteSymbol(sym uint, pe *Encoder) bool {
chunk := pe.chunks[uint32(sym)&pe.chunkMask]
nb := uint(chunk & countMask)
if 64-pw.numBits < nb {
return false
}
pw.bufBits |= uint64(chunk>>countBits) << pw.numBits
pw.numBits += nb
return true
} | go | func (pw *Writer) TryWriteSymbol(sym uint, pe *Encoder) bool {
chunk := pe.chunks[uint32(sym)&pe.chunkMask]
nb := uint(chunk & countMask)
if 64-pw.numBits < nb {
return false
}
pw.bufBits |= uint64(chunk>>countBits) << pw.numBits
pw.numBits += nb
return true
} | [
"func",
"(",
"pw",
"*",
"Writer",
")",
"TryWriteSymbol",
"(",
"sym",
"uint",
",",
"pe",
"*",
"Encoder",
")",
"bool",
"{",
"chunk",
":=",
"pe",
".",
"chunks",
"[",
"uint32",
"(",
"sym",
")",
"&",
"pe",
".",
"chunkMask",
"]",
"\n",
"nb",
":=",
"uin... | // TryWriteSymbol attempts to encode the next symbol using the contents of the
// bit buffer alone. It reports whether it succeeded.
//
// This method is designed to be inlined for performance reasons. | [
"TryWriteSymbol",
"attempts",
"to",
"encode",
"the",
"next",
"symbol",
"using",
"the",
"contents",
"of",
"the",
"bit",
"buffer",
"alone",
".",
"It",
"reports",
"whether",
"it",
"succeeded",
".",
"This",
"method",
"is",
"designed",
"to",
"be",
"inlined",
"for... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/writer.go#L100-L109 |
9,629 | dsnet/compress | internal/prefix/writer.go | WriteSymbol | func (pw *Writer) WriteSymbol(sym uint, pe *Encoder) {
if _, err := pw.PushBits(); err != nil {
errors.Panic(err)
}
chunk := pe.chunks[uint32(sym)&pe.chunkMask]
nb := uint(chunk & countMask)
pw.bufBits |= uint64(chunk>>countBits) << pw.numBits
pw.numBits += nb
} | go | func (pw *Writer) WriteSymbol(sym uint, pe *Encoder) {
if _, err := pw.PushBits(); err != nil {
errors.Panic(err)
}
chunk := pe.chunks[uint32(sym)&pe.chunkMask]
nb := uint(chunk & countMask)
pw.bufBits |= uint64(chunk>>countBits) << pw.numBits
pw.numBits += nb
} | [
"func",
"(",
"pw",
"*",
"Writer",
")",
"WriteSymbol",
"(",
"sym",
"uint",
",",
"pe",
"*",
"Encoder",
")",
"{",
"if",
"_",
",",
"err",
":=",
"pw",
".",
"PushBits",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Panic",
"(",
"err",
")",
... | // WriteSymbol writes the symbol using the provided prefix Encoder. | [
"WriteSymbol",
"writes",
"the",
"symbol",
"using",
"the",
"provided",
"prefix",
"Encoder",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/writer.go#L112-L120 |
9,630 | dsnet/compress | internal/prefix/writer.go | Flush | func (pw *Writer) Flush() (int64, error) {
if pw.numBits < 8 && pw.cntBuf == 0 {
return pw.Offset, nil
}
if _, err := pw.PushBits(); err != nil {
return pw.Offset, err
}
cnt, err := pw.wr.Write(pw.buf[:pw.cntBuf])
pw.cntBuf -= cnt
pw.Offset += int64(cnt)
return pw.Offset, err
} | go | func (pw *Writer) Flush() (int64, error) {
if pw.numBits < 8 && pw.cntBuf == 0 {
return pw.Offset, nil
}
if _, err := pw.PushBits(); err != nil {
return pw.Offset, err
}
cnt, err := pw.wr.Write(pw.buf[:pw.cntBuf])
pw.cntBuf -= cnt
pw.Offset += int64(cnt)
return pw.Offset, err
} | [
"func",
"(",
"pw",
"*",
"Writer",
")",
"Flush",
"(",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"pw",
".",
"numBits",
"<",
"8",
"&&",
"pw",
".",
"cntBuf",
"==",
"0",
"{",
"return",
"pw",
".",
"Offset",
",",
"nil",
"\n",
"}",
"\n",
"if",... | // Flush flushes all complete bytes from the bit buffer to the byte buffer, and
// then flushes all bytes in the byte buffer to the underlying writer.
// After this call, the bit Writer is will only withhold 7 bits at most. | [
"Flush",
"flushes",
"all",
"complete",
"bytes",
"from",
"the",
"bit",
"buffer",
"to",
"the",
"byte",
"buffer",
"and",
"then",
"flushes",
"all",
"bytes",
"in",
"the",
"byte",
"buffer",
"to",
"the",
"underlying",
"writer",
".",
"After",
"this",
"call",
"the"... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/writer.go#L125-L136 |
9,631 | dsnet/compress | internal/prefix/writer.go | PushBits | func (pw *Writer) PushBits() (uint, error) {
if pw.cntBuf >= len(pw.buf)-8 {
cnt, err := pw.wr.Write(pw.buf[:pw.cntBuf])
pw.cntBuf -= cnt
pw.Offset += int64(cnt)
if err != nil {
return 0, err
}
}
u := pw.bufBits
if pw.bigEndian {
// Swap all the bits within each byte.
u = (u&0xaaaaaaaaaaaaaaaa)>>1 | (u&0x5555555555555555)<<1
u = (u&0xcccccccccccccccc)>>2 | (u&0x3333333333333333)<<2
u = (u&0xf0f0f0f0f0f0f0f0)>>4 | (u&0x0f0f0f0f0f0f0f0f)<<4
}
// Starting with Go 1.7, the compiler should use a wide integer
// store here if the architecture supports it.
binary.LittleEndian.PutUint64(pw.buf[pw.cntBuf:], u)
nb := pw.numBits / 8 // Number of bytes to copy from bit buffer
pw.cntBuf += int(nb)
pw.bufBits >>= 8 * nb
pw.numBits -= 8 * nb
return 8 * nb, nil
} | go | func (pw *Writer) PushBits() (uint, error) {
if pw.cntBuf >= len(pw.buf)-8 {
cnt, err := pw.wr.Write(pw.buf[:pw.cntBuf])
pw.cntBuf -= cnt
pw.Offset += int64(cnt)
if err != nil {
return 0, err
}
}
u := pw.bufBits
if pw.bigEndian {
// Swap all the bits within each byte.
u = (u&0xaaaaaaaaaaaaaaaa)>>1 | (u&0x5555555555555555)<<1
u = (u&0xcccccccccccccccc)>>2 | (u&0x3333333333333333)<<2
u = (u&0xf0f0f0f0f0f0f0f0)>>4 | (u&0x0f0f0f0f0f0f0f0f)<<4
}
// Starting with Go 1.7, the compiler should use a wide integer
// store here if the architecture supports it.
binary.LittleEndian.PutUint64(pw.buf[pw.cntBuf:], u)
nb := pw.numBits / 8 // Number of bytes to copy from bit buffer
pw.cntBuf += int(nb)
pw.bufBits >>= 8 * nb
pw.numBits -= 8 * nb
return 8 * nb, nil
} | [
"func",
"(",
"pw",
"*",
"Writer",
")",
"PushBits",
"(",
")",
"(",
"uint",
",",
"error",
")",
"{",
"if",
"pw",
".",
"cntBuf",
">=",
"len",
"(",
"pw",
".",
"buf",
")",
"-",
"8",
"{",
"cnt",
",",
"err",
":=",
"pw",
".",
"wr",
".",
"Write",
"("... | // PushBits pushes as many bytes as possible from the bit buffer to the byte
// buffer, reporting the number of bits pushed. | [
"PushBits",
"pushes",
"as",
"many",
"bytes",
"as",
"possible",
"from",
"the",
"bit",
"buffer",
"to",
"the",
"byte",
"buffer",
"reporting",
"the",
"number",
"of",
"bits",
"pushed",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/writer.go#L140-L166 |
9,632 | dsnet/compress | internal/tool/bench/main.go | getFiles | func getFiles(paths []string, globs []string) []file {
var fs []file
for _, p := range paths {
for _, g := range globs {
ms, _ := filepath.Glob(filepath.Join(p, g))
for _, m := range ms {
r, err1 := filepath.Rel(p, m)
fi, err2 := os.Stat(m)
if err1 == nil && err2 == nil && !fi.IsDir() {
fs = append(fs, file{Abs: m, Rel: r})
}
}
}
}
return fs
} | go | func getFiles(paths []string, globs []string) []file {
var fs []file
for _, p := range paths {
for _, g := range globs {
ms, _ := filepath.Glob(filepath.Join(p, g))
for _, m := range ms {
r, err1 := filepath.Rel(p, m)
fi, err2 := os.Stat(m)
if err1 == nil && err2 == nil && !fi.IsDir() {
fs = append(fs, file{Abs: m, Rel: r})
}
}
}
}
return fs
} | [
"func",
"getFiles",
"(",
"paths",
"[",
"]",
"string",
",",
"globs",
"[",
"]",
"string",
")",
"[",
"]",
"file",
"{",
"var",
"fs",
"[",
"]",
"file",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"paths",
"{",
"for",
"_",
",",
"g",
":=",
"range",
"... | // getFiles returns a list of files found by applying the glob matching on
// all the specified paths. This function ignores any errors. | [
"getFiles",
"returns",
"a",
"list",
"of",
"files",
"found",
"by",
"applying",
"the",
"glob",
"matching",
"on",
"all",
"the",
"specified",
"paths",
".",
"This",
"function",
"ignores",
"any",
"errors",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/tool/bench/main.go#L93-L108 |
9,633 | dsnet/compress | brotli/common.go | errWrap | func errWrap(err error, replaceCode int) error {
if cerr, ok := err.(errors.Error); ok {
if errors.IsInvalid(cerr) {
cerr.Code = replaceCode
}
err = errorf(cerr.Code, "%s", cerr.Msg)
}
return err
} | go | func errWrap(err error, replaceCode int) error {
if cerr, ok := err.(errors.Error); ok {
if errors.IsInvalid(cerr) {
cerr.Code = replaceCode
}
err = errorf(cerr.Code, "%s", cerr.Msg)
}
return err
} | [
"func",
"errWrap",
"(",
"err",
"error",
",",
"replaceCode",
"int",
")",
"error",
"{",
"if",
"cerr",
",",
"ok",
":=",
"err",
".",
"(",
"errors",
".",
"Error",
")",
";",
"ok",
"{",
"if",
"errors",
".",
"IsInvalid",
"(",
"cerr",
")",
"{",
"cerr",
".... | // errWrap converts a lower-level errors.Error to be one from this package.
// The replaceCode passed in will be used to replace the code for any errors
// with the errors.Invalid code.
//
// For the Reader, set this to errors.Corrupted.
// For the Writer, set this to errors.Internal. | [
"errWrap",
"converts",
"a",
"lower",
"-",
"level",
"errors",
".",
"Error",
"to",
"be",
"one",
"from",
"this",
"package",
".",
"The",
"replaceCode",
"passed",
"in",
"will",
"be",
"used",
"to",
"replace",
"the",
"code",
"for",
"any",
"errors",
"with",
"the... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/common.go#L25-L33 |
9,634 | dsnet/compress | brotli/common.go | reverseUint32 | func reverseUint32(v uint32) (x uint32) {
x |= uint32(reverseLUT[byte(v>>0)]) << 24
x |= uint32(reverseLUT[byte(v>>8)]) << 16
x |= uint32(reverseLUT[byte(v>>16)]) << 8
x |= uint32(reverseLUT[byte(v>>24)]) << 0
return x
} | go | func reverseUint32(v uint32) (x uint32) {
x |= uint32(reverseLUT[byte(v>>0)]) << 24
x |= uint32(reverseLUT[byte(v>>8)]) << 16
x |= uint32(reverseLUT[byte(v>>16)]) << 8
x |= uint32(reverseLUT[byte(v>>24)]) << 0
return x
} | [
"func",
"reverseUint32",
"(",
"v",
"uint32",
")",
"(",
"x",
"uint32",
")",
"{",
"x",
"|=",
"uint32",
"(",
"reverseLUT",
"[",
"byte",
"(",
"v",
">>",
"0",
")",
"]",
")",
"<<",
"24",
"\n",
"x",
"|=",
"uint32",
"(",
"reverseLUT",
"[",
"byte",
"(",
... | // reverseUint32 reverses all bits of v. | [
"reverseUint32",
"reverses",
"all",
"bits",
"of",
"v",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/common.go#L76-L82 |
9,635 | dsnet/compress | xflate/internal/meta/reader.go | NewReader | func NewReader(rd io.Reader) *Reader {
mr := new(Reader)
mr.Reset(rd)
return mr
} | go | func NewReader(rd io.Reader) *Reader {
mr := new(Reader)
mr.Reset(rd)
return mr
} | [
"func",
"NewReader",
"(",
"rd",
"io",
".",
"Reader",
")",
"*",
"Reader",
"{",
"mr",
":=",
"new",
"(",
"Reader",
")",
"\n",
"mr",
".",
"Reset",
"(",
"rd",
")",
"\n",
"return",
"mr",
"\n",
"}"
] | // NewReader creates a new Reader reading from the given reader.
// If rd does not also implement compress.ByteReader or compress.BufferedReader,
// then the decoder may read more data than necessary from rd. | [
"NewReader",
"creates",
"a",
"new",
"Reader",
"reading",
"from",
"the",
"given",
"reader",
".",
"If",
"rd",
"does",
"not",
"also",
"implement",
"compress",
".",
"ByteReader",
"or",
"compress",
".",
"BufferedReader",
"then",
"the",
"decoder",
"may",
"read",
"... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/reader.go#L39-L43 |
9,636 | dsnet/compress | xflate/internal/meta/reader.go | Reset | func (mr *Reader) Reset(rd io.Reader) {
*mr = Reader{
br: mr.br,
bw: mr.bw,
bb: mr.bb,
}
if br, ok := rd.(*prefix.Reader); ok {
// Use input Reader directly as a prefix.Reader.
mr.rd = br
} else {
// Use pre-allocated prefix.Reader to wrap input Reader.
mr.rd = &mr.br
mr.rd.Init(rd, false)
}
return
} | go | func (mr *Reader) Reset(rd io.Reader) {
*mr = Reader{
br: mr.br,
bw: mr.bw,
bb: mr.bb,
}
if br, ok := rd.(*prefix.Reader); ok {
// Use input Reader directly as a prefix.Reader.
mr.rd = br
} else {
// Use pre-allocated prefix.Reader to wrap input Reader.
mr.rd = &mr.br
mr.rd.Init(rd, false)
}
return
} | [
"func",
"(",
"mr",
"*",
"Reader",
")",
"Reset",
"(",
"rd",
"io",
".",
"Reader",
")",
"{",
"*",
"mr",
"=",
"Reader",
"{",
"br",
":",
"mr",
".",
"br",
",",
"bw",
":",
"mr",
".",
"bw",
",",
"bb",
":",
"mr",
".",
"bb",
",",
"}",
"\n",
"if",
... | // Reset discards the Reader's state and makes it equivalent to the result
// of a call to NewReader, but reading from rd instead.
//
// This is used to reduce memory allocations. | [
"Reset",
"discards",
"the",
"Reader",
"s",
"state",
"and",
"makes",
"it",
"equivalent",
"to",
"the",
"result",
"of",
"a",
"call",
"to",
"NewReader",
"but",
"reading",
"from",
"rd",
"instead",
".",
"This",
"is",
"used",
"to",
"reduce",
"memory",
"allocation... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/reader.go#L49-L64 |
9,637 | dsnet/compress | xflate/internal/meta/reader.go | Read | func (mr *Reader) Read(buf []byte) (int, error) {
if mr.err != nil {
return 0, mr.err
}
var rdCnt int
for len(buf) > 0 {
if len(mr.buf) > 0 {
cpCnt := copy(buf, mr.buf)
mr.buf = mr.buf[cpCnt:]
rdCnt += cpCnt
break
}
if mr.final != FinalNil {
mr.FinalMode = mr.final
mr.err = io.EOF
break
}
mr.err = mr.decodeBlock()
if mr.err != nil {
break
}
}
mr.OutputOffset += int64(rdCnt)
return rdCnt, mr.err
} | go | func (mr *Reader) Read(buf []byte) (int, error) {
if mr.err != nil {
return 0, mr.err
}
var rdCnt int
for len(buf) > 0 {
if len(mr.buf) > 0 {
cpCnt := copy(buf, mr.buf)
mr.buf = mr.buf[cpCnt:]
rdCnt += cpCnt
break
}
if mr.final != FinalNil {
mr.FinalMode = mr.final
mr.err = io.EOF
break
}
mr.err = mr.decodeBlock()
if mr.err != nil {
break
}
}
mr.OutputOffset += int64(rdCnt)
return rdCnt, mr.err
} | [
"func",
"(",
"mr",
"*",
"Reader",
")",
"Read",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"mr",
".",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"mr",
".",
"err",
"\n",
"}",
"\n\n",
"var",
"rdCnt",
"int",
... | // Read reads the decoded meta data from the underlying io.Reader.
// This returns io.EOF either when a meta block with final bits set is found or
// when io.EOF is hit in the underlying reader. | [
"Read",
"reads",
"the",
"decoded",
"meta",
"data",
"from",
"the",
"underlying",
"io",
".",
"Reader",
".",
"This",
"returns",
"io",
".",
"EOF",
"either",
"when",
"a",
"meta",
"block",
"with",
"final",
"bits",
"set",
"is",
"found",
"or",
"when",
"io",
".... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/reader.go#L69-L97 |
9,638 | dsnet/compress | xflate/internal/meta/reader.go | Close | func (mr *Reader) Close() error {
if mr.err == errClosed {
return nil
}
if mr.err != nil && mr.err != io.EOF {
return mr.err
}
mr.FinalMode = mr.final
mr.err = errClosed
mr.rd = nil // Release reference to underlying Reader
return nil
} | go | func (mr *Reader) Close() error {
if mr.err == errClosed {
return nil
}
if mr.err != nil && mr.err != io.EOF {
return mr.err
}
mr.FinalMode = mr.final
mr.err = errClosed
mr.rd = nil // Release reference to underlying Reader
return nil
} | [
"func",
"(",
"mr",
"*",
"Reader",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"mr",
".",
"err",
"==",
"errClosed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"mr",
".",
"err",
"!=",
"nil",
"&&",
"mr",
".",
"err",
"!=",
"io",
".",
"EOF",
"{"... | // Close ends the meta stream.
// The FinalMode encountered becomes valid after calling Close. | [
"Close",
"ends",
"the",
"meta",
"stream",
".",
"The",
"FinalMode",
"encountered",
"becomes",
"valid",
"after",
"calling",
"Close",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/reader.go#L101-L113 |
9,639 | dsnet/compress | brotli/context.go | initContextLUTs | func initContextLUTs() {
for i := 0; i < 256; i++ {
for m := 0; m < numContextModes; m++ {
base := m << 8
// Operations performed here are specified in RFC section 7.1.
switch m {
case contextLSB6:
contextP1LUT[base+i] = byte(i) & 0x3f
contextP2LUT[base+i] = 0
case contextMSB6:
contextP1LUT[base+i] = byte(i) >> 2
contextP2LUT[base+i] = 0
case contextUTF8:
contextP1LUT[base+i] = contextLUT0[byte(i)]
contextP2LUT[base+i] = contextLUT1[byte(i)]
case contextSigned:
contextP1LUT[base+i] = contextLUT2[byte(i)] << 3
contextP2LUT[base+i] = contextLUT2[byte(i)]
default:
panic("unknown context mode")
}
}
}
} | go | func initContextLUTs() {
for i := 0; i < 256; i++ {
for m := 0; m < numContextModes; m++ {
base := m << 8
// Operations performed here are specified in RFC section 7.1.
switch m {
case contextLSB6:
contextP1LUT[base+i] = byte(i) & 0x3f
contextP2LUT[base+i] = 0
case contextMSB6:
contextP1LUT[base+i] = byte(i) >> 2
contextP2LUT[base+i] = 0
case contextUTF8:
contextP1LUT[base+i] = contextLUT0[byte(i)]
contextP2LUT[base+i] = contextLUT1[byte(i)]
case contextSigned:
contextP1LUT[base+i] = contextLUT2[byte(i)] << 3
contextP2LUT[base+i] = contextLUT2[byte(i)]
default:
panic("unknown context mode")
}
}
}
} | [
"func",
"initContextLUTs",
"(",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"256",
";",
"i",
"++",
"{",
"for",
"m",
":=",
"0",
";",
"m",
"<",
"numContextModes",
";",
"m",
"++",
"{",
"base",
":=",
"m",
"<<",
"8",
"\n\n",
"// Operations perform... | // initContextLUTs computes LUTs so that context ID computation can be
// efficiently without any branches. | [
"initContextLUTs",
"computes",
"LUTs",
"so",
"that",
"context",
"ID",
"computation",
"can",
"be",
"efficiently",
"without",
"any",
"branches",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/context.go#L91-L115 |
9,640 | dsnet/compress | brotli/context.go | getLitContextID | func getLitContextID(p1, p2 byte, mode uint8) uint8 {
base := uint(mode) << 8
return contextP1LUT[base+uint(p1)] | contextP2LUT[base+uint(p2)]
} | go | func getLitContextID(p1, p2 byte, mode uint8) uint8 {
base := uint(mode) << 8
return contextP1LUT[base+uint(p1)] | contextP2LUT[base+uint(p2)]
} | [
"func",
"getLitContextID",
"(",
"p1",
",",
"p2",
"byte",
",",
"mode",
"uint8",
")",
"uint8",
"{",
"base",
":=",
"uint",
"(",
"mode",
")",
"<<",
"8",
"\n",
"return",
"contextP1LUT",
"[",
"base",
"+",
"uint",
"(",
"p1",
")",
"]",
"|",
"contextP2LUT",
... | // getLitContextID computes the context ID for literals from RFC section 7.1.
// Bytes p1 and p2 are the last and second-to-last byte, respectively. | [
"getLitContextID",
"computes",
"the",
"context",
"ID",
"for",
"literals",
"from",
"RFC",
"section",
"7",
".",
"1",
".",
"Bytes",
"p1",
"and",
"p2",
"are",
"the",
"last",
"and",
"second",
"-",
"to",
"-",
"last",
"byte",
"respectively",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/context.go#L119-L122 |
9,641 | dsnet/compress | brotli/dict_decoder.go | HistSize | func (dd *dictDecoder) HistSize() int {
if dd.full {
return dd.size
}
return dd.wrPos
} | go | func (dd *dictDecoder) HistSize() int {
if dd.full {
return dd.size
}
return dd.wrPos
} | [
"func",
"(",
"dd",
"*",
"dictDecoder",
")",
"HistSize",
"(",
")",
"int",
"{",
"if",
"dd",
".",
"full",
"{",
"return",
"dd",
".",
"size",
"\n",
"}",
"\n",
"return",
"dd",
".",
"wrPos",
"\n",
"}"
] | // HistSize reports the total amount of historical data in the dictionary. | [
"HistSize",
"reports",
"the",
"total",
"amount",
"of",
"historical",
"data",
"in",
"the",
"dictionary",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/dict_decoder.go#L49-L54 |
9,642 | dsnet/compress | brotli/dict_decoder.go | ReadFlush | func (dd *dictDecoder) ReadFlush() []byte {
toRead := dd.hist[dd.rdPos:dd.wrPos]
dd.rdPos = dd.wrPos
if dd.wrPos == len(dd.hist) {
if len(dd.hist) == dd.size {
dd.wrPos, dd.rdPos = 0, 0
dd.full = true
} else {
// Allocate a larger history buffer.
size := cap(dd.hist) * growFactor
if size > dd.size {
size = dd.size
}
hist := make([]byte, size)
copy(hist, dd.hist)
dd.hist = hist
}
}
return toRead
} | go | func (dd *dictDecoder) ReadFlush() []byte {
toRead := dd.hist[dd.rdPos:dd.wrPos]
dd.rdPos = dd.wrPos
if dd.wrPos == len(dd.hist) {
if len(dd.hist) == dd.size {
dd.wrPos, dd.rdPos = 0, 0
dd.full = true
} else {
// Allocate a larger history buffer.
size := cap(dd.hist) * growFactor
if size > dd.size {
size = dd.size
}
hist := make([]byte, size)
copy(hist, dd.hist)
dd.hist = hist
}
}
return toRead
} | [
"func",
"(",
"dd",
"*",
"dictDecoder",
")",
"ReadFlush",
"(",
")",
"[",
"]",
"byte",
"{",
"toRead",
":=",
"dd",
".",
"hist",
"[",
"dd",
".",
"rdPos",
":",
"dd",
".",
"wrPos",
"]",
"\n",
"dd",
".",
"rdPos",
"=",
"dd",
".",
"wrPos",
"\n",
"if",
... | // ReadFlush returns a slice of the historical buffer that is ready to be
// emitted to the user. A call to ReadFlush is only valid after all of the data
// from a previous call to ReadFlush has been consumed. | [
"ReadFlush",
"returns",
"a",
"slice",
"of",
"the",
"historical",
"buffer",
"that",
"is",
"ready",
"to",
"be",
"emitted",
"to",
"the",
"user",
".",
"A",
"call",
"to",
"ReadFlush",
"is",
"only",
"valid",
"after",
"all",
"of",
"the",
"data",
"from",
"a",
... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/dict_decoder.go#L105-L124 |
9,643 | dsnet/compress | brotli/dict_decoder.go | LastBytes | func (dd *dictDecoder) LastBytes() (p1, p2 byte) {
if dd.wrPos > 1 {
return dd.hist[dd.wrPos-1], dd.hist[dd.wrPos-2]
} else if dd.wrPos > 0 {
return dd.hist[dd.wrPos-1], dd.hist[len(dd.hist)-1]
} else {
return dd.hist[len(dd.hist)-1], dd.hist[len(dd.hist)-2]
}
} | go | func (dd *dictDecoder) LastBytes() (p1, p2 byte) {
if dd.wrPos > 1 {
return dd.hist[dd.wrPos-1], dd.hist[dd.wrPos-2]
} else if dd.wrPos > 0 {
return dd.hist[dd.wrPos-1], dd.hist[len(dd.hist)-1]
} else {
return dd.hist[len(dd.hist)-1], dd.hist[len(dd.hist)-2]
}
} | [
"func",
"(",
"dd",
"*",
"dictDecoder",
")",
"LastBytes",
"(",
")",
"(",
"p1",
",",
"p2",
"byte",
")",
"{",
"if",
"dd",
".",
"wrPos",
">",
"1",
"{",
"return",
"dd",
".",
"hist",
"[",
"dd",
".",
"wrPos",
"-",
"1",
"]",
",",
"dd",
".",
"hist",
... | // LastBytes reports the last 2 bytes in the dictionary. If they do not exist,
// then zero values are returned. | [
"LastBytes",
"reports",
"the",
"last",
"2",
"bytes",
"in",
"the",
"dictionary",
".",
"If",
"they",
"do",
"not",
"exist",
"then",
"zero",
"values",
"are",
"returned",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/dict_decoder.go#L128-L136 |
9,644 | dsnet/compress | internal/tool/bench/config.go | setDefaults | func setDefaults() {
formats = defaultFormats()
tests = defaultTests()
codecs = defaultCodecs()
paths = defaultPaths()
globs = []string{"*.txt", "*.bin"}
levels = []int{1, 6, 9}
sizes = []int{1e4, 1e5, 1e6}
} | go | func setDefaults() {
formats = defaultFormats()
tests = defaultTests()
codecs = defaultCodecs()
paths = defaultPaths()
globs = []string{"*.txt", "*.bin"}
levels = []int{1, 6, 9}
sizes = []int{1e4, 1e5, 1e6}
} | [
"func",
"setDefaults",
"(",
")",
"{",
"formats",
"=",
"defaultFormats",
"(",
")",
"\n",
"tests",
"=",
"defaultTests",
"(",
")",
"\n",
"codecs",
"=",
"defaultCodecs",
"(",
")",
"\n",
"paths",
"=",
"defaultPaths",
"(",
")",
"\n",
"globs",
"=",
"[",
"]",
... | // setDefaults configures the top-level parameters with default values.
// This function method must be called after all init functions have executed
// since they register the various codecs. | [
"setDefaults",
"configures",
"the",
"top",
"-",
"level",
"parameters",
"with",
"default",
"values",
".",
"This",
"function",
"method",
"must",
"be",
"called",
"after",
"all",
"init",
"functions",
"have",
"executed",
"since",
"they",
"register",
"the",
"various",... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/tool/bench/config.go#L120-L128 |
9,645 | dsnet/compress | internal/tool/bench/config.go | intName | func intName(n int64) string {
switch n {
case 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12:
s := fmt.Sprintf("%e", float64(n))
re := regexp.MustCompile("\\.0*e\\+0*")
return re.ReplaceAllString(s, "e")
default:
s := unitconv.FormatPrefix(float64(n), unitconv.Base1024, 2)
return strings.Replace(s, ".00", "", -1)
}
} | go | func intName(n int64) string {
switch n {
case 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12:
s := fmt.Sprintf("%e", float64(n))
re := regexp.MustCompile("\\.0*e\\+0*")
return re.ReplaceAllString(s, "e")
default:
s := unitconv.FormatPrefix(float64(n), unitconv.Base1024, 2)
return strings.Replace(s, ".00", "", -1)
}
} | [
"func",
"intName",
"(",
"n",
"int64",
")",
"string",
"{",
"switch",
"n",
"{",
"case",
"1e3",
",",
"1e4",
",",
"1e5",
",",
"1e6",
",",
"1e7",
",",
"1e8",
",",
"1e9",
",",
"1e10",
",",
"1e11",
",",
"1e12",
":",
"s",
":=",
"fmt",
".",
"Sprintf",
... | // intName returns a shorter representation of the input integer.
// It uses scientific notation for exact powers of 10.
// It uses SI suffixes for powers of 1024.
// If the number is small enough, it will be printed as is. | [
"intName",
"returns",
"a",
"shorter",
"representation",
"of",
"the",
"input",
"integer",
".",
"It",
"uses",
"scientific",
"notation",
"for",
"exact",
"powers",
"of",
"10",
".",
"It",
"uses",
"SI",
"suffixes",
"for",
"powers",
"of",
"1024",
".",
"If",
"the"... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/tool/bench/config.go#L275-L285 |
9,646 | dsnet/compress | internal/prefix/reader.go | BitsRead | func (pr *Reader) BitsRead() int64 {
offset := 8*pr.Offset - int64(pr.numBits)
if pr.bufRd != nil {
discardBits := pr.discardBits + int(pr.fedBits-pr.numBits)
offset = 8*pr.Offset + int64(discardBits)
}
return offset
} | go | func (pr *Reader) BitsRead() int64 {
offset := 8*pr.Offset - int64(pr.numBits)
if pr.bufRd != nil {
discardBits := pr.discardBits + int(pr.fedBits-pr.numBits)
offset = 8*pr.Offset + int64(discardBits)
}
return offset
} | [
"func",
"(",
"pr",
"*",
"Reader",
")",
"BitsRead",
"(",
")",
"int64",
"{",
"offset",
":=",
"8",
"*",
"pr",
".",
"Offset",
"-",
"int64",
"(",
"pr",
".",
"numBits",
")",
"\n",
"if",
"pr",
".",
"bufRd",
"!=",
"nil",
"{",
"discardBits",
":=",
"pr",
... | // BitsRead reports the total number of bits emitted from any Read method. | [
"BitsRead",
"reports",
"the",
"total",
"number",
"of",
"bits",
"emitted",
"from",
"any",
"Read",
"method",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/reader.go#L97-L104 |
9,647 | dsnet/compress | internal/prefix/reader.go | Read | func (pr *Reader) Read(buf []byte) (cnt int, err error) {
if pr.numBits > 0 {
if pr.numBits%8 != 0 {
return 0, errorf(errors.Invalid, "non-aligned bit buffer")
}
for cnt = 0; len(buf) > cnt && pr.numBits > 0; cnt++ {
if pr.bigEndian {
buf[cnt] = internal.ReverseLUT[byte(pr.bufBits)]
} else {
buf[cnt] = byte(pr.bufBits)
}
pr.bufBits >>= 8
pr.numBits -= 8
}
return cnt, nil
}
if _, err := pr.Flush(); err != nil {
return 0, err
}
cnt, err = pr.rd.Read(buf)
pr.Offset += int64(cnt)
return cnt, err
} | go | func (pr *Reader) Read(buf []byte) (cnt int, err error) {
if pr.numBits > 0 {
if pr.numBits%8 != 0 {
return 0, errorf(errors.Invalid, "non-aligned bit buffer")
}
for cnt = 0; len(buf) > cnt && pr.numBits > 0; cnt++ {
if pr.bigEndian {
buf[cnt] = internal.ReverseLUT[byte(pr.bufBits)]
} else {
buf[cnt] = byte(pr.bufBits)
}
pr.bufBits >>= 8
pr.numBits -= 8
}
return cnt, nil
}
if _, err := pr.Flush(); err != nil {
return 0, err
}
cnt, err = pr.rd.Read(buf)
pr.Offset += int64(cnt)
return cnt, err
} | [
"func",
"(",
"pr",
"*",
"Reader",
")",
"Read",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"cnt",
"int",
",",
"err",
"error",
")",
"{",
"if",
"pr",
".",
"numBits",
">",
"0",
"{",
"if",
"pr",
".",
"numBits",
"%",
"8",
"!=",
"0",
"{",
"return",
"... | // Read reads bytes into buf.
// The bit-ordering mode does not affect this method. | [
"Read",
"reads",
"bytes",
"into",
"buf",
".",
"The",
"bit",
"-",
"ordering",
"mode",
"does",
"not",
"affect",
"this",
"method",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/reader.go#L123-L145 |
9,648 | dsnet/compress | internal/prefix/reader.go | ReadOffset | func (pr *Reader) ReadOffset(pd *Decoder, rcs RangeCodes) uint {
rc := rcs[pr.ReadSymbol(pd)]
return uint(rc.Base) + pr.ReadBits(uint(rc.Len))
} | go | func (pr *Reader) ReadOffset(pd *Decoder, rcs RangeCodes) uint {
rc := rcs[pr.ReadSymbol(pd)]
return uint(rc.Base) + pr.ReadBits(uint(rc.Len))
} | [
"func",
"(",
"pr",
"*",
"Reader",
")",
"ReadOffset",
"(",
"pd",
"*",
"Decoder",
",",
"rcs",
"RangeCodes",
")",
"uint",
"{",
"rc",
":=",
"rcs",
"[",
"pr",
".",
"ReadSymbol",
"(",
"pd",
")",
"]",
"\n",
"return",
"uint",
"(",
"rc",
".",
"Base",
")",... | // ReadOffset reads an offset value using the provided RangeCodes indexed by
// the symbol read. | [
"ReadOffset",
"reads",
"an",
"offset",
"value",
"using",
"the",
"provided",
"RangeCodes",
"indexed",
"by",
"the",
"symbol",
"read",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/reader.go#L149-L152 |
9,649 | dsnet/compress | internal/prefix/reader.go | ReadBits | func (pr *Reader) ReadBits(nb uint) uint {
if err := pr.PullBits(nb); err != nil {
errors.Panic(err)
}
val := uint(pr.bufBits & uint64(1<<nb-1))
pr.bufBits >>= nb
pr.numBits -= nb
return val
} | go | func (pr *Reader) ReadBits(nb uint) uint {
if err := pr.PullBits(nb); err != nil {
errors.Panic(err)
}
val := uint(pr.bufBits & uint64(1<<nb-1))
pr.bufBits >>= nb
pr.numBits -= nb
return val
} | [
"func",
"(",
"pr",
"*",
"Reader",
")",
"ReadBits",
"(",
"nb",
"uint",
")",
"uint",
"{",
"if",
"err",
":=",
"pr",
".",
"PullBits",
"(",
"nb",
")",
";",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"val",
"... | // ReadBits reads nb bits in from the underlying reader. | [
"ReadBits",
"reads",
"nb",
"bits",
"in",
"from",
"the",
"underlying",
"reader",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/reader.go#L169-L177 |
9,650 | dsnet/compress | internal/prefix/reader.go | ReadSymbol | func (pr *Reader) ReadSymbol(pd *Decoder) uint {
if len(pd.chunks) == 0 {
panicf(errors.Invalid, "decode with empty prefix tree")
}
nb := uint(pd.MinBits)
for {
if err := pr.PullBits(nb); err != nil {
errors.Panic(err)
}
chunk := pd.chunks[uint32(pr.bufBits)&pd.chunkMask]
nb = uint(chunk & countMask)
if nb > uint(pd.chunkBits) {
linkIdx := chunk >> countBits
chunk = pd.links[linkIdx][uint32(pr.bufBits>>pd.chunkBits)&pd.linkMask]
nb = uint(chunk & countMask)
}
if nb <= pr.numBits {
pr.bufBits >>= nb
pr.numBits -= nb
return uint(chunk >> countBits)
}
}
} | go | func (pr *Reader) ReadSymbol(pd *Decoder) uint {
if len(pd.chunks) == 0 {
panicf(errors.Invalid, "decode with empty prefix tree")
}
nb := uint(pd.MinBits)
for {
if err := pr.PullBits(nb); err != nil {
errors.Panic(err)
}
chunk := pd.chunks[uint32(pr.bufBits)&pd.chunkMask]
nb = uint(chunk & countMask)
if nb > uint(pd.chunkBits) {
linkIdx := chunk >> countBits
chunk = pd.links[linkIdx][uint32(pr.bufBits>>pd.chunkBits)&pd.linkMask]
nb = uint(chunk & countMask)
}
if nb <= pr.numBits {
pr.bufBits >>= nb
pr.numBits -= nb
return uint(chunk >> countBits)
}
}
} | [
"func",
"(",
"pr",
"*",
"Reader",
")",
"ReadSymbol",
"(",
"pd",
"*",
"Decoder",
")",
"uint",
"{",
"if",
"len",
"(",
"pd",
".",
"chunks",
")",
"==",
"0",
"{",
"panicf",
"(",
"errors",
".",
"Invalid",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"nb"... | // ReadSymbol reads the next symbol using the provided prefix Decoder. | [
"ReadSymbol",
"reads",
"the",
"next",
"symbol",
"using",
"the",
"provided",
"prefix",
"Decoder",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/reader.go#L198-L221 |
9,651 | dsnet/compress | internal/prefix/reader.go | Flush | func (pr *Reader) Flush() (int64, error) {
if pr.bufRd == nil {
return pr.Offset, nil
}
// Update the number of total bits to discard.
pr.discardBits += int(pr.fedBits - pr.numBits)
pr.fedBits = pr.numBits
// Discard some bytes to update read offset.
var err error
nd := (pr.discardBits + 7) / 8 // Round up to nearest byte
nd, err = pr.bufRd.Discard(nd)
pr.discardBits -= nd * 8 // -7..0
pr.Offset += int64(nd)
// These are invalid after Discard.
pr.bufPeek = nil
return pr.Offset, err
} | go | func (pr *Reader) Flush() (int64, error) {
if pr.bufRd == nil {
return pr.Offset, nil
}
// Update the number of total bits to discard.
pr.discardBits += int(pr.fedBits - pr.numBits)
pr.fedBits = pr.numBits
// Discard some bytes to update read offset.
var err error
nd := (pr.discardBits + 7) / 8 // Round up to nearest byte
nd, err = pr.bufRd.Discard(nd)
pr.discardBits -= nd * 8 // -7..0
pr.Offset += int64(nd)
// These are invalid after Discard.
pr.bufPeek = nil
return pr.Offset, err
} | [
"func",
"(",
"pr",
"*",
"Reader",
")",
"Flush",
"(",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"pr",
".",
"bufRd",
"==",
"nil",
"{",
"return",
"pr",
".",
"Offset",
",",
"nil",
"\n",
"}",
"\n\n",
"// Update the number of total bits to discard.",
... | // Flush updates the read offset of the underlying ByteReader.
// If reader is a compress.BufferedReader, then this calls Discard to update
// the read offset. | [
"Flush",
"updates",
"the",
"read",
"offset",
"of",
"the",
"underlying",
"ByteReader",
".",
"If",
"reader",
"is",
"a",
"compress",
".",
"BufferedReader",
"then",
"this",
"calls",
"Discard",
"to",
"update",
"the",
"read",
"offset",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/reader.go#L226-L245 |
9,652 | dsnet/compress | brotli/transform.go | transformUppercase | func transformUppercase(word []byte, once bool) {
for i := 0; i < len(word); {
c := word[i]
if c < 192 {
if c >= 97 && c <= 122 {
word[i] ^= 32
}
i += 1
} else if c < 224 {
if i+1 < len(word) {
word[i+1] ^= 32
}
i += 2
} else {
if i+2 < len(word) {
word[i+2] ^= 5
}
i += 3
}
if once {
return
}
}
} | go | func transformUppercase(word []byte, once bool) {
for i := 0; i < len(word); {
c := word[i]
if c < 192 {
if c >= 97 && c <= 122 {
word[i] ^= 32
}
i += 1
} else if c < 224 {
if i+1 < len(word) {
word[i+1] ^= 32
}
i += 2
} else {
if i+2 < len(word) {
word[i+2] ^= 5
}
i += 3
}
if once {
return
}
}
} | [
"func",
"transformUppercase",
"(",
"word",
"[",
"]",
"byte",
",",
"once",
"bool",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"word",
")",
";",
"{",
"c",
":=",
"word",
"[",
"i",
"]",
"\n",
"if",
"c",
"<",
"192",
"{",
"if",
"... | // transformUppercase transform the word to be in uppercase using the algorithm
// presented in RFC section 8. If once is set, then loop only executes once. | [
"transformUppercase",
"transform",
"the",
"word",
"to",
"be",
"in",
"uppercase",
"using",
"the",
"algorithm",
"presented",
"in",
"RFC",
"section",
"8",
".",
"If",
"once",
"is",
"set",
"then",
"loop",
"only",
"executes",
"once",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/transform.go#L204-L227 |
9,653 | dsnet/compress | internal/tool/bench/benchmarks.go | BenchmarkEncoder | func BenchmarkEncoder(input []byte, enc Encoder, lvl int) testing.BenchmarkResult {
return testing.Benchmark(func(b *testing.B) {
b.StopTimer()
if enc == nil {
b.Fatalf("unexpected error: nil Encoder")
}
runtime.GC()
b.StartTimer()
for i := 0; i < b.N; i++ {
wr := enc(ioutil.Discard, lvl)
_, err := io.Copy(wr, bytes.NewBuffer(input))
if err := wr.Close(); err != nil {
b.Fatalf("unexpected error: %v", err)
}
if err != nil {
b.Fatalf("unexpected error: %v", err)
}
b.SetBytes(int64(len(input)))
}
})
} | go | func BenchmarkEncoder(input []byte, enc Encoder, lvl int) testing.BenchmarkResult {
return testing.Benchmark(func(b *testing.B) {
b.StopTimer()
if enc == nil {
b.Fatalf("unexpected error: nil Encoder")
}
runtime.GC()
b.StartTimer()
for i := 0; i < b.N; i++ {
wr := enc(ioutil.Discard, lvl)
_, err := io.Copy(wr, bytes.NewBuffer(input))
if err := wr.Close(); err != nil {
b.Fatalf("unexpected error: %v", err)
}
if err != nil {
b.Fatalf("unexpected error: %v", err)
}
b.SetBytes(int64(len(input)))
}
})
} | [
"func",
"BenchmarkEncoder",
"(",
"input",
"[",
"]",
"byte",
",",
"enc",
"Encoder",
",",
"lvl",
"int",
")",
"testing",
".",
"BenchmarkResult",
"{",
"return",
"testing",
".",
"Benchmark",
"(",
"func",
"(",
"b",
"*",
"testing",
".",
"B",
")",
"{",
"b",
... | // BenchmarkEncoder benchmarks a single encoder on the given input data using
// the selected compression level and reports the result. | [
"BenchmarkEncoder",
"benchmarks",
"a",
"single",
"encoder",
"on",
"the",
"given",
"input",
"data",
"using",
"the",
"selected",
"compression",
"level",
"and",
"reports",
"the",
"result",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/tool/bench/benchmarks.go#L28-L48 |
9,654 | dsnet/compress | internal/tool/bench/benchmarks.go | BenchmarkDecoder | func BenchmarkDecoder(input []byte, dec Decoder) testing.BenchmarkResult {
return testing.Benchmark(func(b *testing.B) {
b.StopTimer()
if dec == nil {
b.Fatalf("unexpected error: nil Decoder")
}
runtime.GC()
b.StartTimer()
for i := 0; i < b.N; i++ {
rd := dec(bufio.NewReader(bytes.NewBuffer(input)))
cnt, err := io.Copy(ioutil.Discard, rd)
if err := rd.Close(); err != nil {
b.Fatalf("unexpected error: %v", err)
}
if err != nil {
b.Fatalf("unexpected error: %v", err)
}
b.SetBytes(cnt)
}
})
} | go | func BenchmarkDecoder(input []byte, dec Decoder) testing.BenchmarkResult {
return testing.Benchmark(func(b *testing.B) {
b.StopTimer()
if dec == nil {
b.Fatalf("unexpected error: nil Decoder")
}
runtime.GC()
b.StartTimer()
for i := 0; i < b.N; i++ {
rd := dec(bufio.NewReader(bytes.NewBuffer(input)))
cnt, err := io.Copy(ioutil.Discard, rd)
if err := rd.Close(); err != nil {
b.Fatalf("unexpected error: %v", err)
}
if err != nil {
b.Fatalf("unexpected error: %v", err)
}
b.SetBytes(cnt)
}
})
} | [
"func",
"BenchmarkDecoder",
"(",
"input",
"[",
"]",
"byte",
",",
"dec",
"Decoder",
")",
"testing",
".",
"BenchmarkResult",
"{",
"return",
"testing",
".",
"Benchmark",
"(",
"func",
"(",
"b",
"*",
"testing",
".",
"B",
")",
"{",
"b",
".",
"StopTimer",
"("... | // BenchmarkDecoder benchmarks a single decoder on the given pre-compressed
// input data and reports the result. | [
"BenchmarkDecoder",
"benchmarks",
"a",
"single",
"decoder",
"on",
"the",
"given",
"pre",
"-",
"compressed",
"input",
"data",
"and",
"reports",
"the",
"result",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/tool/bench/benchmarks.go#L71-L91 |
9,655 | dsnet/compress | internal/prefix/encoder.go | Init | func (pe *Encoder) Init(codes PrefixCodes) {
// Handle special case trees.
if len(codes) <= 1 {
switch {
case len(codes) == 0: // Empty tree (should error if used later)
*pe = Encoder{chunks: pe.chunks[:0], NumSyms: 0}
case len(codes) == 1 && codes[0].Len == 0: // Single code tree (bit-length of zero)
pe.chunks = append(pe.chunks[:0], codes[0].Val<<countBits|0)
*pe = Encoder{chunks: pe.chunks[:1], NumSyms: 1}
default:
panic("invalid codes")
}
return
}
if internal.Debug && !sort.IsSorted(prefixCodesBySymbol(codes)) {
panic("input codes is not sorted")
}
if internal.Debug && !(codes.checkLengths() && codes.checkPrefixes()) {
panic("detected incomplete or overlapping codes")
}
// Enough chunks to contain all the symbols.
numChunks := 1
for n := len(codes) - 1; n > 0; n >>= 1 {
numChunks <<= 1
}
pe.NumSyms = uint32(len(codes))
retry:
// Allocate and reset chunks.
pe.chunks = allocUint32s(pe.chunks, numChunks)
pe.chunkMask = uint32(numChunks - 1)
for i := range pe.chunks {
pe.chunks[i] = 0 // Logic below relies on zero value as uninitialized
}
// Insert each symbol, checking that there are no conflicts.
for _, c := range codes {
if pe.chunks[c.Sym&pe.chunkMask] > 0 {
// Collision found our "hash" table, so grow and try again.
numChunks <<= 1
goto retry
}
pe.chunks[c.Sym&pe.chunkMask] = c.Val<<countBits | c.Len
}
} | go | func (pe *Encoder) Init(codes PrefixCodes) {
// Handle special case trees.
if len(codes) <= 1 {
switch {
case len(codes) == 0: // Empty tree (should error if used later)
*pe = Encoder{chunks: pe.chunks[:0], NumSyms: 0}
case len(codes) == 1 && codes[0].Len == 0: // Single code tree (bit-length of zero)
pe.chunks = append(pe.chunks[:0], codes[0].Val<<countBits|0)
*pe = Encoder{chunks: pe.chunks[:1], NumSyms: 1}
default:
panic("invalid codes")
}
return
}
if internal.Debug && !sort.IsSorted(prefixCodesBySymbol(codes)) {
panic("input codes is not sorted")
}
if internal.Debug && !(codes.checkLengths() && codes.checkPrefixes()) {
panic("detected incomplete or overlapping codes")
}
// Enough chunks to contain all the symbols.
numChunks := 1
for n := len(codes) - 1; n > 0; n >>= 1 {
numChunks <<= 1
}
pe.NumSyms = uint32(len(codes))
retry:
// Allocate and reset chunks.
pe.chunks = allocUint32s(pe.chunks, numChunks)
pe.chunkMask = uint32(numChunks - 1)
for i := range pe.chunks {
pe.chunks[i] = 0 // Logic below relies on zero value as uninitialized
}
// Insert each symbol, checking that there are no conflicts.
for _, c := range codes {
if pe.chunks[c.Sym&pe.chunkMask] > 0 {
// Collision found our "hash" table, so grow and try again.
numChunks <<= 1
goto retry
}
pe.chunks[c.Sym&pe.chunkMask] = c.Val<<countBits | c.Len
}
} | [
"func",
"(",
"pe",
"*",
"Encoder",
")",
"Init",
"(",
"codes",
"PrefixCodes",
")",
"{",
"// Handle special case trees.",
"if",
"len",
"(",
"codes",
")",
"<=",
"1",
"{",
"switch",
"{",
"case",
"len",
"(",
"codes",
")",
"==",
"0",
":",
"// Empty tree (shoul... | // Init initializes Encoder according to the codes provided. | [
"Init",
"initializes",
"Encoder",
"according",
"to",
"the",
"codes",
"provided",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/encoder.go#L21-L66 |
9,656 | dsnet/compress | internal/tool/fuzz/xflate_meta/xflate_meta.go | decodeMeta | func decodeMeta(data []byte) ([]byte, bool) {
r := bytes.NewReader(data)
mr := xflate.NewMetaReader(r)
b, err := ioutil.ReadAll(mr)
if err != nil {
return nil, false
}
pos := int(r.Size()) - r.Len()
decompressMeta(data[:pos])
return b, true
} | go | func decodeMeta(data []byte) ([]byte, bool) {
r := bytes.NewReader(data)
mr := xflate.NewMetaReader(r)
b, err := ioutil.ReadAll(mr)
if err != nil {
return nil, false
}
pos := int(r.Size()) - r.Len()
decompressMeta(data[:pos])
return b, true
} | [
"func",
"decodeMeta",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"bool",
")",
"{",
"r",
":=",
"bytes",
".",
"NewReader",
"(",
"data",
")",
"\n",
"mr",
":=",
"xflate",
".",
"NewMetaReader",
"(",
"r",
")",
"\n",
"b",
",",
"er... | // decodeMeta attempts to decode the metadata.
// If successful, it verifies that meta-encoded blocks are DEFLATE blocks. | [
"decodeMeta",
"attempts",
"to",
"decode",
"the",
"metadata",
".",
"If",
"successful",
"it",
"verifies",
"that",
"meta",
"-",
"encoded",
"blocks",
"are",
"DEFLATE",
"blocks",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/tool/fuzz/xflate_meta/xflate_meta.go#L30-L40 |
9,657 | dsnet/compress | internal/tool/fuzz/xflate_meta/xflate_meta.go | decompressMeta | func decompressMeta(data []byte) {
// Make a copy and append DEFLATE terminator block.
data = append([]byte(nil), data...)
data = append(data, []byte{0x01, 0x00, 0x00, 0xff, 0xff}...)
r := bytes.NewReader(data)
for r.Len() > 0 {
zr := flate.NewReader(r)
b, err := ioutil.ReadAll(zr)
if err != nil {
panic(err)
}
if len(b) > 0 {
panic("non-zero meta-encoded block")
}
if err := zr.Close(); err != nil {
panic(err)
}
}
} | go | func decompressMeta(data []byte) {
// Make a copy and append DEFLATE terminator block.
data = append([]byte(nil), data...)
data = append(data, []byte{0x01, 0x00, 0x00, 0xff, 0xff}...)
r := bytes.NewReader(data)
for r.Len() > 0 {
zr := flate.NewReader(r)
b, err := ioutil.ReadAll(zr)
if err != nil {
panic(err)
}
if len(b) > 0 {
panic("non-zero meta-encoded block")
}
if err := zr.Close(); err != nil {
panic(err)
}
}
} | [
"func",
"decompressMeta",
"(",
"data",
"[",
"]",
"byte",
")",
"{",
"// Make a copy and append DEFLATE terminator block.",
"data",
"=",
"append",
"(",
"[",
"]",
"byte",
"(",
"nil",
")",
",",
"data",
"...",
")",
"\n",
"data",
"=",
"append",
"(",
"data",
",",... | // decompressMeta attempts to decompress the meta-encoded blocks.
// It expects decompression to succeed and to output nothing. | [
"decompressMeta",
"attempts",
"to",
"decompress",
"the",
"meta",
"-",
"encoded",
"blocks",
".",
"It",
"expects",
"decompression",
"to",
"succeed",
"and",
"to",
"output",
"nothing",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/tool/fuzz/xflate_meta/xflate_meta.go#L44-L63 |
9,658 | dsnet/compress | brotli/dict.go | initDictLUTs | func initDictLUTs() {
// Sweep from minDictLen to maxDictLen, inclusive.
for i := minDictLen; i <= maxDictLen; i++ {
dictSizes[i] = 1 << uint(dictBitSizes[i])
dictOffsets[i] = dictOffsets[i-1] + (i-1)*dictSizes[i-1]
}
} | go | func initDictLUTs() {
// Sweep from minDictLen to maxDictLen, inclusive.
for i := minDictLen; i <= maxDictLen; i++ {
dictSizes[i] = 1 << uint(dictBitSizes[i])
dictOffsets[i] = dictOffsets[i-1] + (i-1)*dictSizes[i-1]
}
} | [
"func",
"initDictLUTs",
"(",
")",
"{",
"// Sweep from minDictLen to maxDictLen, inclusive.",
"for",
"i",
":=",
"minDictLen",
";",
"i",
"<=",
"maxDictLen",
";",
"i",
"++",
"{",
"dictSizes",
"[",
"i",
"]",
"=",
"1",
"<<",
"uint",
"(",
"dictBitSizes",
"[",
"i",... | // We dynamically compute NWORDS and DOFFSET according to the algorithm
// provided in RFC section 8. | [
"We",
"dynamically",
"compute",
"NWORDS",
"and",
"DOFFSET",
"according",
"to",
"the",
"algorithm",
"provided",
"in",
"RFC",
"section",
"8",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/dict.go#L29-L35 |
9,659 | dsnet/compress | internal/prefix/range.go | MakeRangeCodes | func MakeRangeCodes(minBase uint, bits []uint) (rc RangeCodes) {
for _, nb := range bits {
rc = append(rc, RangeCode{Base: uint32(minBase), Len: uint32(nb)})
minBase += 1 << nb
}
return rc
} | go | func MakeRangeCodes(minBase uint, bits []uint) (rc RangeCodes) {
for _, nb := range bits {
rc = append(rc, RangeCode{Base: uint32(minBase), Len: uint32(nb)})
minBase += 1 << nb
}
return rc
} | [
"func",
"MakeRangeCodes",
"(",
"minBase",
"uint",
",",
"bits",
"[",
"]",
"uint",
")",
"(",
"rc",
"RangeCodes",
")",
"{",
"for",
"_",
",",
"nb",
":=",
"range",
"bits",
"{",
"rc",
"=",
"append",
"(",
"rc",
",",
"RangeCode",
"{",
"Base",
":",
"uint32"... | // MakeRangeCodes creates a RangeCodes, where each region is assumed to be
// contiguously stacked, without any gaps, with bit-lengths taken from bits. | [
"MakeRangeCodes",
"creates",
"a",
"RangeCodes",
"where",
"each",
"region",
"is",
"assumed",
"to",
"be",
"contiguously",
"stacked",
"without",
"any",
"gaps",
"with",
"bit",
"-",
"lengths",
"taken",
"from",
"bits",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/range.go#L24-L30 |
9,660 | dsnet/compress | flate/prefix.go | handleDegenerateCodes | func handleDegenerateCodes(codes prefix.PrefixCodes, maxSyms uint) prefix.PrefixCodes {
if len(codes) != 1 {
return codes
}
return append(codes, prefix.PrefixCode{Sym: uint32(maxSyms), Len: 1})
} | go | func handleDegenerateCodes(codes prefix.PrefixCodes, maxSyms uint) prefix.PrefixCodes {
if len(codes) != 1 {
return codes
}
return append(codes, prefix.PrefixCode{Sym: uint32(maxSyms), Len: 1})
} | [
"func",
"handleDegenerateCodes",
"(",
"codes",
"prefix",
".",
"PrefixCodes",
",",
"maxSyms",
"uint",
")",
"prefix",
".",
"PrefixCodes",
"{",
"if",
"len",
"(",
"codes",
")",
"!=",
"1",
"{",
"return",
"codes",
"\n",
"}",
"\n",
"return",
"append",
"(",
"cod... | // RFC section 3.2.7 allows degenerate prefix trees with only node, but requires
// a single bit for that node. This causes an unbalanced tree where the "1" code
// is unused. The canonical prefix code generation algorithm breaks with this.
//
// To handle this case, we artificially insert another node for the "1" code
// that uses a symbol larger than the alphabet to force an error later if
// the code ends up getting used. | [
"RFC",
"section",
"3",
".",
"2",
".",
"7",
"allows",
"degenerate",
"prefix",
"trees",
"with",
"only",
"node",
"but",
"requires",
"a",
"single",
"bit",
"for",
"that",
"node",
".",
"This",
"causes",
"an",
"unbalanced",
"tree",
"where",
"the",
"1",
"code",
... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/flate/prefix.go#L203-L208 |
9,661 | dsnet/compress | internal/common.go | ReverseUint32 | func ReverseUint32(v uint32) (x uint32) {
x |= uint32(ReverseLUT[byte(v>>0)]) << 24
x |= uint32(ReverseLUT[byte(v>>8)]) << 16
x |= uint32(ReverseLUT[byte(v>>16)]) << 8
x |= uint32(ReverseLUT[byte(v>>24)]) << 0
return x
} | go | func ReverseUint32(v uint32) (x uint32) {
x |= uint32(ReverseLUT[byte(v>>0)]) << 24
x |= uint32(ReverseLUT[byte(v>>8)]) << 16
x |= uint32(ReverseLUT[byte(v>>16)]) << 8
x |= uint32(ReverseLUT[byte(v>>24)]) << 0
return x
} | [
"func",
"ReverseUint32",
"(",
"v",
"uint32",
")",
"(",
"x",
"uint32",
")",
"{",
"x",
"|=",
"uint32",
"(",
"ReverseLUT",
"[",
"byte",
"(",
"v",
">>",
"0",
")",
"]",
")",
"<<",
"24",
"\n",
"x",
"|=",
"uint32",
"(",
"ReverseLUT",
"[",
"byte",
"(",
... | // ReverseUint32 reverses all bits of v. | [
"ReverseUint32",
"reverses",
"all",
"bits",
"of",
"v",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/common.go#L34-L40 |
9,662 | dsnet/compress | internal/common.go | ReverseUint32N | func ReverseUint32N(v uint32, n uint) (x uint32) {
return ReverseUint32(v << (32 - n))
} | go | func ReverseUint32N(v uint32, n uint) (x uint32) {
return ReverseUint32(v << (32 - n))
} | [
"func",
"ReverseUint32N",
"(",
"v",
"uint32",
",",
"n",
"uint",
")",
"(",
"x",
"uint32",
")",
"{",
"return",
"ReverseUint32",
"(",
"v",
"<<",
"(",
"32",
"-",
"n",
")",
")",
"\n",
"}"
] | // ReverseUint32N reverses the lower n bits of v. | [
"ReverseUint32N",
"reverses",
"the",
"lower",
"n",
"bits",
"of",
"v",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/common.go#L43-L45 |
9,663 | dsnet/compress | internal/common.go | ReverseUint64 | func ReverseUint64(v uint64) (x uint64) {
x |= uint64(ReverseLUT[byte(v>>0)]) << 56
x |= uint64(ReverseLUT[byte(v>>8)]) << 48
x |= uint64(ReverseLUT[byte(v>>16)]) << 40
x |= uint64(ReverseLUT[byte(v>>24)]) << 32
x |= uint64(ReverseLUT[byte(v>>32)]) << 24
x |= uint64(ReverseLUT[byte(v>>40)]) << 16
x |= uint64(ReverseLUT[byte(v>>48)]) << 8
x |= uint64(ReverseLUT[byte(v>>56)]) << 0
return x
} | go | func ReverseUint64(v uint64) (x uint64) {
x |= uint64(ReverseLUT[byte(v>>0)]) << 56
x |= uint64(ReverseLUT[byte(v>>8)]) << 48
x |= uint64(ReverseLUT[byte(v>>16)]) << 40
x |= uint64(ReverseLUT[byte(v>>24)]) << 32
x |= uint64(ReverseLUT[byte(v>>32)]) << 24
x |= uint64(ReverseLUT[byte(v>>40)]) << 16
x |= uint64(ReverseLUT[byte(v>>48)]) << 8
x |= uint64(ReverseLUT[byte(v>>56)]) << 0
return x
} | [
"func",
"ReverseUint64",
"(",
"v",
"uint64",
")",
"(",
"x",
"uint64",
")",
"{",
"x",
"|=",
"uint64",
"(",
"ReverseLUT",
"[",
"byte",
"(",
"v",
">>",
"0",
")",
"]",
")",
"<<",
"56",
"\n",
"x",
"|=",
"uint64",
"(",
"ReverseLUT",
"[",
"byte",
"(",
... | // ReverseUint64 reverses all bits of v. | [
"ReverseUint64",
"reverses",
"all",
"bits",
"of",
"v",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/common.go#L48-L58 |
9,664 | dsnet/compress | internal/common.go | ReverseUint64N | func ReverseUint64N(v uint64, n uint) (x uint64) {
return ReverseUint64(v << (64 - n))
} | go | func ReverseUint64N(v uint64, n uint) (x uint64) {
return ReverseUint64(v << (64 - n))
} | [
"func",
"ReverseUint64N",
"(",
"v",
"uint64",
",",
"n",
"uint",
")",
"(",
"x",
"uint64",
")",
"{",
"return",
"ReverseUint64",
"(",
"v",
"<<",
"(",
"64",
"-",
"n",
")",
")",
"\n",
"}"
] | // ReverseUint64N reverses the lower n bits of v. | [
"ReverseUint64N",
"reverses",
"the",
"lower",
"n",
"bits",
"of",
"v",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/common.go#L61-L63 |
9,665 | dsnet/compress | xflate/internal/meta/meta.go | ReverseSearch | func ReverseSearch(data []byte) int {
var magic uint32
for i := len(data) - 1; i >= 0; i-- {
magic = (magic << 8) | uint32(data[i])
if magic&magicMask == magicVals {
return i
}
}
return -1
} | go | func ReverseSearch(data []byte) int {
var magic uint32
for i := len(data) - 1; i >= 0; i-- {
magic = (magic << 8) | uint32(data[i])
if magic&magicMask == magicVals {
return i
}
}
return -1
} | [
"func",
"ReverseSearch",
"(",
"data",
"[",
"]",
"byte",
")",
"int",
"{",
"var",
"magic",
"uint32",
"\n",
"for",
"i",
":=",
"len",
"(",
"data",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"magic",
"=",
"(",
"magic",
"<<",
"8",
")"... | // ReverseSearch searches for a meta header in reverse. This returns the last
// index where the header was found. If not found, it returns -1. | [
"ReverseSearch",
"searches",
"for",
"a",
"meta",
"header",
"in",
"reverse",
".",
"This",
"returns",
"the",
"last",
"index",
"where",
"the",
"header",
"was",
"found",
".",
"If",
"not",
"found",
"it",
"returns",
"-",
"1",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/meta.go#L35-L44 |
9,666 | dsnet/compress | xflate/internal/meta/meta.go | numBits | func numBits(b byte) (zeros, ones int) {
ones = int(oneBitsLUT[b])
zeros = 8 - ones
return
} | go | func numBits(b byte) (zeros, ones int) {
ones = int(oneBitsLUT[b])
zeros = 8 - ones
return
} | [
"func",
"numBits",
"(",
"b",
"byte",
")",
"(",
"zeros",
",",
"ones",
"int",
")",
"{",
"ones",
"=",
"int",
"(",
"oneBitsLUT",
"[",
"b",
"]",
")",
"\n",
"zeros",
"=",
"8",
"-",
"ones",
"\n",
"return",
"\n",
"}"
] | // numBits counts the number of zero and one bits in the byte. | [
"numBits",
"counts",
"the",
"number",
"of",
"zero",
"and",
"one",
"bits",
"in",
"the",
"byte",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/meta.go#L156-L160 |
9,667 | dsnet/compress | xflate/reader.go | NewReader | func NewReader(rs io.ReadSeeker, conf *ReaderConfig) (*Reader, error) {
xr := new(Reader)
err := xr.Reset(rs)
return xr, err
} | go | func NewReader(rs io.ReadSeeker, conf *ReaderConfig) (*Reader, error) {
xr := new(Reader)
err := xr.Reset(rs)
return xr, err
} | [
"func",
"NewReader",
"(",
"rs",
"io",
".",
"ReadSeeker",
",",
"conf",
"*",
"ReaderConfig",
")",
"(",
"*",
"Reader",
",",
"error",
")",
"{",
"xr",
":=",
"new",
"(",
"Reader",
")",
"\n",
"err",
":=",
"xr",
".",
"Reset",
"(",
"rs",
")",
"\n",
"retur... | // NewReader creates a new Reader reading the given reader rs. This reader can
// only decompress files in the XFLATE format. If the underlying stream is
// regular DEFLATE and not XFLATE, then this returns error.
//
// Regardless of the current offset in rs, this function Seeks to the end of rs
// in order to determine the total compressed size. The Reader returned has its
// offset set to the start of the stream.
//
// If conf is nil, then default configuration values are used. Reader copies
// all configuration values as necessary and does not store conf. | [
"NewReader",
"creates",
"a",
"new",
"Reader",
"reading",
"the",
"given",
"reader",
"rs",
".",
"This",
"reader",
"can",
"only",
"decompress",
"files",
"in",
"the",
"XFLATE",
"format",
".",
"If",
"the",
"underlying",
"stream",
"is",
"regular",
"DEFLATE",
"and"... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/reader.go#L113-L117 |
9,668 | dsnet/compress | xflate/reader.go | Reset | func (xr *Reader) Reset(rs io.ReadSeeker) error {
*xr = Reader{
rd: rs,
mr: xr.mr,
zr: xr.zr,
idx: xr.idx,
br: xr.br,
bw: xr.bw,
idxs: xr.idxs,
chunks: xr.chunks,
}
if xr.zr == nil {
xr.zr, _ = newFlateReader(nil)
}
xr.idx.Reset()
// Read entire index.
var backSize, footSize int64
if backSize, footSize, xr.err = xr.decodeFooter(); xr.err != nil {
return xr.err
}
if xr.err = xr.decodeIndexes(backSize); xr.err != nil {
return xr.err
}
if !xr.idx.AppendRecord(footSize, 0, footerType) {
xr.err = errCorrupted
return xr.err
}
// Setup initial chunk reader.
_, xr.err = xr.Seek(0, io.SeekStart)
return xr.err
} | go | func (xr *Reader) Reset(rs io.ReadSeeker) error {
*xr = Reader{
rd: rs,
mr: xr.mr,
zr: xr.zr,
idx: xr.idx,
br: xr.br,
bw: xr.bw,
idxs: xr.idxs,
chunks: xr.chunks,
}
if xr.zr == nil {
xr.zr, _ = newFlateReader(nil)
}
xr.idx.Reset()
// Read entire index.
var backSize, footSize int64
if backSize, footSize, xr.err = xr.decodeFooter(); xr.err != nil {
return xr.err
}
if xr.err = xr.decodeIndexes(backSize); xr.err != nil {
return xr.err
}
if !xr.idx.AppendRecord(footSize, 0, footerType) {
xr.err = errCorrupted
return xr.err
}
// Setup initial chunk reader.
_, xr.err = xr.Seek(0, io.SeekStart)
return xr.err
} | [
"func",
"(",
"xr",
"*",
"Reader",
")",
"Reset",
"(",
"rs",
"io",
".",
"ReadSeeker",
")",
"error",
"{",
"*",
"xr",
"=",
"Reader",
"{",
"rd",
":",
"rs",
",",
"mr",
":",
"xr",
".",
"mr",
",",
"zr",
":",
"xr",
".",
"zr",
",",
"idx",
":",
"xr",
... | // Reset discards the Reader's state and makes it equivalent to the result
// of a call to NewReader, but reading from rd instead. This method may return
// an error if it is unable to parse the index.
//
// This is used to reduce memory allocations. | [
"Reset",
"discards",
"the",
"Reader",
"s",
"state",
"and",
"makes",
"it",
"equivalent",
"to",
"the",
"result",
"of",
"a",
"call",
"to",
"NewReader",
"but",
"reading",
"from",
"rd",
"instead",
".",
"This",
"method",
"may",
"return",
"an",
"error",
"if",
"... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/reader.go#L124-L157 |
9,669 | dsnet/compress | xflate/reader.go | Read | func (xr *Reader) Read(buf []byte) (int, error) {
if xr.err != nil {
return 0, xr.err
}
// Discard some data to reach the expected raw offset.
if xr.discard > 0 {
var n int64
xr.lr = io.LimitedReader{R: xr.zr, N: xr.discard}
n, xr.err = io.Copy(ioutil.Discard, &xr.lr)
if xr.err != nil {
return 0, xr.err
}
if n != xr.discard {
xr.err = errCorrupted
return 0, xr.err
}
xr.discard = 0
}
var cnt int
for cnt == 0 && xr.err == nil {
cnt, xr.err = xr.zr.Read(buf)
xr.offset += int64(cnt)
if xr.err == io.EOF {
xr.err = nil // Clear io.EOF temporarily
// Verify that the compressed section ends with an empty raw block.
if xr.chk.typ == deflateType && xr.cr.sync != 0x0000ffff {
xr.err = errCorrupted
break
}
// Verify that the compressed and raw sizes match.
if xr.chk.typ != footerType {
xr.chk.csize += int64(len(endBlock)) // Side of effect of using chunkReader
}
if xr.chk.csize != xr.zr.InputOffset || xr.chk.rsize != xr.zr.OutputOffset {
xr.err = errCorrupted
break
}
// Seek to next chunk.
if _, xr.err = xr.Seek(xr.offset, io.SeekStart); xr.err != nil {
break
}
if xr.chk.typ == unknownType {
xr.err = io.EOF
}
}
}
return cnt, xr.err
} | go | func (xr *Reader) Read(buf []byte) (int, error) {
if xr.err != nil {
return 0, xr.err
}
// Discard some data to reach the expected raw offset.
if xr.discard > 0 {
var n int64
xr.lr = io.LimitedReader{R: xr.zr, N: xr.discard}
n, xr.err = io.Copy(ioutil.Discard, &xr.lr)
if xr.err != nil {
return 0, xr.err
}
if n != xr.discard {
xr.err = errCorrupted
return 0, xr.err
}
xr.discard = 0
}
var cnt int
for cnt == 0 && xr.err == nil {
cnt, xr.err = xr.zr.Read(buf)
xr.offset += int64(cnt)
if xr.err == io.EOF {
xr.err = nil // Clear io.EOF temporarily
// Verify that the compressed section ends with an empty raw block.
if xr.chk.typ == deflateType && xr.cr.sync != 0x0000ffff {
xr.err = errCorrupted
break
}
// Verify that the compressed and raw sizes match.
if xr.chk.typ != footerType {
xr.chk.csize += int64(len(endBlock)) // Side of effect of using chunkReader
}
if xr.chk.csize != xr.zr.InputOffset || xr.chk.rsize != xr.zr.OutputOffset {
xr.err = errCorrupted
break
}
// Seek to next chunk.
if _, xr.err = xr.Seek(xr.offset, io.SeekStart); xr.err != nil {
break
}
if xr.chk.typ == unknownType {
xr.err = io.EOF
}
}
}
return cnt, xr.err
} | [
"func",
"(",
"xr",
"*",
"Reader",
")",
"Read",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"xr",
".",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"xr",
".",
"err",
"\n",
"}",
"\n\n",
"// Discard some data to reac... | // Read reads decompressed data from the underlying io.Reader.
// This method automatically proceeds to the next chunk when the current one
// has been fully read. | [
"Read",
"reads",
"decompressed",
"data",
"from",
"the",
"underlying",
"io",
".",
"Reader",
".",
"This",
"method",
"automatically",
"proceeds",
"to",
"the",
"next",
"chunk",
"when",
"the",
"current",
"one",
"has",
"been",
"fully",
"read",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/reader.go#L162-L215 |
9,670 | dsnet/compress | xflate/reader.go | Seek | func (xr *Reader) Seek(offset int64, whence int) (int64, error) {
if xr.err != nil && xr.err != io.EOF {
return 0, xr.err
}
// Determine which position to seek to.
var pos int64
end := xr.idx.LastRecord().RawOffset
switch whence {
case io.SeekStart:
pos = offset
case io.SeekCurrent:
pos = xr.offset + offset
case io.SeekEnd:
pos = end + offset
default:
return 0, errorf(errors.Invalid, "invalid whence: %d", whence)
}
if pos < 0 {
return 0, errorf(errors.Invalid, "negative position: %d", pos)
}
// As an optimization if the new position is within the current chunk,
// then just adjust the discard value.
discard := pos - xr.offset
remain := xr.chk.rsize - xr.zr.OutputOffset
if discard > 0 && remain > 0 && discard < remain {
xr.offset, xr.discard = pos, discard
return pos, nil
}
// Query the index for the chunk to start decoding from.
// Attempt to use the subsequent record before resorting to binary search.
prev, curr := xr.idx.GetRecords(xr.ri)
if !(prev.RawOffset <= pos && pos <= curr.RawOffset) {
xr.ri = xr.idx.Search(pos)
prev, curr = xr.idx.GetRecords(xr.ri)
}
xr.ri++
if xr.ri > len(xr.idx.Records) {
xr.ri = len(xr.idx.Records)
}
// Setup a chunk reader at the given position.
xr.chk = chunk{
csize: curr.CompOffset - prev.CompOffset,
rsize: curr.RawOffset - prev.RawOffset,
typ: curr.Type,
}
xr.offset, xr.discard = pos, pos-prev.RawOffset
if pos > end {
// In case pos is really large, only discard data that actually exists.
xr.discard = end - prev.RawOffset
}
_, xr.err = xr.rd.Seek(prev.CompOffset, io.SeekStart)
xr.cr.Reset(xr.rd, xr.chk.csize)
xr.zr.Reset(&xr.cr)
return pos, xr.err
} | go | func (xr *Reader) Seek(offset int64, whence int) (int64, error) {
if xr.err != nil && xr.err != io.EOF {
return 0, xr.err
}
// Determine which position to seek to.
var pos int64
end := xr.idx.LastRecord().RawOffset
switch whence {
case io.SeekStart:
pos = offset
case io.SeekCurrent:
pos = xr.offset + offset
case io.SeekEnd:
pos = end + offset
default:
return 0, errorf(errors.Invalid, "invalid whence: %d", whence)
}
if pos < 0 {
return 0, errorf(errors.Invalid, "negative position: %d", pos)
}
// As an optimization if the new position is within the current chunk,
// then just adjust the discard value.
discard := pos - xr.offset
remain := xr.chk.rsize - xr.zr.OutputOffset
if discard > 0 && remain > 0 && discard < remain {
xr.offset, xr.discard = pos, discard
return pos, nil
}
// Query the index for the chunk to start decoding from.
// Attempt to use the subsequent record before resorting to binary search.
prev, curr := xr.idx.GetRecords(xr.ri)
if !(prev.RawOffset <= pos && pos <= curr.RawOffset) {
xr.ri = xr.idx.Search(pos)
prev, curr = xr.idx.GetRecords(xr.ri)
}
xr.ri++
if xr.ri > len(xr.idx.Records) {
xr.ri = len(xr.idx.Records)
}
// Setup a chunk reader at the given position.
xr.chk = chunk{
csize: curr.CompOffset - prev.CompOffset,
rsize: curr.RawOffset - prev.RawOffset,
typ: curr.Type,
}
xr.offset, xr.discard = pos, pos-prev.RawOffset
if pos > end {
// In case pos is really large, only discard data that actually exists.
xr.discard = end - prev.RawOffset
}
_, xr.err = xr.rd.Seek(prev.CompOffset, io.SeekStart)
xr.cr.Reset(xr.rd, xr.chk.csize)
xr.zr.Reset(&xr.cr)
return pos, xr.err
} | [
"func",
"(",
"xr",
"*",
"Reader",
")",
"Seek",
"(",
"offset",
"int64",
",",
"whence",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"xr",
".",
"err",
"!=",
"nil",
"&&",
"xr",
".",
"err",
"!=",
"io",
".",
"EOF",
"{",
"return",
"0",
"... | // Seek sets the offset for the next Read operation, interpreted according to
// the whence value provided. It is permitted to seek to offsets in the middle
// of a compressed chunk. The next call to Read will automatically discard some
// number of bytes before returning the requested data. | [
"Seek",
"sets",
"the",
"offset",
"for",
"the",
"next",
"Read",
"operation",
"interpreted",
"according",
"to",
"the",
"whence",
"value",
"provided",
".",
"It",
"is",
"permitted",
"to",
"seek",
"to",
"offsets",
"in",
"the",
"middle",
"of",
"a",
"compressed",
... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/reader.go#L221-L279 |
9,671 | dsnet/compress | xflate/reader.go | Close | func (xr *Reader) Close() error {
if xr.err == errClosed {
return nil
}
if xr.err != nil && xr.err != io.EOF {
return xr.err
}
xr.err = errClosed
return nil
} | go | func (xr *Reader) Close() error {
if xr.err == errClosed {
return nil
}
if xr.err != nil && xr.err != io.EOF {
return xr.err
}
xr.err = errClosed
return nil
} | [
"func",
"(",
"xr",
"*",
"Reader",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"xr",
".",
"err",
"==",
"errClosed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"xr",
".",
"err",
"!=",
"nil",
"&&",
"xr",
".",
"err",
"!=",
"io",
".",
"EOF",
"{"... | // Close ends the XFLATE stream. | [
"Close",
"ends",
"the",
"XFLATE",
"stream",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/reader.go#L282-L291 |
9,672 | dsnet/compress | xflate/reader.go | decodeIndexes | func (xr *Reader) decodeIndexes(backSize int64) error {
pos, err := xr.rd.Seek(0, io.SeekCurrent)
if err != nil {
return err
}
// Read all indexes.
var compSize int64
xr.idxs = xr.idxs[:0]
for {
// Seek backwards past index and compressed blocks.
newPos := pos - (backSize + compSize)
if newPos < 0 || newPos > pos {
return errCorrupted // Integer overflow for new seek position
}
if pos, err = xr.rd.Seek(newPos, io.SeekStart); err != nil {
return err
}
if backSize == 0 {
break
}
// Read the index.
if cap(xr.idxs) > len(xr.idxs) {
xr.idxs = xr.idxs[:len(xr.idxs)+1]
} else {
xr.idxs = append(xr.idxs, index{})
}
idx := &xr.idxs[len(xr.idxs)-1]
idx.Reset()
idx.IndexSize = backSize
if err = xr.decodeIndex(idx); err != nil {
return err
}
backSize, compSize = idx.BackSize, idx.LastRecord().CompOffset
}
if pos != 0 {
return errCorrupted
}
// Compact all indexes into one.
for i := len(xr.idxs) - 1; i >= 0; i-- {
idx := xr.idxs[i]
if !xr.idx.AppendIndex(&idx) {
return errCorrupted
}
if !xr.idx.AppendRecord(idx.IndexSize, 0, indexType) {
return errCorrupted
}
}
return nil
} | go | func (xr *Reader) decodeIndexes(backSize int64) error {
pos, err := xr.rd.Seek(0, io.SeekCurrent)
if err != nil {
return err
}
// Read all indexes.
var compSize int64
xr.idxs = xr.idxs[:0]
for {
// Seek backwards past index and compressed blocks.
newPos := pos - (backSize + compSize)
if newPos < 0 || newPos > pos {
return errCorrupted // Integer overflow for new seek position
}
if pos, err = xr.rd.Seek(newPos, io.SeekStart); err != nil {
return err
}
if backSize == 0 {
break
}
// Read the index.
if cap(xr.idxs) > len(xr.idxs) {
xr.idxs = xr.idxs[:len(xr.idxs)+1]
} else {
xr.idxs = append(xr.idxs, index{})
}
idx := &xr.idxs[len(xr.idxs)-1]
idx.Reset()
idx.IndexSize = backSize
if err = xr.decodeIndex(idx); err != nil {
return err
}
backSize, compSize = idx.BackSize, idx.LastRecord().CompOffset
}
if pos != 0 {
return errCorrupted
}
// Compact all indexes into one.
for i := len(xr.idxs) - 1; i >= 0; i-- {
idx := xr.idxs[i]
if !xr.idx.AppendIndex(&idx) {
return errCorrupted
}
if !xr.idx.AppendRecord(idx.IndexSize, 0, indexType) {
return errCorrupted
}
}
return nil
} | [
"func",
"(",
"xr",
"*",
"Reader",
")",
"decodeIndexes",
"(",
"backSize",
"int64",
")",
"error",
"{",
"pos",
",",
"err",
":=",
"xr",
".",
"rd",
".",
"Seek",
"(",
"0",
",",
"io",
".",
"SeekCurrent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return... | // decodeIndexes iteratively decodes all of the indexes in the XFLATE stream.
// Even if the index is fragmented in the source stream, this method will merge
// all of the index fragments into a single index table. | [
"decodeIndexes",
"iteratively",
"decodes",
"all",
"of",
"the",
"indexes",
"in",
"the",
"XFLATE",
"stream",
".",
"Even",
"if",
"the",
"index",
"is",
"fragmented",
"in",
"the",
"source",
"stream",
"this",
"method",
"will",
"merge",
"all",
"of",
"the",
"index",... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/reader.go#L296-L347 |
9,673 | dsnet/compress | xflate/reader.go | decodeIndex | func (xr *Reader) decodeIndex(idx *index) error {
// Helper function to read VLIs.
var errVLI error
readVLI := func() int64 {
x, n := binary.Uvarint(xr.bw.Bytes())
if n <= 0 || x > math.MaxInt64 {
errVLI = errCorrupted
return 0
}
xr.bw.Next(n)
return int64(x)
}
// Read the index and restore the underlying reader offset.
xr.br.Reset()
xr.lr = io.LimitedReader{R: xr.rd, N: idx.IndexSize}
n, err := io.Copy(&xr.br, &xr.lr)
if err != nil {
return err
}
if _, err := xr.rd.Seek(-n, io.SeekCurrent); err != nil {
return err
}
// Parse the index.
var crc uint32
xr.chunks = xr.chunks[:0]
xr.bw.Reset()
xr.mr.Reset(&xr.br)
if _, err := io.Copy(&xr.bw, &xr.mr); err != nil {
return errWrap(err)
}
if xr.bw.Len() > 4 {
crc = crc32.ChecksumIEEE(xr.bw.Bytes()[:xr.bw.Len()-4])
}
idx.BackSize = readVLI()
numRecs := readVLI()
totalCompSize := readVLI()
totalRawSize := readVLI()
if errVLI != nil {
return errVLI
}
for i := int64(0); i < numRecs; i++ {
xr.chunks = append(xr.chunks, chunk{readVLI(), readVLI(), 0})
}
if xr.bw.Len() != 4 || binary.LittleEndian.Uint32(xr.bw.Bytes()) != crc {
return errCorrupted
}
if xr.mr.FinalMode != meta.FinalMeta {
return errCorrupted
}
if xr.mr.InputOffset != idx.IndexSize {
return errCorrupted
}
// Convert individual index sizes to be absolute offsets.
for _, chk := range xr.chunks {
if chk.csize <= 4 {
return errCorrupted // Every chunk has a sync marker
}
if !idx.AppendRecord(chk.csize, chk.rsize, deflateType) {
return errCorrupted
}
}
lastRec := idx.LastRecord()
if lastRec.CompOffset != totalCompSize || lastRec.RawOffset != totalRawSize {
return errCorrupted
}
return nil
} | go | func (xr *Reader) decodeIndex(idx *index) error {
// Helper function to read VLIs.
var errVLI error
readVLI := func() int64 {
x, n := binary.Uvarint(xr.bw.Bytes())
if n <= 0 || x > math.MaxInt64 {
errVLI = errCorrupted
return 0
}
xr.bw.Next(n)
return int64(x)
}
// Read the index and restore the underlying reader offset.
xr.br.Reset()
xr.lr = io.LimitedReader{R: xr.rd, N: idx.IndexSize}
n, err := io.Copy(&xr.br, &xr.lr)
if err != nil {
return err
}
if _, err := xr.rd.Seek(-n, io.SeekCurrent); err != nil {
return err
}
// Parse the index.
var crc uint32
xr.chunks = xr.chunks[:0]
xr.bw.Reset()
xr.mr.Reset(&xr.br)
if _, err := io.Copy(&xr.bw, &xr.mr); err != nil {
return errWrap(err)
}
if xr.bw.Len() > 4 {
crc = crc32.ChecksumIEEE(xr.bw.Bytes()[:xr.bw.Len()-4])
}
idx.BackSize = readVLI()
numRecs := readVLI()
totalCompSize := readVLI()
totalRawSize := readVLI()
if errVLI != nil {
return errVLI
}
for i := int64(0); i < numRecs; i++ {
xr.chunks = append(xr.chunks, chunk{readVLI(), readVLI(), 0})
}
if xr.bw.Len() != 4 || binary.LittleEndian.Uint32(xr.bw.Bytes()) != crc {
return errCorrupted
}
if xr.mr.FinalMode != meta.FinalMeta {
return errCorrupted
}
if xr.mr.InputOffset != idx.IndexSize {
return errCorrupted
}
// Convert individual index sizes to be absolute offsets.
for _, chk := range xr.chunks {
if chk.csize <= 4 {
return errCorrupted // Every chunk has a sync marker
}
if !idx.AppendRecord(chk.csize, chk.rsize, deflateType) {
return errCorrupted
}
}
lastRec := idx.LastRecord()
if lastRec.CompOffset != totalCompSize || lastRec.RawOffset != totalRawSize {
return errCorrupted
}
return nil
} | [
"func",
"(",
"xr",
"*",
"Reader",
")",
"decodeIndex",
"(",
"idx",
"*",
"index",
")",
"error",
"{",
"// Helper function to read VLIs.",
"var",
"errVLI",
"error",
"\n",
"readVLI",
":=",
"func",
"(",
")",
"int64",
"{",
"x",
",",
"n",
":=",
"binary",
".",
... | // decodeIndex decodes the index from a meta encoded stream.
// The current offset must be set to the start of the encoded index and
// index.IndexSize must be populated. If successful, the index.Records and
// index.BackSize fields will be populated. This method will attempt to reset
// the read offset to the start of the index. | [
"decodeIndex",
"decodes",
"the",
"index",
"from",
"a",
"meta",
"encoded",
"stream",
".",
"The",
"current",
"offset",
"must",
"be",
"set",
"to",
"the",
"start",
"of",
"the",
"encoded",
"index",
"and",
"index",
".",
"IndexSize",
"must",
"be",
"populated",
".... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/reader.go#L354-L424 |
9,674 | dsnet/compress | xflate/reader.go | decodeFooter | func (xr *Reader) decodeFooter() (backSize, footSize int64, err error) {
// Read the last few bytes of the stream.
end, err := xr.rd.Seek(0, io.SeekEnd)
if err != nil {
return 0, 0, err
}
if end > meta.MaxEncBytes {
end = meta.MaxEncBytes
}
if _, err := xr.rd.Seek(-end, io.SeekEnd); err != nil {
return 0, 0, err
}
xr.br.Reset()
if _, err := io.Copy(&xr.br, xr.rd); err != nil {
return 0, 0, err
}
// Search for and read the meta block.
idx := meta.ReverseSearch(xr.br.Bytes())
if idx < 0 {
return 0, 0, errCorrupted
}
xr.br.Next(idx) // Skip data until magic marker
xr.bw.Reset()
xr.mr.Reset(&xr.br)
if _, err := io.Copy(&xr.bw, &xr.mr); err != nil {
return 0, 0, errWrap(err)
}
if xr.br.Len() != 0 || xr.mr.NumBlocks != 1 {
return 0, 0, errCorrupted
}
if xr.mr.FinalMode != meta.FinalStream {
return 0, 0, errCorrupted
}
if _, err := xr.rd.Seek(-xr.mr.InputOffset, io.SeekCurrent); err != nil {
return 0, 0, err
}
// Parse the footer.
bufRaw := xr.bw.Bytes()
if len(bufRaw) < 3 || !bytes.Equal(bufRaw[:3], magic[:]) {
return 0, 0, errCorrupted // Magic value mismatch
}
backSizeU64, cnt := binary.Uvarint(bufRaw[3:])
if cnt <= 0 {
return 0, 0, errCorrupted // Integer overflow for VLI
}
if len(bufRaw[3+cnt:]) > 0 {
return 0, 0, errCorrupted // Trailing unread bytes
}
return int64(backSizeU64), xr.mr.InputOffset, nil
} | go | func (xr *Reader) decodeFooter() (backSize, footSize int64, err error) {
// Read the last few bytes of the stream.
end, err := xr.rd.Seek(0, io.SeekEnd)
if err != nil {
return 0, 0, err
}
if end > meta.MaxEncBytes {
end = meta.MaxEncBytes
}
if _, err := xr.rd.Seek(-end, io.SeekEnd); err != nil {
return 0, 0, err
}
xr.br.Reset()
if _, err := io.Copy(&xr.br, xr.rd); err != nil {
return 0, 0, err
}
// Search for and read the meta block.
idx := meta.ReverseSearch(xr.br.Bytes())
if idx < 0 {
return 0, 0, errCorrupted
}
xr.br.Next(idx) // Skip data until magic marker
xr.bw.Reset()
xr.mr.Reset(&xr.br)
if _, err := io.Copy(&xr.bw, &xr.mr); err != nil {
return 0, 0, errWrap(err)
}
if xr.br.Len() != 0 || xr.mr.NumBlocks != 1 {
return 0, 0, errCorrupted
}
if xr.mr.FinalMode != meta.FinalStream {
return 0, 0, errCorrupted
}
if _, err := xr.rd.Seek(-xr.mr.InputOffset, io.SeekCurrent); err != nil {
return 0, 0, err
}
// Parse the footer.
bufRaw := xr.bw.Bytes()
if len(bufRaw) < 3 || !bytes.Equal(bufRaw[:3], magic[:]) {
return 0, 0, errCorrupted // Magic value mismatch
}
backSizeU64, cnt := binary.Uvarint(bufRaw[3:])
if cnt <= 0 {
return 0, 0, errCorrupted // Integer overflow for VLI
}
if len(bufRaw[3+cnt:]) > 0 {
return 0, 0, errCorrupted // Trailing unread bytes
}
return int64(backSizeU64), xr.mr.InputOffset, nil
} | [
"func",
"(",
"xr",
"*",
"Reader",
")",
"decodeFooter",
"(",
")",
"(",
"backSize",
",",
"footSize",
"int64",
",",
"err",
"error",
")",
"{",
"// Read the last few bytes of the stream.",
"end",
",",
"err",
":=",
"xr",
".",
"rd",
".",
"Seek",
"(",
"0",
",",
... | // decodeFooter seeks to the end of the stream, searches for the footer
// and decodes it. If successful, it will return the backSize for the preceding
// index and the size of the footer itself. This method will attempt to reset
// the read offset to the start of the footer. | [
"decodeFooter",
"seeks",
"to",
"the",
"end",
"of",
"the",
"stream",
"searches",
"for",
"the",
"footer",
"and",
"decodes",
"it",
".",
"If",
"successful",
"it",
"will",
"return",
"the",
"backSize",
"for",
"the",
"preceding",
"index",
"and",
"the",
"size",
"o... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/reader.go#L430-L483 |
9,675 | dsnet/compress | xflate/index.go | AppendRecord | func (idx *index) AppendRecord(compSize, rawSize int64, typ int) bool {
if rawSize < 0 || compSize < 0 {
return false // Invalid size
}
lastRec := idx.LastRecord()
rec := record{
CompOffset: lastRec.CompOffset + compSize,
RawOffset: lastRec.RawOffset + rawSize,
Type: typ,
}
if rec.CompOffset < lastRec.CompOffset || rec.RawOffset < lastRec.RawOffset {
return false // Overflow detected
}
idx.Records = append(idx.Records, rec)
return true
} | go | func (idx *index) AppendRecord(compSize, rawSize int64, typ int) bool {
if rawSize < 0 || compSize < 0 {
return false // Invalid size
}
lastRec := idx.LastRecord()
rec := record{
CompOffset: lastRec.CompOffset + compSize,
RawOffset: lastRec.RawOffset + rawSize,
Type: typ,
}
if rec.CompOffset < lastRec.CompOffset || rec.RawOffset < lastRec.RawOffset {
return false // Overflow detected
}
idx.Records = append(idx.Records, rec)
return true
} | [
"func",
"(",
"idx",
"*",
"index",
")",
"AppendRecord",
"(",
"compSize",
",",
"rawSize",
"int64",
",",
"typ",
"int",
")",
"bool",
"{",
"if",
"rawSize",
"<",
"0",
"||",
"compSize",
"<",
"0",
"{",
"return",
"false",
"// Invalid size",
"\n",
"}",
"\n\n",
... | // AppendRecord appends a new record to the end of the index and reports whether
// the operation was successful or not. | [
"AppendRecord",
"appends",
"a",
"new",
"record",
"to",
"the",
"end",
"of",
"the",
"index",
"and",
"reports",
"whether",
"the",
"operation",
"was",
"successful",
"or",
"not",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/index.go#L40-L56 |
9,676 | dsnet/compress | xflate/index.go | AppendIndex | func (idx *index) AppendIndex(other *index) bool {
var preRec record
for i, rec := range other.Records {
csize, rsize := rec.CompOffset-preRec.CompOffset, rec.RawOffset-preRec.RawOffset
if !idx.AppendRecord(csize, rsize, rec.Type) {
idx.Records = idx.Records[:len(idx.Records)-i] // Ensure atomic append
return false
}
preRec = rec
}
return true
} | go | func (idx *index) AppendIndex(other *index) bool {
var preRec record
for i, rec := range other.Records {
csize, rsize := rec.CompOffset-preRec.CompOffset, rec.RawOffset-preRec.RawOffset
if !idx.AppendRecord(csize, rsize, rec.Type) {
idx.Records = idx.Records[:len(idx.Records)-i] // Ensure atomic append
return false
}
preRec = rec
}
return true
} | [
"func",
"(",
"idx",
"*",
"index",
")",
"AppendIndex",
"(",
"other",
"*",
"index",
")",
"bool",
"{",
"var",
"preRec",
"record",
"\n",
"for",
"i",
",",
"rec",
":=",
"range",
"other",
".",
"Records",
"{",
"csize",
",",
"rsize",
":=",
"rec",
".",
"Comp... | // AppendIndex appends the contents of another index onto the current receiver
// and reports whether the operation was successful or not. | [
"AppendIndex",
"appends",
"the",
"contents",
"of",
"another",
"index",
"onto",
"the",
"current",
"receiver",
"and",
"reports",
"whether",
"the",
"operation",
"was",
"successful",
"or",
"not",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/index.go#L60-L71 |
9,677 | dsnet/compress | xflate/index.go | GetRecords | func (idx *index) GetRecords(i int) (prev, curr record) {
recs := idx.Records
if i > len(recs) {
i = len(recs)
}
if i-1 >= 0 && i-1 < len(recs) {
prev = recs[i-1]
}
if i >= 0 && i < len(recs) {
curr = recs[i]
} else {
curr = prev
curr.Type = unknownType
}
return prev, curr
} | go | func (idx *index) GetRecords(i int) (prev, curr record) {
recs := idx.Records
if i > len(recs) {
i = len(recs)
}
if i-1 >= 0 && i-1 < len(recs) {
prev = recs[i-1]
}
if i >= 0 && i < len(recs) {
curr = recs[i]
} else {
curr = prev
curr.Type = unknownType
}
return prev, curr
} | [
"func",
"(",
"idx",
"*",
"index",
")",
"GetRecords",
"(",
"i",
"int",
")",
"(",
"prev",
",",
"curr",
"record",
")",
"{",
"recs",
":=",
"idx",
".",
"Records",
"\n",
"if",
"i",
">",
"len",
"(",
"recs",
")",
"{",
"i",
"=",
"len",
"(",
"recs",
")... | // GetRecords returns the previous and current records at the given position.
// This method will automatically bind the search position within the bounds
// of the index. Thus, this will return zero value records if the position is
// too low, and the last record if the value is too high. | [
"GetRecords",
"returns",
"the",
"previous",
"and",
"current",
"records",
"at",
"the",
"given",
"position",
".",
"This",
"method",
"will",
"automatically",
"bind",
"the",
"search",
"position",
"within",
"the",
"bounds",
"of",
"the",
"index",
".",
"Thus",
"this"... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/index.go#L116-L131 |
9,678 | dsnet/compress | xflate/index.go | LastRecord | func (idx *index) LastRecord() record {
var rec record
if len(idx.Records) > 0 {
rec = idx.Records[len(idx.Records)-1]
}
return rec
} | go | func (idx *index) LastRecord() record {
var rec record
if len(idx.Records) > 0 {
rec = idx.Records[len(idx.Records)-1]
}
return rec
} | [
"func",
"(",
"idx",
"*",
"index",
")",
"LastRecord",
"(",
")",
"record",
"{",
"var",
"rec",
"record",
"\n",
"if",
"len",
"(",
"idx",
".",
"Records",
")",
">",
"0",
"{",
"rec",
"=",
"idx",
".",
"Records",
"[",
"len",
"(",
"idx",
".",
"Records",
... | // LastRecord returns the last record if it exists, otherwise the zero value. | [
"LastRecord",
"returns",
"the",
"last",
"record",
"if",
"it",
"exists",
"otherwise",
"the",
"zero",
"value",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/index.go#L134-L140 |
9,679 | dsnet/compress | internal/prefix/wrap.go | update | func (r *stringReader) update() {
pos, _ := r.Seek(0, io.SeekCurrent)
if off := pos - r.pos; off >= 0 && off < int64(len(r.buf)) {
r.buf, r.pos = r.buf[off:], pos
} else {
r.buf, r.pos = nil, pos
}
} | go | func (r *stringReader) update() {
pos, _ := r.Seek(0, io.SeekCurrent)
if off := pos - r.pos; off >= 0 && off < int64(len(r.buf)) {
r.buf, r.pos = r.buf[off:], pos
} else {
r.buf, r.pos = nil, pos
}
} | [
"func",
"(",
"r",
"*",
"stringReader",
")",
"update",
"(",
")",
"{",
"pos",
",",
"_",
":=",
"r",
".",
"Seek",
"(",
"0",
",",
"io",
".",
"SeekCurrent",
")",
"\n",
"if",
"off",
":=",
"pos",
"-",
"r",
".",
"pos",
";",
"off",
">=",
"0",
"&&",
"... | // update reslices the internal buffer to be consistent with the read offset. | [
"update",
"reslices",
"the",
"internal",
"buffer",
"to",
"be",
"consistent",
"with",
"the",
"read",
"offset",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/internal/prefix/wrap.go#L139-L146 |
9,680 | dsnet/compress | xflate/xflate_stats.go | computeRecords | func computeRecords(r io.Reader, lvl, chnkSize int) (strmRec indexRecord, chnkRecs []indexRecord) {
var cw1, cw2 countWriter
zw1, _ := flate.NewWriter(&cw1, lvl) // Streamed compressor
zw2, _ := flate.NewWriter(&cw2, lvl) // Chunked compressor
buf := make([]byte, chnkSize)
for {
// Read a full chunks worth of data.
cnt, err := io.ReadFull(r, buf)
strmRec.rawSize += int64(cnt)
if err == io.EOF {
break
}
// Write chunk to both compressors.
if _, err := zw1.Write(buf[:cnt]); err != nil {
log.Fatal(err)
}
if _, err := zw2.Write(buf[:cnt]); err != nil {
log.Fatal(err)
}
// Flush the chunked compressor, append the record, and reset.
if err := zw2.Flush(); err != nil {
log.Fatal(err)
}
chnkRecs = append(chnkRecs, indexRecord{rawSize: int64(cnt), compSize: int64(cw2)})
cw2 = 0
zw2.Reset(&cw2)
if err == io.ErrUnexpectedEOF {
break
}
if err != nil {
log.Fatal(err)
}
}
// Flush the streamed compressor and record the compressed size.
if err := zw1.Flush(); err != nil {
log.Fatal(err)
}
strmRec.compSize = int64(cw1)
return strmRec, chnkRecs
} | go | func computeRecords(r io.Reader, lvl, chnkSize int) (strmRec indexRecord, chnkRecs []indexRecord) {
var cw1, cw2 countWriter
zw1, _ := flate.NewWriter(&cw1, lvl) // Streamed compressor
zw2, _ := flate.NewWriter(&cw2, lvl) // Chunked compressor
buf := make([]byte, chnkSize)
for {
// Read a full chunks worth of data.
cnt, err := io.ReadFull(r, buf)
strmRec.rawSize += int64(cnt)
if err == io.EOF {
break
}
// Write chunk to both compressors.
if _, err := zw1.Write(buf[:cnt]); err != nil {
log.Fatal(err)
}
if _, err := zw2.Write(buf[:cnt]); err != nil {
log.Fatal(err)
}
// Flush the chunked compressor, append the record, and reset.
if err := zw2.Flush(); err != nil {
log.Fatal(err)
}
chnkRecs = append(chnkRecs, indexRecord{rawSize: int64(cnt), compSize: int64(cw2)})
cw2 = 0
zw2.Reset(&cw2)
if err == io.ErrUnexpectedEOF {
break
}
if err != nil {
log.Fatal(err)
}
}
// Flush the streamed compressor and record the compressed size.
if err := zw1.Flush(); err != nil {
log.Fatal(err)
}
strmRec.compSize = int64(cw1)
return strmRec, chnkRecs
} | [
"func",
"computeRecords",
"(",
"r",
"io",
".",
"Reader",
",",
"lvl",
",",
"chnkSize",
"int",
")",
"(",
"strmRec",
"indexRecord",
",",
"chnkRecs",
"[",
"]",
"indexRecord",
")",
"{",
"var",
"cw1",
",",
"cw2",
"countWriter",
"\n",
"zw1",
",",
"_",
":=",
... | // computeRecords computes the records the raw input size and the compressed
// output size. strmRec is a single record for when the input is compressed as
// a single stream. chnkRecs is a list of records for when the input is
// compressed individually as chunks. | [
"computeRecords",
"computes",
"the",
"records",
"the",
"raw",
"input",
"size",
"and",
"the",
"compressed",
"output",
"size",
".",
"strmRec",
"is",
"a",
"single",
"record",
"for",
"when",
"the",
"input",
"is",
"compressed",
"as",
"a",
"single",
"stream",
".",... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/xflate_stats.go#L236-L279 |
9,681 | dsnet/compress | xflate/xflate_stats.go | compress | func compress(b []byte, lvl int) []byte {
var buf bytes.Buffer
w, err := flate.NewWriter(&buf, lvl)
if err != nil {
log.Fatal(err)
}
if _, err := io.Copy(w, bytes.NewReader(b)); err != nil {
log.Fatal(err)
}
if err := w.Close(); err != nil {
log.Fatal(err)
}
return buf.Bytes()
} | go | func compress(b []byte, lvl int) []byte {
var buf bytes.Buffer
w, err := flate.NewWriter(&buf, lvl)
if err != nil {
log.Fatal(err)
}
if _, err := io.Copy(w, bytes.NewReader(b)); err != nil {
log.Fatal(err)
}
if err := w.Close(); err != nil {
log.Fatal(err)
}
return buf.Bytes()
} | [
"func",
"compress",
"(",
"b",
"[",
"]",
"byte",
",",
"lvl",
"int",
")",
"[",
"]",
"byte",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"w",
",",
"err",
":=",
"flate",
".",
"NewWriter",
"(",
"&",
"buf",
",",
"lvl",
")",
"\n",
"if",
"err",
... | // compress compresses the input buffer at the given level. | [
"compress",
"compresses",
"the",
"input",
"buffer",
"at",
"the",
"given",
"level",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/xflate_stats.go#L282-L295 |
9,682 | dsnet/compress | xflate/xflate_stats.go | encode | func encode(b []byte) []byte {
var buf bytes.Buffer
mw := meta.NewWriter(&buf)
mw.FinalMode = meta.FinalMeta
if _, err := io.Copy(mw, bytes.NewReader(b)); err != nil {
log.Fatal(err)
}
if err := mw.Close(); err != nil {
log.Fatal(err)
}
return buf.Bytes()
} | go | func encode(b []byte) []byte {
var buf bytes.Buffer
mw := meta.NewWriter(&buf)
mw.FinalMode = meta.FinalMeta
if _, err := io.Copy(mw, bytes.NewReader(b)); err != nil {
log.Fatal(err)
}
if err := mw.Close(); err != nil {
log.Fatal(err)
}
return buf.Bytes()
} | [
"func",
"encode",
"(",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"mw",
":=",
"meta",
".",
"NewWriter",
"(",
"&",
"buf",
")",
"\n",
"mw",
".",
"FinalMode",
"=",
"meta",
".",
"FinalMeta",
"\n",
... | // encode encodes the input using XFLATE's meta encoding. | [
"encode",
"encodes",
"the",
"input",
"using",
"XFLATE",
"s",
"meta",
"encoding",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/xflate_stats.go#L298-L309 |
9,683 | dsnet/compress | xflate/writer.go | NewWriter | func NewWriter(wr io.Writer, conf *WriterConfig) (*Writer, error) {
var lvl int
var nchk, nidx int64
if conf != nil {
lvl = conf.Level
switch {
case conf.ChunkSize < 0:
return nil, errorf(errors.Invalid, "invalid chunk size: %d", conf.ChunkSize)
case conf.ChunkSize > 0:
nchk = conf.ChunkSize
}
switch {
case conf.IndexSize < 0:
nidx = -1
case conf.IndexSize > 0:
nidx = conf.IndexSize
}
}
zw, err := newFlateWriter(wr, lvl)
if err != nil {
return nil, err
}
xw := &Writer{wr: wr, zw: zw, nchk: nchk, nidx: nidx}
xw.Reset(wr)
return xw, nil
} | go | func NewWriter(wr io.Writer, conf *WriterConfig) (*Writer, error) {
var lvl int
var nchk, nidx int64
if conf != nil {
lvl = conf.Level
switch {
case conf.ChunkSize < 0:
return nil, errorf(errors.Invalid, "invalid chunk size: %d", conf.ChunkSize)
case conf.ChunkSize > 0:
nchk = conf.ChunkSize
}
switch {
case conf.IndexSize < 0:
nidx = -1
case conf.IndexSize > 0:
nidx = conf.IndexSize
}
}
zw, err := newFlateWriter(wr, lvl)
if err != nil {
return nil, err
}
xw := &Writer{wr: wr, zw: zw, nchk: nchk, nidx: nidx}
xw.Reset(wr)
return xw, nil
} | [
"func",
"NewWriter",
"(",
"wr",
"io",
".",
"Writer",
",",
"conf",
"*",
"WriterConfig",
")",
"(",
"*",
"Writer",
",",
"error",
")",
"{",
"var",
"lvl",
"int",
"\n",
"var",
"nchk",
",",
"nidx",
"int64",
"\n",
"if",
"conf",
"!=",
"nil",
"{",
"lvl",
"... | // NewWriter creates a new Writer writing to the given writer.
// It is the caller's responsibility to call Close to complete the stream.
//
// If conf is nil, then default configuration values are used. Writer copies
// all configuration values as necessary and does not store conf. | [
"NewWriter",
"creates",
"a",
"new",
"Writer",
"writing",
"to",
"the",
"given",
"writer",
".",
"It",
"is",
"the",
"caller",
"s",
"responsibility",
"to",
"call",
"Close",
"to",
"complete",
"the",
"stream",
".",
"If",
"conf",
"is",
"nil",
"then",
"default",
... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/writer.go#L78-L104 |
9,684 | dsnet/compress | xflate/writer.go | Reset | func (xw *Writer) Reset(wr io.Writer) error {
*xw = Writer{
wr: wr,
mw: xw.mw,
zw: xw.zw,
nchk: xw.nchk,
nidx: xw.nidx,
idx: xw.idx,
}
if xw.zw == nil {
xw.zw, _ = newFlateWriter(wr, DefaultCompression)
} else {
xw.zw.Reset(wr)
}
if xw.nchk == 0 {
xw.nchk = DefaultChunkSize
}
if xw.nidx == 0 {
xw.nidx = DefaultIndexSize
}
xw.idx.Reset()
return nil
} | go | func (xw *Writer) Reset(wr io.Writer) error {
*xw = Writer{
wr: wr,
mw: xw.mw,
zw: xw.zw,
nchk: xw.nchk,
nidx: xw.nidx,
idx: xw.idx,
}
if xw.zw == nil {
xw.zw, _ = newFlateWriter(wr, DefaultCompression)
} else {
xw.zw.Reset(wr)
}
if xw.nchk == 0 {
xw.nchk = DefaultChunkSize
}
if xw.nidx == 0 {
xw.nidx = DefaultIndexSize
}
xw.idx.Reset()
return nil
} | [
"func",
"(",
"xw",
"*",
"Writer",
")",
"Reset",
"(",
"wr",
"io",
".",
"Writer",
")",
"error",
"{",
"*",
"xw",
"=",
"Writer",
"{",
"wr",
":",
"wr",
",",
"mw",
":",
"xw",
".",
"mw",
",",
"zw",
":",
"xw",
".",
"zw",
",",
"nchk",
":",
"xw",
"... | // Reset discards the Writer's state and makes it equivalent to the result
// of a call to NewWriter, but writes to wr instead. Any configurations from
// a prior call to NewWriter will be preserved.
//
// This is used to reduce memory allocations. | [
"Reset",
"discards",
"the",
"Writer",
"s",
"state",
"and",
"makes",
"it",
"equivalent",
"to",
"the",
"result",
"of",
"a",
"call",
"to",
"NewWriter",
"but",
"writes",
"to",
"wr",
"instead",
".",
"Any",
"configurations",
"from",
"a",
"prior",
"call",
"to",
... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/writer.go#L111-L133 |
9,685 | dsnet/compress | xflate/writer.go | Write | func (xw *Writer) Write(buf []byte) (int, error) {
if xw.err != nil {
return 0, xw.err
}
var n, cnt int
for len(buf) > 0 && xw.err == nil {
// Flush chunk if necessary.
remain := xw.nchk - xw.zw.InputOffset
if remain <= 0 {
xw.err = xw.Flush(FlushFull)
continue
}
if remain > int64(len(buf)) {
remain = int64(len(buf))
}
// Compress data for current chunk.
offset := xw.zw.OutputOffset
n, xw.err = xw.zw.Write(buf[:remain])
xw.OutputOffset += xw.zw.OutputOffset - offset
buf = buf[n:]
cnt += n
}
xw.InputOffset += int64(cnt)
return cnt, xw.err
} | go | func (xw *Writer) Write(buf []byte) (int, error) {
if xw.err != nil {
return 0, xw.err
}
var n, cnt int
for len(buf) > 0 && xw.err == nil {
// Flush chunk if necessary.
remain := xw.nchk - xw.zw.InputOffset
if remain <= 0 {
xw.err = xw.Flush(FlushFull)
continue
}
if remain > int64(len(buf)) {
remain = int64(len(buf))
}
// Compress data for current chunk.
offset := xw.zw.OutputOffset
n, xw.err = xw.zw.Write(buf[:remain])
xw.OutputOffset += xw.zw.OutputOffset - offset
buf = buf[n:]
cnt += n
}
xw.InputOffset += int64(cnt)
return cnt, xw.err
} | [
"func",
"(",
"xw",
"*",
"Writer",
")",
"Write",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"xw",
".",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"xw",
".",
"err",
"\n",
"}",
"\n\n",
"var",
"n",
",",
"cnt"... | // Write writes the compressed form of buf to the underlying io.Writer.
// This automatically breaks the input into multiple chunks, writes them out,
// and records the sizes of each chunk in the index table. | [
"Write",
"writes",
"the",
"compressed",
"form",
"of",
"buf",
"to",
"the",
"underlying",
"io",
".",
"Writer",
".",
"This",
"automatically",
"breaks",
"the",
"input",
"into",
"multiple",
"chunks",
"writes",
"them",
"out",
"and",
"records",
"the",
"sizes",
"of"... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/writer.go#L138-L165 |
9,686 | dsnet/compress | xflate/writer.go | Flush | func (xw *Writer) Flush(mode FlushMode) error {
if xw.err != nil {
return xw.err
}
switch mode {
case FlushSync:
offset := xw.zw.OutputOffset
xw.err = xw.zw.Flush()
xw.OutputOffset += xw.zw.OutputOffset - offset
return xw.err
case FlushFull:
if xw.err = xw.Flush(FlushSync); xw.err != nil {
return xw.err
}
xw.idx.AppendRecord(xw.zw.OutputOffset, xw.zw.InputOffset, deflateType)
xw.zw.Reset(xw.wr)
if int64(len(xw.idx.Records)) == xw.nidx {
xw.err = xw.Flush(FlushIndex)
}
return xw.err
case FlushIndex:
if xw.zw.InputOffset+xw.zw.OutputOffset > 0 {
if err := xw.Flush(FlushFull); err != nil {
return err
}
}
xw.err = xw.encodeIndex(&xw.idx)
backSize := xw.idx.IndexSize
xw.idx.Reset()
xw.idx.BackSize = backSize
return xw.err
default:
return errorf(errors.Invalid, "invalid flush mode: %d", mode)
}
} | go | func (xw *Writer) Flush(mode FlushMode) error {
if xw.err != nil {
return xw.err
}
switch mode {
case FlushSync:
offset := xw.zw.OutputOffset
xw.err = xw.zw.Flush()
xw.OutputOffset += xw.zw.OutputOffset - offset
return xw.err
case FlushFull:
if xw.err = xw.Flush(FlushSync); xw.err != nil {
return xw.err
}
xw.idx.AppendRecord(xw.zw.OutputOffset, xw.zw.InputOffset, deflateType)
xw.zw.Reset(xw.wr)
if int64(len(xw.idx.Records)) == xw.nidx {
xw.err = xw.Flush(FlushIndex)
}
return xw.err
case FlushIndex:
if xw.zw.InputOffset+xw.zw.OutputOffset > 0 {
if err := xw.Flush(FlushFull); err != nil {
return err
}
}
xw.err = xw.encodeIndex(&xw.idx)
backSize := xw.idx.IndexSize
xw.idx.Reset()
xw.idx.BackSize = backSize
return xw.err
default:
return errorf(errors.Invalid, "invalid flush mode: %d", mode)
}
} | [
"func",
"(",
"xw",
"*",
"Writer",
")",
"Flush",
"(",
"mode",
"FlushMode",
")",
"error",
"{",
"if",
"xw",
".",
"err",
"!=",
"nil",
"{",
"return",
"xw",
".",
"err",
"\n",
"}",
"\n\n",
"switch",
"mode",
"{",
"case",
"FlushSync",
":",
"offset",
":=",
... | // Flush flushes the current write buffer to the underlying writer.
// Flushing is entirely optional and should be used sparingly. | [
"Flush",
"flushes",
"the",
"current",
"write",
"buffer",
"to",
"the",
"underlying",
"writer",
".",
"Flushing",
"is",
"entirely",
"optional",
"and",
"should",
"be",
"used",
"sparingly",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/writer.go#L169-L204 |
9,687 | dsnet/compress | xflate/writer.go | Close | func (xw *Writer) Close() error {
if xw.err == errClosed {
return nil
}
if xw.err != nil {
return xw.err
}
// Flush final index.
if xw.zw.OutputOffset+xw.zw.InputOffset > 0 || len(xw.idx.Records) > 0 {
xw.err = xw.Flush(FlushIndex)
if xw.err != nil {
return xw.err
}
}
// Encode the footer.
err := xw.encodeFooter(xw.idx.BackSize)
if err != nil {
xw.err = err
} else {
xw.err = errClosed
}
return err
} | go | func (xw *Writer) Close() error {
if xw.err == errClosed {
return nil
}
if xw.err != nil {
return xw.err
}
// Flush final index.
if xw.zw.OutputOffset+xw.zw.InputOffset > 0 || len(xw.idx.Records) > 0 {
xw.err = xw.Flush(FlushIndex)
if xw.err != nil {
return xw.err
}
}
// Encode the footer.
err := xw.encodeFooter(xw.idx.BackSize)
if err != nil {
xw.err = err
} else {
xw.err = errClosed
}
return err
} | [
"func",
"(",
"xw",
"*",
"Writer",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"xw",
".",
"err",
"==",
"errClosed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"xw",
".",
"err",
"!=",
"nil",
"{",
"return",
"xw",
".",
"err",
"\n",
"}",
"\n\n",
... | // Close ends the XFLATE stream and flushes all buffered data.
// This method automatically writes an index if any chunks have been written
// since the last FlushIndex. | [
"Close",
"ends",
"the",
"XFLATE",
"stream",
"and",
"flushes",
"all",
"buffered",
"data",
".",
"This",
"method",
"automatically",
"writes",
"an",
"index",
"if",
"any",
"chunks",
"have",
"been",
"written",
"since",
"the",
"last",
"FlushIndex",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/writer.go#L209-L233 |
9,688 | dsnet/compress | xflate/writer.go | encodeIndex | func (xw *Writer) encodeIndex(index *index) error {
// Helper function to write VLIs.
var crc uint32
var errVLI error
writeVLI := func(x int64) {
b := xw.scratch[:binary.PutUvarint(xw.scratch[:], uint64(x))]
crc = crc32.Update(crc, crc32.MakeTable(crc32.IEEE), b)
if _, err := xw.mw.Write(b); err != nil {
errVLI = errWrap(err)
}
}
// Write the index.
xw.mw.Reset(xw.wr)
defer func() { xw.OutputOffset += xw.mw.OutputOffset }()
xw.mw.FinalMode = meta.FinalMeta
writeVLI(index.BackSize)
writeVLI(int64(len(index.Records)))
writeVLI(index.LastRecord().CompOffset)
writeVLI(index.LastRecord().RawOffset)
var preRec record
for _, rec := range index.Records {
writeVLI(rec.CompOffset - preRec.CompOffset)
writeVLI(rec.RawOffset - preRec.RawOffset)
preRec = rec
}
if errVLI != nil {
return errWrap(errVLI)
}
binary.LittleEndian.PutUint32(xw.scratch[:], crc)
if _, err := xw.mw.Write(xw.scratch[:4]); err != nil {
return errWrap(err)
}
if err := xw.mw.Close(); err != nil {
return errWrap(err)
}
index.IndexSize = xw.mw.OutputOffset // Record the encoded size
return nil
} | go | func (xw *Writer) encodeIndex(index *index) error {
// Helper function to write VLIs.
var crc uint32
var errVLI error
writeVLI := func(x int64) {
b := xw.scratch[:binary.PutUvarint(xw.scratch[:], uint64(x))]
crc = crc32.Update(crc, crc32.MakeTable(crc32.IEEE), b)
if _, err := xw.mw.Write(b); err != nil {
errVLI = errWrap(err)
}
}
// Write the index.
xw.mw.Reset(xw.wr)
defer func() { xw.OutputOffset += xw.mw.OutputOffset }()
xw.mw.FinalMode = meta.FinalMeta
writeVLI(index.BackSize)
writeVLI(int64(len(index.Records)))
writeVLI(index.LastRecord().CompOffset)
writeVLI(index.LastRecord().RawOffset)
var preRec record
for _, rec := range index.Records {
writeVLI(rec.CompOffset - preRec.CompOffset)
writeVLI(rec.RawOffset - preRec.RawOffset)
preRec = rec
}
if errVLI != nil {
return errWrap(errVLI)
}
binary.LittleEndian.PutUint32(xw.scratch[:], crc)
if _, err := xw.mw.Write(xw.scratch[:4]); err != nil {
return errWrap(err)
}
if err := xw.mw.Close(); err != nil {
return errWrap(err)
}
index.IndexSize = xw.mw.OutputOffset // Record the encoded size
return nil
} | [
"func",
"(",
"xw",
"*",
"Writer",
")",
"encodeIndex",
"(",
"index",
"*",
"index",
")",
"error",
"{",
"// Helper function to write VLIs.",
"var",
"crc",
"uint32",
"\n",
"var",
"errVLI",
"error",
"\n",
"writeVLI",
":=",
"func",
"(",
"x",
"int64",
")",
"{",
... | // encodeIndex encodes the index into a meta encoded stream.
// The index.Records and index.BackSize fields must be populated.
// The index.IndexSize field will be populated upon successful write. | [
"encodeIndex",
"encodes",
"the",
"index",
"into",
"a",
"meta",
"encoded",
"stream",
".",
"The",
"index",
".",
"Records",
"and",
"index",
".",
"BackSize",
"fields",
"must",
"be",
"populated",
".",
"The",
"index",
".",
"IndexSize",
"field",
"will",
"be",
"po... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/writer.go#L238-L277 |
9,689 | dsnet/compress | xflate/writer.go | encodeFooter | func (xw *Writer) encodeFooter(backSize int64) error {
var n int
n += copy(xw.scratch[n:], magic[:])
n += binary.PutUvarint(xw.scratch[n:], uint64(backSize))
xw.mw.Reset(xw.wr)
defer func() { xw.OutputOffset += xw.mw.OutputOffset }()
xw.mw.FinalMode = meta.FinalStream
if _, err := xw.mw.Write(xw.scratch[:n]); err != nil {
return errWrap(err)
}
if err := xw.mw.Close(); err != nil {
return errWrap(err)
}
if xw.mw.NumBlocks != 1 {
return errorf(errors.Internal, "footer was not a single block")
}
return nil
} | go | func (xw *Writer) encodeFooter(backSize int64) error {
var n int
n += copy(xw.scratch[n:], magic[:])
n += binary.PutUvarint(xw.scratch[n:], uint64(backSize))
xw.mw.Reset(xw.wr)
defer func() { xw.OutputOffset += xw.mw.OutputOffset }()
xw.mw.FinalMode = meta.FinalStream
if _, err := xw.mw.Write(xw.scratch[:n]); err != nil {
return errWrap(err)
}
if err := xw.mw.Close(); err != nil {
return errWrap(err)
}
if xw.mw.NumBlocks != 1 {
return errorf(errors.Internal, "footer was not a single block")
}
return nil
} | [
"func",
"(",
"xw",
"*",
"Writer",
")",
"encodeFooter",
"(",
"backSize",
"int64",
")",
"error",
"{",
"var",
"n",
"int",
"\n",
"n",
"+=",
"copy",
"(",
"xw",
".",
"scratch",
"[",
"n",
":",
"]",
",",
"magic",
"[",
":",
"]",
")",
"\n",
"n",
"+=",
... | // encodeFooter writes the final footer, encoding the provided backSize into it. | [
"encodeFooter",
"writes",
"the",
"final",
"footer",
"encoding",
"the",
"provided",
"backSize",
"into",
"it",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/writer.go#L280-L298 |
9,690 | dsnet/compress | xflate/internal/meta/writer.go | NewWriter | func NewWriter(wr io.Writer) *Writer {
mw := new(Writer)
mw.Reset(wr)
return mw
} | go | func NewWriter(wr io.Writer) *Writer {
mw := new(Writer)
mw.Reset(wr)
return mw
} | [
"func",
"NewWriter",
"(",
"wr",
"io",
".",
"Writer",
")",
"*",
"Writer",
"{",
"mw",
":=",
"new",
"(",
"Writer",
")",
"\n",
"mw",
".",
"Reset",
"(",
"wr",
")",
"\n",
"return",
"mw",
"\n",
"}"
] | // NewWriter creates a new Writer writing to the given writer.
// It is the caller's responsibility to call Close to complete the meta stream. | [
"NewWriter",
"creates",
"a",
"new",
"Writer",
"writing",
"to",
"the",
"given",
"writer",
".",
"It",
"is",
"the",
"caller",
"s",
"responsibility",
"to",
"call",
"Close",
"to",
"complete",
"the",
"meta",
"stream",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/writer.go#L40-L44 |
9,691 | dsnet/compress | xflate/internal/meta/writer.go | Reset | func (mw *Writer) Reset(wr io.Writer) {
*mw = Writer{
wr: wr,
bw: mw.bw,
bb: mw.bb,
cnts: mw.cnts,
}
return
} | go | func (mw *Writer) Reset(wr io.Writer) {
*mw = Writer{
wr: wr,
bw: mw.bw,
bb: mw.bb,
cnts: mw.cnts,
}
return
} | [
"func",
"(",
"mw",
"*",
"Writer",
")",
"Reset",
"(",
"wr",
"io",
".",
"Writer",
")",
"{",
"*",
"mw",
"=",
"Writer",
"{",
"wr",
":",
"wr",
",",
"bw",
":",
"mw",
".",
"bw",
",",
"bb",
":",
"mw",
".",
"bb",
",",
"cnts",
":",
"mw",
".",
"cnts... | // Reset discards the Writer's state and makes it equivalent to the result
// of a call to NewWriter, but writes to wr instead.
//
// This is used to reduce memory allocations. | [
"Reset",
"discards",
"the",
"Writer",
"s",
"state",
"and",
"makes",
"it",
"equivalent",
"to",
"the",
"result",
"of",
"a",
"call",
"to",
"NewWriter",
"but",
"writes",
"to",
"wr",
"instead",
".",
"This",
"is",
"used",
"to",
"reduce",
"memory",
"allocations",... | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/writer.go#L50-L58 |
9,692 | dsnet/compress | xflate/internal/meta/writer.go | Write | func (mw *Writer) Write(buf []byte) (int, error) {
if mw.err != nil {
return 0, mw.err
}
var wrCnt int
for _, b := range buf {
zeros, ones := numBits(b)
// If possible, avoid flushing to maintain high efficiency.
if ensured := mw.bufCnt < EnsureRawBytes; ensured {
goto skipEncode
}
if huffLen, _ := mw.computeHuffLen(mw.buf0s+zeros, mw.buf1s+ones); huffLen > 0 {
goto skipEncode
}
mw.err = mw.encodeBlock(FinalNil)
if mw.err != nil {
break
}
skipEncode:
mw.buf0s += zeros
mw.buf1s += ones
mw.buf[mw.bufCnt] = b
mw.bufCnt++
wrCnt++
}
mw.InputOffset += int64(wrCnt)
return wrCnt, mw.err
} | go | func (mw *Writer) Write(buf []byte) (int, error) {
if mw.err != nil {
return 0, mw.err
}
var wrCnt int
for _, b := range buf {
zeros, ones := numBits(b)
// If possible, avoid flushing to maintain high efficiency.
if ensured := mw.bufCnt < EnsureRawBytes; ensured {
goto skipEncode
}
if huffLen, _ := mw.computeHuffLen(mw.buf0s+zeros, mw.buf1s+ones); huffLen > 0 {
goto skipEncode
}
mw.err = mw.encodeBlock(FinalNil)
if mw.err != nil {
break
}
skipEncode:
mw.buf0s += zeros
mw.buf1s += ones
mw.buf[mw.bufCnt] = b
mw.bufCnt++
wrCnt++
}
mw.InputOffset += int64(wrCnt)
return wrCnt, mw.err
} | [
"func",
"(",
"mw",
"*",
"Writer",
")",
"Write",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"mw",
".",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"mw",
".",
"err",
"\n",
"}",
"\n\n",
"var",
"wrCnt",
"int",
... | // Write writes the encoded form of buf to the underlying io.Writer.
// The Writer may buffer the input in order to produce larger meta blocks. | [
"Write",
"writes",
"the",
"encoded",
"form",
"of",
"buf",
"to",
"the",
"underlying",
"io",
".",
"Writer",
".",
"The",
"Writer",
"may",
"buffer",
"the",
"input",
"in",
"order",
"to",
"produce",
"larger",
"meta",
"blocks",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/writer.go#L62-L94 |
9,693 | dsnet/compress | xflate/internal/meta/writer.go | Close | func (mw *Writer) Close() error {
if mw.err == errClosed {
return nil
}
if mw.err != nil {
return mw.err
}
err := mw.encodeBlock(mw.FinalMode)
if err != nil {
mw.err = err
} else {
mw.err = errClosed
}
mw.wr = nil // Release reference to underlying Writer
return err
} | go | func (mw *Writer) Close() error {
if mw.err == errClosed {
return nil
}
if mw.err != nil {
return mw.err
}
err := mw.encodeBlock(mw.FinalMode)
if err != nil {
mw.err = err
} else {
mw.err = errClosed
}
mw.wr = nil // Release reference to underlying Writer
return err
} | [
"func",
"(",
"mw",
"*",
"Writer",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"mw",
".",
"err",
"==",
"errClosed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"mw",
".",
"err",
"!=",
"nil",
"{",
"return",
"mw",
".",
"err",
"\n",
"}",
"\n\n",
... | // Close ends the meta stream and flushes all buffered data.
// The desired FinalMode must be set prior to calling Close. | [
"Close",
"ends",
"the",
"meta",
"stream",
"and",
"flushes",
"all",
"buffered",
"data",
".",
"The",
"desired",
"FinalMode",
"must",
"be",
"set",
"prior",
"to",
"calling",
"Close",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/xflate/internal/meta/writer.go#L98-L114 |
9,694 | dsnet/compress | bzip2/common.go | update | func (c *crc) update(buf []byte) {
cval := internal.ReverseUint32(c.val)
for len(buf) > 0 {
n := len(buf)
if n > len(c.buf) {
n = len(c.buf)
}
for i, b := range buf[:n] {
c.buf[i] = internal.ReverseLUT[b]
}
cval = crc32.Update(cval, crc32.IEEETable, c.buf[:n])
buf = buf[n:]
}
c.val = internal.ReverseUint32(cval)
} | go | func (c *crc) update(buf []byte) {
cval := internal.ReverseUint32(c.val)
for len(buf) > 0 {
n := len(buf)
if n > len(c.buf) {
n = len(c.buf)
}
for i, b := range buf[:n] {
c.buf[i] = internal.ReverseLUT[b]
}
cval = crc32.Update(cval, crc32.IEEETable, c.buf[:n])
buf = buf[n:]
}
c.val = internal.ReverseUint32(cval)
} | [
"func",
"(",
"c",
"*",
"crc",
")",
"update",
"(",
"buf",
"[",
"]",
"byte",
")",
"{",
"cval",
":=",
"internal",
".",
"ReverseUint32",
"(",
"c",
".",
"val",
")",
"\n",
"for",
"len",
"(",
"buf",
")",
">",
"0",
"{",
"n",
":=",
"len",
"(",
"buf",
... | // update computes the CRC-32 of appending buf to c. | [
"update",
"computes",
"the",
"CRC",
"-",
"32",
"of",
"appending",
"buf",
"to",
"c",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/bzip2/common.go#L96-L110 |
9,695 | dsnet/compress | flate/reader.go | readBlockHeader | func (zr *Reader) readBlockHeader() {
zr.last = zr.rd.ReadBits(1) == 1
switch zr.rd.ReadBits(2) {
case 0:
// Raw block (RFC section 3.2.4).
zr.rd.ReadPads()
n := uint16(zr.rd.ReadBits(16))
nn := uint16(zr.rd.ReadBits(16))
if n^nn != 0xffff {
panicf(errors.Corrupted, "raw block size mismatch")
}
zr.blkLen = int(n)
// By convention, an empty block flushes the read buffer.
if zr.blkLen == 0 {
zr.toRead = zr.dict.ReadFlush()
zr.finishBlock()
return
}
zr.step = (*Reader).readRawData
case 1:
// Fixed prefix block (RFC section 3.2.6).
zr.litTree, zr.distTree = &decLit, &decDist
zr.step = (*Reader).readBlock
case 2:
// Dynamic prefix block (RFC section 3.2.7).
zr.litTree, zr.distTree = &zr.pd1, &zr.pd2
zr.rd.ReadPrefixCodes(zr.litTree, zr.distTree)
zr.step = (*Reader).readBlock
default:
// Reserved block (RFC section 3.2.3).
panicf(errors.Corrupted, "encountered reserved block")
}
} | go | func (zr *Reader) readBlockHeader() {
zr.last = zr.rd.ReadBits(1) == 1
switch zr.rd.ReadBits(2) {
case 0:
// Raw block (RFC section 3.2.4).
zr.rd.ReadPads()
n := uint16(zr.rd.ReadBits(16))
nn := uint16(zr.rd.ReadBits(16))
if n^nn != 0xffff {
panicf(errors.Corrupted, "raw block size mismatch")
}
zr.blkLen = int(n)
// By convention, an empty block flushes the read buffer.
if zr.blkLen == 0 {
zr.toRead = zr.dict.ReadFlush()
zr.finishBlock()
return
}
zr.step = (*Reader).readRawData
case 1:
// Fixed prefix block (RFC section 3.2.6).
zr.litTree, zr.distTree = &decLit, &decDist
zr.step = (*Reader).readBlock
case 2:
// Dynamic prefix block (RFC section 3.2.7).
zr.litTree, zr.distTree = &zr.pd1, &zr.pd2
zr.rd.ReadPrefixCodes(zr.litTree, zr.distTree)
zr.step = (*Reader).readBlock
default:
// Reserved block (RFC section 3.2.3).
panicf(errors.Corrupted, "encountered reserved block")
}
} | [
"func",
"(",
"zr",
"*",
"Reader",
")",
"readBlockHeader",
"(",
")",
"{",
"zr",
".",
"last",
"=",
"zr",
".",
"rd",
".",
"ReadBits",
"(",
"1",
")",
"==",
"1",
"\n",
"switch",
"zr",
".",
"rd",
".",
"ReadBits",
"(",
"2",
")",
"{",
"case",
"0",
":... | // readBlockHeader reads the block header according to RFC section 3.2.3. | [
"readBlockHeader",
"reads",
"the",
"block",
"header",
"according",
"to",
"RFC",
"section",
"3",
".",
"2",
".",
"3",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/flate/reader.go#L100-L134 |
9,696 | dsnet/compress | flate/reader.go | readRawData | func (zr *Reader) readRawData() {
buf := zr.dict.WriteSlice()
if len(buf) > zr.blkLen {
buf = buf[:zr.blkLen]
}
cnt, err := zr.rd.Read(buf)
zr.blkLen -= cnt
zr.dict.WriteMark(cnt)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
errors.Panic(err)
}
if zr.blkLen > 0 {
zr.toRead = zr.dict.ReadFlush()
zr.step = (*Reader).readRawData // We need to continue this work
return
}
zr.finishBlock()
} | go | func (zr *Reader) readRawData() {
buf := zr.dict.WriteSlice()
if len(buf) > zr.blkLen {
buf = buf[:zr.blkLen]
}
cnt, err := zr.rd.Read(buf)
zr.blkLen -= cnt
zr.dict.WriteMark(cnt)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
errors.Panic(err)
}
if zr.blkLen > 0 {
zr.toRead = zr.dict.ReadFlush()
zr.step = (*Reader).readRawData // We need to continue this work
return
}
zr.finishBlock()
} | [
"func",
"(",
"zr",
"*",
"Reader",
")",
"readRawData",
"(",
")",
"{",
"buf",
":=",
"zr",
".",
"dict",
".",
"WriteSlice",
"(",
")",
"\n",
"if",
"len",
"(",
"buf",
")",
">",
"zr",
".",
"blkLen",
"{",
"buf",
"=",
"buf",
"[",
":",
"zr",
".",
"blkL... | // readRawData reads raw data according to RFC section 3.2.4. | [
"readRawData",
"reads",
"raw",
"data",
"according",
"to",
"RFC",
"section",
"3",
".",
"2",
".",
"4",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/flate/reader.go#L137-L159 |
9,697 | dsnet/compress | flate/reader.go | readBlock | func (zr *Reader) readBlock() {
const (
stateInit = iota // Zero value must be stateInit
stateDict
)
switch zr.stepState {
case stateInit:
goto readLiteral
case stateDict:
goto copyDistance
}
readLiteral:
// Read literal and/or (length, distance) according to RFC section 3.2.3.
{
if zr.dict.AvailSize() == 0 {
zr.toRead = zr.dict.ReadFlush()
zr.step = (*Reader).readBlock
zr.stepState = stateInit // Need to continue work here
return
}
// Read the literal symbol.
litSym, ok := zr.rd.TryReadSymbol(zr.litTree)
if !ok {
litSym = zr.rd.ReadSymbol(zr.litTree)
}
switch {
case litSym < endBlockSym:
zr.dict.WriteByte(byte(litSym))
goto readLiteral
case litSym == endBlockSym:
zr.finishBlock()
zr.stepState = stateInit // Next call to readBlock must start here
return
case litSym < maxNumLitSyms:
// Decode the copy length.
rec := lenRanges[litSym-257]
extra, ok := zr.rd.TryReadBits(uint(rec.Len))
if !ok {
extra = zr.rd.ReadBits(uint(rec.Len))
}
zr.cpyLen = int(rec.Base) + int(extra)
// Read the distance symbol.
distSym, ok := zr.rd.TryReadSymbol(zr.distTree)
if !ok {
distSym = zr.rd.ReadSymbol(zr.distTree)
}
if distSym >= maxNumDistSyms {
panicf(errors.Corrupted, "invalid distance symbol: %d", distSym)
}
// Decode the copy distance.
rec = distRanges[distSym]
extra, ok = zr.rd.TryReadBits(uint(rec.Len))
if !ok {
extra = zr.rd.ReadBits(uint(rec.Len))
}
zr.dist = int(rec.Base) + int(extra)
if zr.dist > zr.dict.HistSize() {
panicf(errors.Corrupted, "copy distance exceeds window history")
}
goto copyDistance
default:
panicf(errors.Corrupted, "invalid literal symbol: %d", litSym)
}
}
copyDistance:
// Perform a backwards copy according to RFC section 3.2.3.
{
cnt := zr.dict.TryWriteCopy(zr.dist, zr.cpyLen)
if cnt == 0 {
cnt = zr.dict.WriteCopy(zr.dist, zr.cpyLen)
}
zr.cpyLen -= cnt
if zr.cpyLen > 0 {
zr.toRead = zr.dict.ReadFlush()
zr.step = (*Reader).readBlock
zr.stepState = stateDict // Need to continue work here
return
}
goto readLiteral
}
} | go | func (zr *Reader) readBlock() {
const (
stateInit = iota // Zero value must be stateInit
stateDict
)
switch zr.stepState {
case stateInit:
goto readLiteral
case stateDict:
goto copyDistance
}
readLiteral:
// Read literal and/or (length, distance) according to RFC section 3.2.3.
{
if zr.dict.AvailSize() == 0 {
zr.toRead = zr.dict.ReadFlush()
zr.step = (*Reader).readBlock
zr.stepState = stateInit // Need to continue work here
return
}
// Read the literal symbol.
litSym, ok := zr.rd.TryReadSymbol(zr.litTree)
if !ok {
litSym = zr.rd.ReadSymbol(zr.litTree)
}
switch {
case litSym < endBlockSym:
zr.dict.WriteByte(byte(litSym))
goto readLiteral
case litSym == endBlockSym:
zr.finishBlock()
zr.stepState = stateInit // Next call to readBlock must start here
return
case litSym < maxNumLitSyms:
// Decode the copy length.
rec := lenRanges[litSym-257]
extra, ok := zr.rd.TryReadBits(uint(rec.Len))
if !ok {
extra = zr.rd.ReadBits(uint(rec.Len))
}
zr.cpyLen = int(rec.Base) + int(extra)
// Read the distance symbol.
distSym, ok := zr.rd.TryReadSymbol(zr.distTree)
if !ok {
distSym = zr.rd.ReadSymbol(zr.distTree)
}
if distSym >= maxNumDistSyms {
panicf(errors.Corrupted, "invalid distance symbol: %d", distSym)
}
// Decode the copy distance.
rec = distRanges[distSym]
extra, ok = zr.rd.TryReadBits(uint(rec.Len))
if !ok {
extra = zr.rd.ReadBits(uint(rec.Len))
}
zr.dist = int(rec.Base) + int(extra)
if zr.dist > zr.dict.HistSize() {
panicf(errors.Corrupted, "copy distance exceeds window history")
}
goto copyDistance
default:
panicf(errors.Corrupted, "invalid literal symbol: %d", litSym)
}
}
copyDistance:
// Perform a backwards copy according to RFC section 3.2.3.
{
cnt := zr.dict.TryWriteCopy(zr.dist, zr.cpyLen)
if cnt == 0 {
cnt = zr.dict.WriteCopy(zr.dist, zr.cpyLen)
}
zr.cpyLen -= cnt
if zr.cpyLen > 0 {
zr.toRead = zr.dict.ReadFlush()
zr.step = (*Reader).readBlock
zr.stepState = stateDict // Need to continue work here
return
}
goto readLiteral
}
} | [
"func",
"(",
"zr",
"*",
"Reader",
")",
"readBlock",
"(",
")",
"{",
"const",
"(",
"stateInit",
"=",
"iota",
"// Zero value must be stateInit",
"\n",
"stateDict",
"\n",
")",
"\n\n",
"switch",
"zr",
".",
"stepState",
"{",
"case",
"stateInit",
":",
"goto",
"re... | // readCommands reads block commands according to RFC section 3.2.3. | [
"readCommands",
"reads",
"block",
"commands",
"according",
"to",
"RFC",
"section",
"3",
".",
"2",
".",
"3",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/flate/reader.go#L162-L250 |
9,698 | dsnet/compress | flate/reader.go | finishBlock | func (zr *Reader) finishBlock() {
if zr.last {
zr.rd.ReadPads()
zr.err = io.EOF
}
zr.step = (*Reader).readBlockHeader
} | go | func (zr *Reader) finishBlock() {
if zr.last {
zr.rd.ReadPads()
zr.err = io.EOF
}
zr.step = (*Reader).readBlockHeader
} | [
"func",
"(",
"zr",
"*",
"Reader",
")",
"finishBlock",
"(",
")",
"{",
"if",
"zr",
".",
"last",
"{",
"zr",
".",
"rd",
".",
"ReadPads",
"(",
")",
"\n",
"zr",
".",
"err",
"=",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"zr",
".",
"step",
"=",
"(",
"*",... | // finishBlock checks if we have hit io.EOF. | [
"finishBlock",
"checks",
"if",
"we",
"have",
"hit",
"io",
".",
"EOF",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/flate/reader.go#L253-L259 |
9,699 | dsnet/compress | brotli/bit_reader.go | FlushOffset | func (br *bitReader) FlushOffset() int64 {
if br.bufRd == nil {
return br.offset
}
// Update the number of total bits to discard.
br.discardBits += int(br.fedBits - br.numBits)
br.fedBits = br.numBits
// Discard some bytes to update read offset.
nd := (br.discardBits + 7) / 8 // Round up to nearest byte
nd, _ = br.bufRd.Discard(nd)
br.discardBits -= nd * 8 // -7..0
br.offset += int64(nd)
// These are invalid after Discard.
br.bufPeek = nil
return br.offset
} | go | func (br *bitReader) FlushOffset() int64 {
if br.bufRd == nil {
return br.offset
}
// Update the number of total bits to discard.
br.discardBits += int(br.fedBits - br.numBits)
br.fedBits = br.numBits
// Discard some bytes to update read offset.
nd := (br.discardBits + 7) / 8 // Round up to nearest byte
nd, _ = br.bufRd.Discard(nd)
br.discardBits -= nd * 8 // -7..0
br.offset += int64(nd)
// These are invalid after Discard.
br.bufPeek = nil
return br.offset
} | [
"func",
"(",
"br",
"*",
"bitReader",
")",
"FlushOffset",
"(",
")",
"int64",
"{",
"if",
"br",
".",
"bufRd",
"==",
"nil",
"{",
"return",
"br",
".",
"offset",
"\n",
"}",
"\n\n",
"// Update the number of total bits to discard.",
"br",
".",
"discardBits",
"+=",
... | // FlushOffset updates the read offset of the underlying byteReader.
// If the byteReader is a bufio.Reader, then this calls Discard to update the
// read offset. | [
"FlushOffset",
"updates",
"the",
"read",
"offset",
"of",
"the",
"underlying",
"byteReader",
".",
"If",
"the",
"byteReader",
"is",
"a",
"bufio",
".",
"Reader",
"then",
"this",
"calls",
"Discard",
"to",
"update",
"the",
"read",
"offset",
"."
] | da652975a8eea9fa0735aba8056747a751db0bd3 | https://github.com/dsnet/compress/blob/da652975a8eea9fa0735aba8056747a751db0bd3/brotli/bit_reader.go#L61-L79 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.