func ModuleHostname(c context.Context, module, version, instance string) (string, error) {
	req := &modpb.GetHostnameRequest{}
	if module != "" {
		req.Module = &module
	}
	if version != "" {
		req.Version = &version
	}
	if instance != "" {
		req.Instance = &instance
	}
	res := &modpb.GetHostnameResponse{}
	if err := internal.Call(c, "modules", "GetHostname", req, res); err != nil {
		return "", err
	}
	return *res.Hostname, nil
}

func ModuleHostname ( c context . Context , module , version , instance string ) ( string , error ) { req := & modpb . GetHostnameRequest { } if module != " " { req . Module = & module } if version != " " { req . Version = & version } if instance != " " { req . Instance = & instance } res := & modpb . GetHostnameResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return " " , err } return * res . Hostname , nil }

// ModuleHostname returns a hostname of a module instance.
// If module is the empty string, it refers to the module of the current instance.
// If version is empty, it refers to the version of the current instance if valid,
// or the default version of the module of the current instance.
// If instance is empty, ModuleHostname returns the load-balancing hostname.

ModuleHostname returns a hostname of a module instance . If module is the empty string it refers to the module of the current instance . If version is empty it refers to the version of the current instance if valid or the default version of the module of the current instance . If instance is empty ModuleHostname returns the load - balancing hostname .


func AccessToken(c context.Context, scopes ...string) (token string, expiry time.Time, err error) {
	req := &pb.GetAccessTokenRequest{Scope: scopes}
	res := &pb.GetAccessTokenResponse{}

	err = internal.Call(c, "app_identity_service", "GetAccessToken", req, res)
	if err != nil {
		return "", time.Time{}, err
	}
	return res.GetAccessToken(), time.Unix(res.GetExpirationTime(), 0), nil
}

func AccessToken ( c context . Context , scopes ... string ) ( token string , expiry time . Time , err error ) { req := & pb . GetAccessTokenRequest { Scope : scopes } res := & pb . GetAccessTokenResponse { } err = internal . Call ( c , " " , " " , req , res ) if err != nil { return " " , time . Time { } , err } return res . GetAccessToken ( ) , time . Unix ( res . GetExpirationTime ( ) , 0 ) , nil }

// AccessToken generates an OAuth2 access token for the specified scopes on
// behalf of service account of this application. This token will expire after
// the returned time.

AccessToken generates an OAuth2 access token for the specified scopes on behalf of service account of this application . This token will expire after the returned time .


func PublicCertificates(c context.Context) ([]Certificate, error) {
	req := &pb.GetPublicCertificateForAppRequest{}
	res := &pb.GetPublicCertificateForAppResponse{}
	if err := internal.Call(c, "app_identity_service", "GetPublicCertificatesForApp", req, res); err != nil {
		return nil, err
	}
	var cs []Certificate
	for _, pc := range res.PublicCertificateList {
		cs = append(cs, Certificate{
			KeyName: pc.GetKeyName(),
			Data:    []byte(pc.GetX509CertificatePem()),
		})
	}
	return cs, nil
}

func PublicCertificates ( c context . Context ) ( [ ] Certificate , error ) { req := & pb . GetPublicCertificateForAppRequest { } res := & pb . GetPublicCertificateForAppResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return nil , err } var cs [ ] Certificate for _ , pc := range res . PublicCertificateList { cs = append ( cs , Certificate { KeyName : pc . GetKeyName ( ) , Data : [ ] byte ( pc . GetX509CertificatePem ( ) ) , } ) } return cs , nil }

// PublicCertificates retrieves the public certificates for the app.
// They can be used to verify a signature returned by SignBytes.

PublicCertificates retrieves the public certificates for the app . They can be used to verify a signature returned by SignBytes .


func ServiceAccount(c context.Context) (string, error) {
	req := &pb.GetServiceAccountNameRequest{}
	res := &pb.GetServiceAccountNameResponse{}

	err := internal.Call(c, "app_identity_service", "GetServiceAccountName", req, res)
	if err != nil {
		return "", err
	}
	return res.GetServiceAccountName(), err
}

func ServiceAccount ( c context . Context ) ( string , error ) { req := & pb . GetServiceAccountNameRequest { } res := & pb . GetServiceAccountNameResponse { } err := internal . Call ( c , " " , " " , req , res ) if err != nil { return " " , err } return res . GetServiceAccountName ( ) , err }

// ServiceAccount returns a string representing the service account name, in
// the form of an email address (typically app_id@appspot.gserviceaccount.com).

ServiceAccount returns a string representing the service account name in the form of an email address ( typically app_id


func SignBytes(c context.Context, bytes []byte) (keyName string, signature []byte, err error) {
	req := &pb.SignForAppRequest{BytesToSign: bytes}
	res := &pb.SignForAppResponse{}

	if err := internal.Call(c, "app_identity_service", "SignForApp", req, res); err != nil {
		return "", nil, err
	}
	return res.GetKeyName(), res.GetSignatureBytes(), nil
}

func SignBytes ( c context . Context , bytes [ ] byte ) ( keyName string , signature [ ] byte , err error ) { req := & pb . SignForAppRequest { BytesToSign : bytes } res := & pb . SignForAppResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return " " , nil , err } return res . GetKeyName ( ) , res . GetSignatureBytes ( ) , nil }

// SignBytes signs bytes using a private key unique to your application.

SignBytes signs bytes using a private key unique to your application .


func (r *reader) fetch(off int64) error {
	req := &blobpb.FetchDataRequest{
		BlobKey:    proto.String(string(r.blobKey)),
		StartIndex: proto.Int64(off),
		EndIndex:   proto.Int64(off + readBufferSize - 1), // EndIndex is inclusive.
	}
	res := &blobpb.FetchDataResponse{}
	if err := internal.Call(r.c, "blobstore", "FetchData", req, res); err != nil {
		return err
	}
	if len(res.Data) == 0 {
		return io.EOF
	}
	r.buf, r.r, r.off = res.Data, 0, off
	return nil
}

func
(
r
*
reader
)
fetch
(
off
int64
)
error
{
req
:=
&
blobpb
.
FetchDataRequest
{
BlobKey
:
proto
.
String
(
string
(
r
.
blobKey
)
)
,
StartIndex
:
proto
.
Int64
(
off
)
,
EndIndex
:
proto
.
Int64
(
off
+
readBufferSize
1
)
,
// EndIndex is inclusive.
}
res
:=
&
blobpb
.
FetchDataResponse
{
}
if
err
:=
internal
.
Call
(
r
.
c
,
"
"
,
"
"
,
req
,
res
)
;
err
!=
{
return
err
}
if
len
(
res
.
Data
)
==
0
{
return
io
.
EOF
}
r
.
buf
,
r
.
r
,
r
.
off
=
res
.
Data
,
0
,
off
return
}

// fetch fetches readBufferSize bytes starting at the given offset. On success,
// the data is saved as r.buf.

fetch fetches readBufferSize bytes starting at the given offset . On success the data is saved as r . buf .


func (r *reader) seek(off int64) (int64, error) {
	delta := off - r.off
	if delta >= 0 && delta < int64(len(r.buf)) {
		r.r = int(delta)
		return off, nil
	}
	r.buf, r.r, r.off = nil, 0, off
	return off, nil
}

func ( r * reader ) seek ( off int64 ) ( int64 , error ) { delta := off - r . off if delta >= 0 && delta < int64 ( len ( r . buf ) ) { r . r = int ( delta ) return off , nil } r . buf , r . r , r . off = nil , 0 , off return off , nil }

// seek seeks to the given offset with an effective whence equal to SEEK_SET.
// It discards the read buffer if the invariant cannot be maintained.

seek seeks to the given offset with an effective whence equal to SEEK_SET . It discards the read buffer if the invariant cannot be maintained .


func multiKeyToProto(appID string, key []*Key) []*pb.Reference {
	ret := make([]*pb.Reference, len(key))
	for i, k := range key {
		ret[i] = keyToProto(appID, k)
	}
	return ret
}

func multiKeyToProto ( appID string , key [ ] * Key ) [ ] * pb . Reference { ret := make ( [ ] * pb . Reference , len ( key ) ) for i , k := range key { ret [ i ] = keyToProto ( appID , k ) } return ret }

// multiKeyToProto is a batch version of keyToProto.

multiKeyToProto is a batch version of keyToProto .


func referenceValueToKey(r *pb.PropertyValue_ReferenceValue) (k *Key, err error) {
	appID := r.GetApp()
	namespace := r.GetNameSpace()
	for _, e := range r.Pathelement {
		k = &Key{
			kind:      e.GetType(),
			stringID:  e.GetName(),
			intID:     e.GetId(),
			parent:    k,
			appID:     appID,
			namespace: namespace,
		}
		if !k.valid() {
			return nil, ErrInvalidKey
		}
	}
	return
}

func referenceValueToKey ( r * pb . PropertyValue_ReferenceValue ) ( k * Key , err error ) { appID := r . GetApp ( ) namespace := r . GetNameSpace ( ) for _ , e := range r . Pathelement { k = & Key { kind : e . GetType ( ) , stringID : e . GetName ( ) , intID : e . GetId ( ) , parent : k , appID : appID , namespace : namespace , } if ! k . valid ( ) { return nil , ErrInvalidKey } } return }

// It's unfortunate that the two semantically equivalent concepts pb.Reference
// and pb.PropertyValue_ReferenceValue aren't the same type. For example, the
// two have different protobuf field numbers.
// referenceValueToKey is the same as protoToKey except the input is a
// PropertyValue_ReferenceValue instead of a Reference.

It s unfortunate that the two semantically equivalent concepts pb . Reference and pb . PropertyValue_ReferenceValue aren t the same type . For example the two have different protobuf field numbers . referenceValueToKey is the same as protoToKey except the input is a PropertyValue_ReferenceValue instead of a Reference .


func keyToReferenceValue(defaultAppID string, k *Key) *pb.PropertyValue_ReferenceValue {
	ref := keyToProto(defaultAppID, k)
	pe := make([]*pb.PropertyValue_ReferenceValue_PathElement, len(ref.Path.Element))
	for i, e := range ref.Path.Element {
		pe[i] = &pb.PropertyValue_ReferenceValue_PathElement{
			Type: e.Type,
			Id:   e.Id,
			Name: e.Name,
		}
	}
	return &pb.PropertyValue_ReferenceValue{
		App:         ref.App,
		NameSpace:   ref.NameSpace,
		Pathelement: pe,
	}
}

// keyToReferenceValue is the same as keyToProto except the output is a
// PropertyValue_ReferenceValue instead of a Reference.

keyToReferenceValue is the same as keyToProto except the output is a PropertyValue_ReferenceValue instead of a Reference .


func Put(c context.Context, key *Key, src interface{}) (*Key, error) {
	k, err := PutMulti(c, []*Key{key}, []interface{}{src})
	if err != nil {
		if me, ok := err.(appengine.MultiError); ok {
			return nil, me[0]
		}
		return nil, err
	}
	return k[0], nil
}

func Put ( c context . Context , key * Key , src interface { } ) ( * Key , error ) { k , err := PutMulti ( c , [ ] * Key { key } , [ ] interface { } { src } ) if err != nil { if me , ok := err . ( appengine . MultiError ) ; ok { return nil , me [ 0 ] } return nil , err } return k [ 0 ] , nil }

// Put saves the entity src into the datastore with key k. src must be a struct
// pointer or implement PropertyLoadSaver; if a struct pointer then any
// unexported fields of that struct will be skipped. If k is an incomplete key,
// the returned key will be a unique key generated by the datastore.

Put saves the entity src into the datastore with key k . src must be a struct pointer or implement PropertyLoadSaver ; if a struct pointer then any unexported fields of that struct will be skipped . If k is an incomplete key the returned key will be a unique key generated by the datastore .


func PutMulti(c context.Context, key []*Key, src interface{}) ([]*Key, error) {
	v := reflect.ValueOf(src)
	multiArgType, _ := checkMultiArg(v)
	if multiArgType == multiArgTypeInvalid {
		return nil, errors.New("datastore: src has invalid type")
	}
	if len(key) != v.Len() {
		return nil, errors.New("datastore: key and src slices have different length")
	}
	if len(key) == 0 {
		return nil, nil
	}
	appID := internal.FullyQualifiedAppID(c)
	if err := multiValid(key); err != nil {
		return nil, err
	}
	req := &pb.PutRequest{}
	for i := range key {
		elem := v.Index(i)
		if multiArgType == multiArgTypePropertyLoadSaver || multiArgType == multiArgTypeStruct {
			elem = elem.Addr()
		}
		sProto, err := saveEntity(appID, key[i], elem.Interface())
		if err != nil {
			return nil, err
		}
		req.Entity = append(req.Entity, sProto)
	}
	res := &pb.PutResponse{}
	if err := internal.Call(c, "datastore_v3", "Put", req, res); err != nil {
		return nil, err
	}
	if len(key) != len(res.Key) {
		return nil, errors.New("datastore: internal error: server returned the wrong number of keys")
	}
	ret := make([]*Key, len(key))
	for i := range ret {
		var err error
		ret[i], err = protoToKey(res.Key[i])
		if err != nil || ret[i].Incomplete() {
			return nil, errors.New("datastore: internal error: server returned an invalid key")
		}
	}
	return ret, nil
}

func PutMulti ( c context . Context , key [ ] * Key , src interface { } ) ( [ ] * Key , error ) { v := reflect . ValueOf ( src ) multiArgType , _ := checkMultiArg ( v ) if multiArgType == multiArgTypeInvalid { return nil , errors . New ( " " ) } if len ( key ) != v . Len ( ) { return nil , errors . New ( " " ) } if len ( key ) == 0 { return nil , nil } appID := internal . FullyQualifiedAppID ( c ) if err := multiValid ( key ) ; err != nil { return nil , err } req := & pb . PutRequest { } for i := range key { elem := v . Index ( i ) if multiArgType == multiArgTypePropertyLoadSaver || multiArgType == multiArgTypeStruct { elem = elem . Addr ( ) } sProto , err := saveEntity ( appID , key [ i ] , elem . Interface ( ) ) if err != nil { return nil , err } req . Entity = append ( req . Entity , sProto ) } res := & pb . PutResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return nil , err } if len ( key ) != len ( res . Key ) { return nil , errors . New ( " " ) } ret := make ( [ ] * Key , len ( key ) ) for i := range ret { var err error ret [ i ] , err = protoToKey ( res . Key [ i ] ) if err != nil || ret [ i ] . Incomplete ( ) { return nil , errors . New ( " " ) } } return ret , nil }

// PutMulti is a batch version of Put.
//
// src must satisfy the same conditions as the dst argument to GetMulti.

PutMulti is a batch version of Put . src must satisfy the same conditions as the dst argument to GetMulti .


func Delete(c context.Context, key *Key) error {
	err := DeleteMulti(c, []*Key{key})
	if me, ok := err.(appengine.MultiError); ok {
		return me[0]
	}
	return err
}

func Delete ( c context . Context , key * Key ) error { err := DeleteMulti ( c , [ ] * Key { key } ) if me , ok := err . ( appengine . MultiError ) ; ok { return me [ 0 ] } return err }

// Delete deletes the entity for the given key.

Delete deletes the entity for the given key .


func DeleteMulti(c context.Context, key []*Key) error {
	if len(key) == 0 {
		return nil
	}
	if err := multiValid(key); err != nil {
		return err
	}
	req := &pb.DeleteRequest{
		Key: multiKeyToProto(internal.FullyQualifiedAppID(c), key),
	}
	res := &pb.DeleteResponse{}
	return internal.Call(c, "datastore_v3", "Delete", req, res)
}

func DeleteMulti ( c context . Context , key [ ] * Key ) error { if len ( key ) == 0 { return nil } if err := multiValid ( key ) ; err != nil { return err } req := & pb . DeleteRequest { Key : multiKeyToProto ( internal . FullyQualifiedAppID ( c ) , key ) , } res := & pb . DeleteResponse { } return internal . Call ( c , " " , " " , req , res ) }

// DeleteMulti is a batch version of Delete.

DeleteMulti is a batch version of Delete .


func deploy() error {
	vlogf("Running command %v", flag.Args())
	cmd := exec.Command(flag.Arg(0), flag.Args()[1:]...)
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("unable to run %q: %v", strings.Join(flag.Args(), " "), err)
	}
	return nil
}

func deploy ( ) error { vlogf ( " " , flag . Args ( ) ) cmd := exec . Command ( flag . Arg ( 0 ) , flag . Args ( ) [ 1 : ] ... ) cmd . Stdin , cmd . Stdout , cmd . Stderr = os . Stdin , os . Stdout , os . Stderr if err := cmd . Run ( ) ; err != nil { return fmt . Errorf ( " " , strings . Join ( flag . Args ( ) , " " ) , err ) } return nil }

// deploy calls the provided command to deploy the app from the temporary directory.

deploy calls the provided command to deploy the app from the temporary directory .


func (qr *Result) Next() (*Record, error) {
	if qr.err != nil {
		return nil, qr.err
	}
	if len(qr.logs) > 0 {
		lr := qr.logs[0]
		qr.logs = qr.logs[1:]
		return lr, nil
	}

	if qr.request.Offset == nil && qr.resultsSeen {
		return nil, Done
	}

	if err := qr.run(); err != nil {
		// Errors here may be retried, so don't store the error.
		return nil, err
	}

	return qr.Next()
}


func protoToAppLogs(logLines []*pb.LogLine) []AppLog {
	appLogs := make([]AppLog, len(logLines))

	for i, line := range logLines {
		appLogs[i] = AppLog{
			Time:    time.Unix(0, *line.Time*1e3),
			Level:   int(*line.Level),
			Message: *line.LogMessage,
		}
	}

	return appLogs
}

func protoToAppLogs ( logLines [ ] * pb . LogLine ) [ ] AppLog { appLogs := make ( [ ] AppLog , len ( logLines ) ) for i , line := range logLines { appLogs [ i ] = AppLog { Time : time . Unix ( 0 , * line . Time * 1e3 ) , Level : int ( * line . Level ) , Message : * line . LogMessage , } } return appLogs }

// protoToAppLogs takes as input an array of pointers to LogLines, the internal
// Protocol Buffer representation of a single application-level log,
// and converts it to an array of AppLogs, the external representation
// of an application-level log.

protoToAppLogs takes as input an array of pointers to LogLines the internal Protocol Buffer representation of a single application - level log and converts it to an array of AppLogs the external representation of an application - level log .


func protoToRecord(rl *pb.RequestLog) *Record {
	offset, err := proto.Marshal(rl.Offset)
	if err != nil {
		offset = nil
	}
	return &Record{
		AppID:             *rl.AppId,
		ModuleID:          rl.GetModuleId(),
		VersionID:         *rl.VersionId,
		RequestID:         rl.RequestId,
		Offset:            offset,
		IP:                *rl.Ip,
		Nickname:          rl.GetNickname(),
		AppEngineRelease:  string(rl.GetAppEngineRelease()),
		StartTime:         time.Unix(0, *rl.StartTime*1e3),
		EndTime:           time.Unix(0, *rl.EndTime*1e3),
		Latency:           time.Duration(*rl.Latency) * time.Microsecond,
		MCycles:           *rl.Mcycles,
		Method:            *rl.Method,
		Resource:          *rl.Resource,
		HTTPVersion:       *rl.HttpVersion,
		Status:            *rl.Status,
		ResponseSize:      *rl.ResponseSize,
		Referrer:          rl.GetReferrer(),
		UserAgent:         rl.GetUserAgent(),
		URLMapEntry:       *rl.UrlMapEntry,
		Combined:          *rl.Combined,
		Host:              rl.GetHost(),
		Cost:              rl.GetCost(),
		TaskQueueName:     rl.GetTaskQueueName(),
		TaskName:          rl.GetTaskName(),
		WasLoadingRequest: rl.GetWasLoadingRequest(),
		PendingTime:       time.Duration(rl.GetPendingTime()) * time.Microsecond,
		Finished:          rl.GetFinished(),
		AppLogs:           protoToAppLogs(rl.Line),
		InstanceID:        string(rl.GetCloneKey()),
	}
}

func protoToRecord ( rl * pb . RequestLog ) * Record { offset , err := proto . Marshal ( rl . Offset ) if err != nil { offset = nil } return & Record { AppID : * rl . AppId , ModuleID : rl . GetModuleId ( ) , VersionID : * rl . VersionId , RequestID : rl . RequestId , Offset : offset , IP : * rl . Ip , Nickname : rl . GetNickname ( ) , AppEngineRelease : string ( rl . GetAppEngineRelease ( ) ) , StartTime : time . Unix ( 0 , * rl . StartTime * 1e3 ) , EndTime : time . Unix ( 0 , * rl . EndTime * 1e3 ) , Latency : time . Duration ( * rl . Latency ) * time . Microsecond , MCycles : * rl . Mcycles , Method : * rl . Method , Resource : * rl . Resource , HTTPVersion : * rl . HttpVersion , Status : * rl . Status , ResponseSize : * rl . ResponseSize , Referrer : rl . GetReferrer ( ) , UserAgent : rl . GetUserAgent ( ) , URLMapEntry : * rl . UrlMapEntry , Combined : * rl . Combined , Host : rl . GetHost ( ) , Cost : rl . GetCost ( ) , TaskQueueName : rl . GetTaskQueueName ( ) , TaskName : rl . GetTaskName ( ) , WasLoadingRequest : rl . GetWasLoadingRequest ( ) , PendingTime : time . Duration ( rl . GetPendingTime ( ) ) * time . Microsecond , Finished : rl . GetFinished ( ) , AppLogs : protoToAppLogs ( rl . Line ) , InstanceID : string ( rl . GetCloneKey ( ) ) , } }

// protoToRecord converts a RequestLog, the internal Protocol Buffer
// representation of a single request-level log, to a Record, its
// corresponding external representation.

protoToRecord converts a RequestLog the internal Protocol Buffer representation of a single request - level log to a Record its corresponding external representation .


func (params *Query) Run(c context.Context) *Result {
	req, err := makeRequest(params, internal.FullyQualifiedAppID(c), appengine.VersionID(c))
	return &Result{
		context: c,
		request: req,
		err:     err,
	}
}

func ( params * Query ) Run ( c context . Context ) * Result { req , err := makeRequest ( params , internal . FullyQualifiedAppID ( c ) , appengine . VersionID ( c ) ) return & Result { context : c , request : req , err : err , } }

// Run starts a query for log records, which contain request and application
// level log information.

Run starts a query for log records which contain request and application level log information .


func (r *Result) run() error {
	res := &pb.LogReadResponse{}
	if err := internal.Call(r.context, "logservice", "Read", r.request, res); err != nil {
		return err
	}

	r.logs = make([]*Record, len(res.Log))
	r.request.Offset = res.Offset
	r.resultsSeen = true

	for i, log := range res.Log {
		r.logs[i] = protoToRecord(log)
	}

	return nil
}

func ( r * Result ) run ( ) error { res := & pb . LogReadResponse { } if err := internal . Call ( r . context , " " , " " , r . request , res ) ; err != nil { return err } r . logs = make ( [ ] * Record , len ( res . Log ) ) r . request . Offset = res . Offset r . resultsSeen = true for i , log := range res . Log { r . logs [ i ] = protoToRecord ( log ) } return nil }

// run takes the query Result produced by a call to Run and updates it with
// more Records. The updated Result contains a new set of logs as well as an
// offset to where more logs can be found. We also convert the items in the
// response from their internal representations to external versions of the
// same structs.

run takes the query Result produced by a call to Run and updates it with more Records . The updated Result contains a new set of logs as well as an offset to where more logs can be found . We also convert the items in the response from their internal representations to external versions of the same structs .


func Current(c context.Context) *User {
	h := internal.IncomingHeaders(c)
	u := &User{
		Email:             h.Get("X-AppEngine-User-Email"),
		AuthDomain:        h.Get("X-AppEngine-Auth-Domain"),
		ID:                h.Get("X-AppEngine-User-Id"),
		Admin:             h.Get("X-AppEngine-User-Is-Admin") == "1",
		FederatedIdentity: h.Get("X-AppEngine-Federated-Identity"),
		FederatedProvider: h.Get("X-AppEngine-Federated-Provider"),
	}
	if u.Email == "" && u.FederatedIdentity == "" {
		return nil
	}
	return u
}

func Current ( c context . Context ) * User { h := internal . IncomingHeaders ( c ) u := & User { Email : h . Get ( " " ) , AuthDomain : h . Get ( " " ) , ID : h . Get ( " " ) , Admin : h . Get ( " " ) == " " , FederatedIdentity : h . Get ( " " ) , FederatedProvider : h . Get ( " " ) , } if u . Email == " " && u . FederatedIdentity == " " { return nil } return u }

// Current returns the currently logged-in user,
// or nil if the user is not signed in.

Current returns the currently logged - in user or nil if the user is not signed in .


func IsAdmin(c context.Context) bool {
	h := internal.IncomingHeaders(c)
	return h.Get("X-AppEngine-User-Is-Admin") == "1"
}

func IsAdmin ( c context . Context ) bool { h := internal . IncomingHeaders ( c ) return h . Get ( " " ) == " " }

// IsAdmin returns true if the current user is signed in and
// is currently registered as an administrator of the application.

IsAdmin returns true if the current user is signed in and is currently registered as an administrator of the application .


func isErrFieldMismatch(err error) bool {
	_, ok := err.(*datastore.ErrFieldMismatch)
	return ok
}

func isErrFieldMismatch ( err error ) bool { _ , ok := err . ( * datastore . ErrFieldMismatch ) return ok }

// isErrFieldMismatch returns whether err is a datastore.ErrFieldMismatch.
//
// The blobstore stores blob metadata in the datastore. When loading that
// metadata, it may contain fields that we don't care about. datastore.Get will
// return datastore.ErrFieldMismatch in that case, so we ignore that specific
// error.

isErrFieldMismatch returns whether err is a datastore . ErrFieldMismatch . The blobstore stores blob metadata in the datastore . When loading that metadata it may contain fields that we don t care about . datastore . Get will return datastore . ErrFieldMismatch in that case so we ignore that specific error .


func Stat(c context.Context, blobKey appengine.BlobKey) (*BlobInfo, error) {
	c, _ = appengine.Namespace(c, "") // Blobstore is always in the empty string namespace
	dskey := datastore.NewKey(c, blobInfoKind, string(blobKey), 0, nil)
	bi := &BlobInfo{
		BlobKey: blobKey,
	}
	if err := datastore.Get(c, dskey, bi); err != nil && !isErrFieldMismatch(err) {
		return nil, err
	}
	return bi, nil
}

// Stat returns the BlobInfo for a provided blobKey. If no blob was found for
// that key, Stat returns datastore.ErrNoSuchEntity.

Stat returns the BlobInfo for a provided blobKey . If no blob was found for that key Stat returns datastore . ErrNoSuchEntity .


func Send(response http.ResponseWriter, blobKey appengine.BlobKey) {
	hdr := response.Header()
	hdr.Set("X-AppEngine-BlobKey", string(blobKey))

	if hdr.Get("Content-Type") == "" {
		// This value is known to dev_appserver to mean automatic.
		// In production this is remapped to the empty value which
		// means automatic.
		hdr.Set("Content-Type", "application/vnd.google.appengine.auto")
	}
}

// Send sets the headers on response to instruct App Engine to send a blob as
// the response body. This is more efficient than reading and writing it out
// manually and isn't subject to normal response size limits.

Send sets the headers on response to instruct App Engine to send a blob as the response body . This is more efficient than reading and writing it out manually and isn t subject to normal response size limits .


func UploadURL(c context.Context, successPath string, opts *UploadURLOptions) (*url.URL, error) {
	req := &blobpb.CreateUploadURLRequest{
		SuccessPath: proto.String(successPath),
	}
	if opts != nil {
		if n := opts.MaxUploadBytes; n != 0 {
			req.MaxUploadSizeBytes = &n
		}
		if n := opts.MaxUploadBytesPerBlob; n != 0 {
			req.MaxUploadSizePerBlobBytes = &n
		}
		if s := opts.StorageBucket; s != "" {
			req.GsBucketName = &s
		}
	}
	res := &blobpb.CreateUploadURLResponse{}
	if err := internal.Call(c, "blobstore", "CreateUploadURL", req, res); err != nil {
		return nil, err
	}
	return url.Parse(*res.Url)
}

func UploadURL ( c context . Context , successPath string , opts * UploadURLOptions ) ( * url . URL , error ) { req := & blobpb . CreateUploadURLRequest { SuccessPath : proto . String ( successPath ) , } if opts != nil { if n := opts . MaxUploadBytes ; n != 0 { req . MaxUploadSizeBytes = & n } if n := opts . MaxUploadBytesPerBlob ; n != 0 { req . MaxUploadSizePerBlobBytes = & n } if s := opts . StorageBucket ; s != " " { req . GsBucketName = & s } } res := & blobpb . CreateUploadURLResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return nil , err } return url . Parse ( * res . Url ) }

// UploadURL creates an upload URL for the form that the user will
// fill out, passing the application path to load when the POST of the
// form is completed. These URLs expire and should not be reused. The
// opts parameter may be nil.

UploadURL creates an upload URL for the form that the user will fill out passing the application path to load when the POST of the form is completed . These URLs expire and should not be reused . The opts parameter may be nil .


func Delete(c context.Context, blobKey appengine.BlobKey) error {
	return DeleteMulti(c, []appengine.BlobKey{blobKey})
}

func Delete ( c context . Context , blobKey appengine . BlobKey ) error { return DeleteMulti ( c , [ ] appengine . BlobKey { blobKey } ) }


func DeleteMulti(c context.Context, blobKey []appengine.BlobKey) error {
	s := make([]string, len(blobKey))
	for i, b := range blobKey {
		s[i] = string(b)
	}
	req := &blobpb.DeleteBlobRequest{
		BlobKey: s,
	}
	res := &basepb.VoidProto{}
	if err := internal.Call(c, "blobstore", "DeleteBlob", req, res); err != nil {
		return err
	}
	return nil
}

func DeleteMulti ( c context . Context , blobKey [ ] appengine . BlobKey ) error { s := make ( [ ] string , len ( blobKey ) ) for i , b := range blobKey { s [ i ] = string ( b ) } req := & blobpb . DeleteBlobRequest { BlobKey : s , } res := & basepb . VoidProto { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return err } return nil }


func NewReader(c context.Context, blobKey appengine.BlobKey) Reader {
	return openBlob(c, blobKey)
}

func NewReader ( c context . Context , blobKey appengine . BlobKey ) Reader { return openBlob ( c , blobKey ) }

// NewReader returns a reader for a blob. It always succeeds; if the blob does
// not exist then an error will be reported upon first read.

NewReader returns a reader for a blob . It always succeeds ; if the blob does not exist then an error will be reported upon first read .


func Handle(f func(c context.Context, m *Message)) {
	http.HandleFunc("/_ah/xmpp/message/chat/", func(_ http.ResponseWriter, r *http.Request) {
		f(appengine.NewContext(r), &Message{
			Sender: r.FormValue("from"),
			To:     []string{r.FormValue("to")},
			Body:   r.FormValue("body"),
		})
	})
}

func Handle ( f func ( c context . Context , m * Message ) ) { http . HandleFunc ( " " , func ( _ http . ResponseWriter , r * http . Request ) { f ( appengine . NewContext ( r ) , & Message { Sender : r . FormValue ( " " ) , To : [ ] string { r . FormValue ( " " ) } , Body : r . FormValue ( " " ) , } ) } ) }

// Handle arranges for f to be called for incoming XMPP messages.
// Only messages of type "chat" or "normal" will be handled.

Handle arranges for f to be called for incoming XMPP messages . Only messages of type chat or normal will be handled .


func (m *Message) Send(c context.Context) error {
	req := &pb.XmppMessageRequest{
		Jid:    m.To,
		Body:   &m.Body,
		RawXml: &m.RawXML,
	}
	if m.Type != "" && m.Type != "chat" {
		req.Type = &m.Type
	}
	if m.Sender != "" {
		req.FromJid = &m.Sender
	}
	res := &pb.XmppMessageResponse{}
	if err := internal.Call(c, "xmpp", "SendMessage", req, res); err != nil {
		return err
	}

	if len(res.Status) != len(req.Jid) {
		return fmt.Errorf("xmpp: sent message to %d JIDs, but only got %d statuses back", len(req.Jid), len(res.Status))
	}
	me, any := make(appengine.MultiError, len(req.Jid)), false
	for i, st := range res.Status {
		if st != pb.XmppMessageResponse_NO_ERROR {
			me[i] = errors.New(st.String())
			any = true
		}
	}
	if any {
		return me
	}
	return nil
}

func ( m * Message ) Send ( c context . Context ) error { req := & pb . XmppMessageRequest { Jid : m . To , Body : & m . Body , RawXml : & m . RawXML , } if m . Type != " " && m . Type != " " { req . Type = & m . Type } if m . Sender != " " { req . FromJid = & m . Sender } res := & pb . XmppMessageResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return err } if len ( res . Status ) != len ( req . Jid ) { return fmt . Errorf ( " " , len ( req . Jid ) , len ( res . Status ) ) } me , any := make ( appengine . MultiError , len ( req . Jid ) ) , false for i , st := range res . Status { if st != pb . XmppMessageResponse_NO_ERROR { me [ i ] = errors . New ( st . String ( ) ) any = true } } if any { return me } return nil }

// Send sends a message.
// If any failures occur with specific recipients, the error will be an appengine.MultiError.

Send sends a message . If any failures occur with specific recipients the error will be an appengine . MultiError .


func Invite(c context.Context, to, from string) error {
	req := &pb.XmppInviteRequest{
		Jid: &to,
	}
	if from != "" {
		req.FromJid = &from
	}
	res := &pb.XmppInviteResponse{}
	return internal.Call(c, "xmpp", "SendInvite", req, res)
}

func Invite ( c context . Context , to , from string ) error { req := & pb . XmppInviteRequest { Jid : & to , } if from != " " { req . FromJid = & from } res := & pb . XmppInviteResponse { } return internal . Call ( c , " " , " " , req , res ) }

// Invite sends an invitation. If the from address is an empty string
// the default (yourapp@appspot.com/bot) will be used.

Invite sends an invitation . If the from address is an empty string the default ( yourapp


func (p *Presence) Send(c context.Context) error {
	req := &pb.XmppSendPresenceRequest{
		Jid: &p.To,
	}
	if p.State != "" {
		req.Show = &p.State
	}
	if p.Type != "" {
		req.Type = &p.Type
	}
	if p.Sender != "" {
		req.FromJid = &p.Sender
	}
	if p.Status != "" {
		req.Status = &p.Status
	}
	res := &pb.XmppSendPresenceResponse{}
	return internal.Call(c, "xmpp", "SendPresence", req, res)
}

func ( p * Presence ) Send ( c context . Context ) error { req := & pb . XmppSendPresenceRequest { Jid : & p . To , } if p . State != " " { req . Show = & p . State } if p . Type != " " { req . Type = & p . Type } if p . Sender != " " { req . FromJid = & p . Sender } if p . Status != " " { req . Status = & p . Status } res := & pb . XmppSendPresenceResponse { } return internal . Call ( c , " " , " " , req , res ) }


func GetPresence(c context.Context, to string, from string) (string, error) {
	req := &pb.PresenceRequest{
		Jid: &to,
	}
	if from != "" {
		req.FromJid = &from
	}
	res := &pb.PresenceResponse{}
	if err := internal.Call(c, "xmpp", "GetPresence", req, res); err != nil {
		return "", err
	}
	if !*res.IsAvailable || res.Presence == nil {
		return "", ErrPresenceUnavailable
	}
	presence, ok := presenceMap[*res.Presence]
	if ok {
		return presence, nil
	}
	return "", fmt.Errorf("xmpp: unknown presence %v", *res.Presence)
}

func GetPresence ( c context . Context , to string , from string ) ( string , error ) { req := & pb . PresenceRequest { Jid : & to , } if from != " " { req . FromJid = & from } res := & pb . PresenceResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return " " , err } if ! * res . IsAvailable || res . Presence == nil { return " " , ErrPresenceUnavailable } presence , ok := presenceMap [ * res . Presence ] if ok { return presence , nil } return " " , fmt . Errorf ( " " , * res . Presence ) }

// GetPresence retrieves a user's presence.
// If the from address is an empty string the default
// (yourapp@appspot.com/bot) will be used.
// Possible return values are "", "away", "dnd", "chat", "xa".
// ErrPresenceUnavailable is returned if the presence is unavailable.

GetPresence retrieves a user s presence . If the from address is an empty string the default ( yourapp


func GetPresenceMulti(c context.Context, to []string, from string) ([]string, error) {
	req := &pb.BulkPresenceRequest{
		Jid: to,
	}
	if from != "" {
		req.FromJid = &from
	}
	res := &pb.BulkPresenceResponse{}

	if err := internal.Call(c, "xmpp", "BulkGetPresence", req, res); err != nil {
		return nil, err
	}

	presences := make([]string, 0, len(res.PresenceResponse))
	errs := appengine.MultiError{}

	addResult := func(presence string, err error) {
		presences = append(presences, presence)
		errs = append(errs, err)
	}

	anyErr := false
	for _, subres := range res.PresenceResponse {
		if !subres.GetValid() {
			anyErr = true
			addResult("", ErrInvalidJID)
			continue
		}
		if !*subres.IsAvailable || subres.Presence == nil {
			anyErr = true
			addResult("", ErrPresenceUnavailable)
			continue
		}
		presence, ok := presenceMap[*subres.Presence]
		if ok {
			addResult(presence, nil)
		} else {
			anyErr = true
			addResult("", fmt.Errorf("xmpp: unknown presence %q", *subres.Presence))
		}
	}
	if anyErr {
		return presences, errs
	}
	return presences, nil
}

func GetPresenceMulti ( c context . Context , to [ ] string , from string ) ( [ ] string , error ) { req := & pb . BulkPresenceRequest { Jid : to , } if from != " " { req . FromJid = & from } res := & pb . BulkPresenceResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return nil , err } presences := make ( [ ] string , 0 , len ( res . PresenceResponse ) ) errs := appengine . MultiError { } addResult := func ( presence string , err error ) { presences = append ( presences , presence ) errs = append ( errs , err ) } anyErr := false for _ , subres := range res . PresenceResponse { if ! subres . GetValid ( ) { anyErr = true addResult ( " " , ErrInvalidJID ) continue } if ! * subres . IsAvailable || subres . Presence == nil { anyErr = true addResult ( " " , ErrPresenceUnavailable ) continue } presence , ok := presenceMap [ * subres . Presence ] if ok { addResult ( presence , nil ) } else { anyErr = true addResult ( " " , fmt . Errorf ( " " , * subres . Presence ) ) } } if anyErr { return presences , errs } return presences , nil }

// GetPresenceMulti retrieves multiple users' presence.
// If the from address is an empty string the default
// (yourapp@appspot.com/bot) will be used.
// Possible return values are "", "away", "dnd", "chat", "xa".
// If any presence is unavailable, an appengine.MultiError is returned

GetPresenceMulti retrieves multiple users presence . If the from address is an empty string the default ( yourapp


func newStructFLS(p interface{}) (FieldLoadSaver, error) {
	v := reflect.ValueOf(p)
	if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct {
		return nil, ErrInvalidDocumentType
	}
	codec, err := loadCodec(v.Elem().Type())
	if err != nil {
		return nil, err
	}
	return structFLS{v.Elem(), codec}, nil
}

func newStructFLS ( p interface { } ) ( FieldLoadSaver , error ) { v := reflect . ValueOf ( p ) if v . Kind ( ) != reflect . Ptr || v . IsNil ( ) || v . Elem ( ) . Kind ( ) != reflect . Struct { return nil , ErrInvalidDocumentType } codec , err := loadCodec ( v . Elem ( ) . Type ( ) ) if err != nil { return nil , err } return structFLS { v . Elem ( ) , codec } , nil }

// newStructFLS returns a FieldLoadSaver for the struct pointer p.

newStructFLS returns a FieldLoadSaver for the struct pointer p .


func SaveStruct(src interface{}) ([]Field, error) {
	f, _, err := saveStructWithMeta(src)
	return f, err
}

func SaveStruct ( src interface { } ) ( [ ] Field , error ) { f , _ , err := saveStructWithMeta ( src ) return f , err }

// SaveStruct returns the fields from src as a slice of Field.
// src must be a struct pointer.

SaveStruct returns the fields from src as a slice of Field . src must be a struct pointer .


func Namespaces(ctx context.Context) ([]string, error) {
	// TODO(djd): Support range queries.
	q := NewQuery(namespaceKind).KeysOnly()
	keys, err := q.GetAll(ctx, nil)
	if err != nil {
		return nil, err
	}
	// The empty namespace key uses a numeric ID (==1), but luckily
	// the string ID defaults to "" for numeric IDs anyway.
	return keyNames(keys), nil
}

// Namespaces returns all the datastore namespaces.

Namespaces returns all the datastore namespaces .


func Kinds(ctx context.Context) ([]string, error) {
	// TODO(djd): Support range queries.
	q := NewQuery(kindKind).KeysOnly()
	keys, err := q.GetAll(ctx, nil)
	if err != nil {
		return nil, err
	}
	return keyNames(keys), nil
}

func
Kinds
(
ctx
context
.
Context
)
(
[
]
string
,
error
)
{
// TODO(djd): Support range queries.
q
:=
NewQuery
(
kindKind
)
.
KeysOnly
(
)
keys
,
err
:=
q
.
GetAll
(
ctx
,
)
if
err
!=
{
return
,
err
}
return
keyNames
(
keys
)
,
}

// Kinds returns the names of all the kinds in the current namespace.

Kinds returns the names of all the kinds in the current namespace .


func RunInTransaction(c context.Context, f func(tc context.Context) error, opts *TransactionOptions) error {
	xg := false
	if opts != nil {
		xg = opts.XG
	}
	readOnly := false
	if opts != nil {
		readOnly = opts.ReadOnly
	}
	attempts := 3
	if opts != nil && opts.Attempts > 0 {
		attempts = opts.Attempts
	}
	var t *pb.Transaction
	var err error
	for i := 0; i < attempts; i++ {
		if t, err = internal.RunTransactionOnce(c, f, xg, readOnly, t); err != internal.ErrConcurrentTransaction {
			return err
		}
	}
	return ErrConcurrentTransaction
}

func RunInTransaction ( c context . Context , f func ( tc context . Context ) error , opts * TransactionOptions ) error { xg := false if opts != nil { xg = opts . XG } readOnly := false if opts != nil { readOnly = opts . ReadOnly } attempts := 3 if opts != nil && opts . Attempts > 0 { attempts = opts . Attempts } var t * pb . Transaction var err error for i := 0 ; i < attempts ; i ++ { if t , err = internal . RunTransactionOnce ( c , f , xg , readOnly , t ) ; err != internal . ErrConcurrentTransaction { return err } } return ErrConcurrentTransaction }

// RunInTransaction runs f in a transaction. It calls f with a transaction
// context tc that f should use for all App Engine operations.
//
// If f returns nil, RunInTransaction attempts to commit the transaction,
// returning nil if it succeeds. If the commit fails due to a conflicting
// transaction, RunInTransaction retries f, each time with a new transaction
// context. It gives up and returns ErrConcurrentTransaction after three
// failed attempts. The number of attempts can be configured by specifying
// TransactionOptions.Attempts.
//
// If f returns non-nil, then any datastore changes will not be applied and
// RunInTransaction returns that same error. The function f is not retried.
//
// Note that when f returns, the transaction is not yet committed. Calling code
// must be careful not to assume that any of f's changes have been committed
// until RunInTransaction returns nil.
//
// Since f may be called multiple times, f should usually be idempotent.
// datastore.Get is not idempotent when unmarshaling slice fields.
//
// Nested transactions are not supported; c may not be a transaction context.

RunInTransaction runs f in a transaction . It calls f with a transaction context tc that f should use for all App Engine operations . If f returns nil RunInTransaction attempts to commit the transaction returning nil if it succeeds . If the commit fails due to a conflicting transaction RunInTransaction retries f each time with a new transaction context . It gives up and returns ErrConcurrentTransaction after three failed attempts . The number of attempts can be configured by specifying TransactionOptions . Attempts . If f returns non - nil then any datastore changes will not be applied and RunInTransaction returns that same error . The function f is not retried . Note that when f returns the transaction is not yet committed . Calling code must be careful not to assume that any of f s changes have been committed until RunInTransaction returns nil . Since f may be called multiple times f should usually be idempotent . datastore . Get is not idempotent when unmarshaling slice fields . Nested transactions are not supported ; c may not be a transaction context .


func imports(f *ast.File, path string) bool {
	return importSpec(f, path) != nil
}

func imports ( f * ast . File , path string ) bool { return importSpec ( f , path ) != nil }

// imports returns true if f imports path.

imports returns true if f imports path .


func importSpec(f *ast.File, path string) *ast.ImportSpec {
	for _, s := range f.Imports {
		if importPath(s) == path {
			return s
		}
	}
	return nil
}

func importSpec ( f * ast . File , path string ) * ast . ImportSpec { for _ , s := range f . Imports { if importPath ( s ) == path { return s } } return nil }

// importSpec returns the import spec if f imports path,
// or nil otherwise.

importSpec returns the import spec if f imports path or nil otherwise .


func declImports(gen *ast.GenDecl, path string) bool {
	if gen.Tok != token.IMPORT {
		return false
	}
	for _, spec := range gen.Specs {
		impspec := spec.(*ast.ImportSpec)
		if importPath(impspec) == path {
			return true
		}
	}
	return false
}

func declImports ( gen * ast . GenDecl , path string ) bool { if gen . Tok != token . IMPORT { return false } for _ , spec := range gen . Specs { impspec := spec . ( * ast . ImportSpec ) if importPath ( impspec ) == path { return true } } return false }

// declImports reports whether gen contains an import of path.

declImports reports whether gen contains an import of path .


func isPkgDot(t ast.Expr, pkg, name string) bool {
	sel, ok := t.(*ast.SelectorExpr)
	return ok && isTopName(sel.X, pkg) && sel.Sel.String() == name
}

func isPkgDot ( t ast . Expr , pkg , name string ) bool { sel , ok := t . ( * ast . SelectorExpr ) return ok && isTopName ( sel . X , pkg ) && sel . Sel . String ( ) == name }

// isPkgDot returns true if t is the expression "pkg.name"
// where pkg is an imported identifier.

isPkgDot returns true if t is the expression pkg . name where pkg is an imported identifier .


func isTopName(n ast.Expr, name string) bool {
	id, ok := n.(*ast.Ident)
	return ok && id.Name == name && id.Obj == nil
}

func isTopName ( n ast . Expr , name string ) bool { id , ok := n . ( * ast . Ident ) return ok && id . Name == name && id . Obj == nil }

// isTopName returns true if n is a top-level unresolved identifier with the given name.

isTopName returns true if n is a top - level unresolved identifier with the given name .


func isName(n ast.Expr, name string) bool {
	id, ok := n.(*ast.Ident)
	return ok && id.String() == name
}

func isName ( n ast . Expr , name string ) bool { id , ok := n . ( * ast . Ident ) return ok && id . String ( ) == name }

// isName returns true if n is an identifier with the given name.

isName returns true if n is an identifier with the given name .


func isCall(t ast.Expr, pkg, name string) bool {
	call, ok := t.(*ast.CallExpr)
	return ok && isPkgDot(call.Fun, pkg, name)
}

func isCall ( t ast . Expr , pkg , name string ) bool { call , ok := t . ( * ast . CallExpr ) return ok && isPkgDot ( call . Fun , pkg , name ) }

// isCall returns true if t is a call to pkg.name.

isCall returns true if t is a call to pkg . name .


func refersTo(n ast.Node, x *ast.Ident) bool {
	id, ok := n.(*ast.Ident)
	// The test of id.Name == x.Name handles top-level unresolved
	// identifiers, which all have Obj == nil.
	return ok && id.Obj == x.Obj && id.Name == x.Name
}

// refersTo returns true if n is a reference to the same object as x.

refersTo returns true if n is a reference to the same object as x .


func isEmptyString(n ast.Expr) bool {
	lit, ok := n.(*ast.BasicLit)
	return ok && lit.Kind == token.STRING && len(lit.Value) == 2
}

func isEmptyString ( n ast . Expr ) bool { lit , ok := n . ( * ast . BasicLit ) return ok && lit . Kind == token . STRING && len ( lit . Value ) == 2 }

// isEmptyString returns true if n is an empty string literal.

isEmptyString returns true if n is an empty string literal .


func countUses(x *ast.Ident, scope []ast.Stmt) int {
	count := 0
	ff := func(n interface{}) {
		if n, ok := n.(ast.Node); ok && refersTo(n, x) {
			count++
		}
	}
	for _, n := range scope {
		walk(n, ff)
	}
	return count
}

func countUses ( x * ast . Ident , scope [ ] ast . Stmt ) int { count := 0 ff := func ( n interface { } ) { if n , ok := n . ( ast . Node ) ; ok && refersTo ( n , x ) { count ++ } } for _ , n := range scope { walk ( n , ff ) } return count }

// countUses returns the number of uses of the identifier x in scope.

countUses returns the number of uses of the identifier x in scope .


func assignsTo(x *ast.Ident, scope []ast.Stmt) bool {
	assigned := false
	ff := func(n interface{}) {
		if assigned {
			return
		}
		switch n := n.(type) {
		case *ast.UnaryExpr:
			// use of &x
			if n.Op == token.AND && refersTo(n.X, x) {
				assigned = true
				return
			}
		case *ast.AssignStmt:
			for _, l := range n.Lhs {
				if refersTo(l, x) {
					assigned = true
					return
				}
			}
		}
	}
	for _, n := range scope {
		if assigned {
			break
		}
		walk(n, ff)
	}
	return assigned
}

func
assignsTo
(
x
*
ast
.
Ident
,
scope
[
]
ast
.
Stmt
)
bool
{
assigned
:=
false
ff
:=
func
(
n
interface
{
}
)
{
if
assigned
{
return
}
switch
n
:=
n
.
(
type
)
{
case
*
ast
.
UnaryExpr
:
// use of &x
if
n
.
Op
==
token
.
AND
&&
refersTo
(
n
.
X
,
x
)
{
assigned
=
true
return
}
case
*
ast
.
AssignStmt
:
for
_
,
l
:=
range
n
.
Lhs
{
if
refersTo
(
l
,
x
)
{
assigned
=
true
return
}
}
}
}
for
_
,
n
:=
range
scope
{
if
assigned
{
break
}
walk
(
n
,
ff
)
}
return
assigned
}

// assignsTo returns true if any of the code in scope assigns to or takes the address of x.

assignsTo returns true if any of the code in scope assigns to or takes the address of x .


func newPkgDot(pos token.Pos, pkg, name string) ast.Expr {
	return &ast.SelectorExpr{
		X: &ast.Ident{
			NamePos: pos,
			Name:    pkg,
		},
		Sel: &ast.Ident{
			NamePos: pos,
			Name:    name,
		},
	}
}

func newPkgDot ( pos token . Pos , pkg , name string ) ast . Expr { return & ast . SelectorExpr { X : & ast . Ident { NamePos : pos , Name : pkg , } , Sel : & ast . Ident { NamePos : pos , Name : name , } , } }

// newPkgDot returns an ast.Expr referring to "pkg.name" at position pos.

newPkgDot returns an ast . Expr referring to pkg . name at position pos .


func renameTop(f *ast.File, old, new string) bool {
	var fixed bool

	// Rename any conflicting imports
	// (assuming package name is last element of path).
	for _, s := range f.Imports {
		if s.Name != nil {
			if s.Name.Name == old {
				s.Name.Name = new
				fixed = true
			}
		} else {
			_, thisName := path.Split(importPath(s))
			if thisName == old {
				s.Name = ast.NewIdent(new)
				fixed = true
			}
		}
	}

	// Rename any top-level declarations.
	for _, d := range f.Decls {
		switch d := d.(type) {
		case *ast.FuncDecl:
			if d.Recv == nil && d.Name.Name == old {
				d.Name.Name = new
				d.Name.Obj.Name = new
				fixed = true
			}
		case *ast.GenDecl:
			for _, s := range d.Specs {
				switch s := s.(type) {
				case *ast.TypeSpec:
					if s.Name.Name == old {
						s.Name.Name = new
						s.Name.Obj.Name = new
						fixed = true
					}
				case *ast.ValueSpec:
					for _, n := range s.Names {
						if n.Name == old {
							n.Name = new
							n.Obj.Name = new
							fixed = true
						}
					}
				}
			}
		}
	}

	// Rename top-level old to new, both unresolved names
	// (probably defined in another file) and names that resolve
	// to a declaration we renamed.
	walk(f, func(n interface{}) {
		id, ok := n.(*ast.Ident)
		if ok && isTopName(id, old) {
			id.Name = new
			fixed = true
		}
		if ok && id.Obj != nil && id.Name == old && id.Obj.Name == new {
			id.Name = id.Obj.Name
			fixed = true
		}
	})

	return fixed
}

// renameTop renames all references to the top-level name old.
// It returns true if it makes any changes.

renameTop renames all references to the top - level name old . It returns true if it makes any changes .


func matchLen(x, y string) int {
	i := 0
	for i < len(x) && i < len(y) && x[i] == y[i] {
		i++
	}
	return i
}

func matchLen ( x , y string ) int { i := 0 for i < len ( x ) && i < len ( y ) && x [ i ] == y [ i ] { i ++ } return i }

// matchLen returns the length of the longest prefix shared by x and y.

matchLen returns the length of the longest prefix shared by x and y .


func deleteImport(f *ast.File, path string) (deleted bool) {
	oldImport := importSpec(f, path)

	// Find the import node that imports path, if any.
	for i, decl := range f.Decls {
		gen, ok := decl.(*ast.GenDecl)
		if !ok || gen.Tok != token.IMPORT {
			continue
		}
		for j, spec := range gen.Specs {
			impspec := spec.(*ast.ImportSpec)
			if oldImport != impspec {
				continue
			}

			// We found an import spec that imports path.
			// Delete it.
			deleted = true
			copy(gen.Specs[j:], gen.Specs[j+1:])
			gen.Specs = gen.Specs[:len(gen.Specs)-1]

			// If this was the last import spec in this decl,
			// delete the decl, too.
			if len(gen.Specs) == 0 {
				copy(f.Decls[i:], f.Decls[i+1:])
				f.Decls = f.Decls[:len(f.Decls)-1]
			} else if len(gen.Specs) == 1 {
				gen.Lparen = token.NoPos // drop parens
			}
			if j > 0 {
				// We deleted an entry but now there will be
				// a blank line-sized hole where the import was.
				// Close the hole by making the previous
				// import appear to "end" where this one did.
				gen.Specs[j-1].(*ast.ImportSpec).EndPos = impspec.End()
			}
			break
		}
	}

	// Delete it from f.Imports.
	for i, imp := range f.Imports {
		if imp == oldImport {
			copy(f.Imports[i:], f.Imports[i+1:])
			f.Imports = f.Imports[:len(f.Imports)-1]
			break
		}
	}

	return
}

// deleteImport deletes the import path from the file f, if present.

deleteImport deletes the import path from the file f if present .


func rewriteImport(f *ast.File, oldPath, newPath string) (rewrote bool) {
	for _, imp := range f.Imports {
		if importPath(imp) == oldPath {
			rewrote = true
			// record old End, because the default is to compute
			// it using the length of imp.Path.Value.
			imp.EndPos = imp.End()
			imp.Path.Value = strconv.Quote(newPath)
		}
	}
	return
}

// rewriteImport rewrites any import of path oldPath to path newPath.

rewriteImport rewrites any import of path oldPath to path newPath .


func DefaultTicket() string {
	defaultTicketOnce.Do(func() {
		if IsDevAppServer() {
			defaultTicket = "testapp" + defaultTicketSuffix
			return
		}
		appID := partitionlessAppID()
		escAppID := strings.Replace(strings.Replace(appID, ":", "_", -1), ".", "_", -1)
		majVersion := VersionID(nil)
		if i := strings.Index(majVersion, "."); i > 0 {
			majVersion = majVersion[:i]
		}
		defaultTicket = fmt.Sprintf("%s/%s.%s.%s", escAppID, ModuleName(nil), majVersion, InstanceID())
	})
	return defaultTicket
}

func DefaultTicket ( ) string { defaultTicketOnce . Do ( func ( ) { if IsDevAppServer ( ) { defaultTicket = " " + defaultTicketSuffix return } appID := partitionlessAppID ( ) escAppID := strings . Replace ( strings . Replace ( appID , " " , " " , - 1 ) , " " , " " , - 1 ) majVersion := VersionID ( nil ) if i := strings . Index ( majVersion , " " ) ; i > 0 { majVersion = majVersion [ : i ] } defaultTicket = fmt . Sprintf ( " " , escAppID , ModuleName ( nil ) , majVersion , InstanceID ( ) ) } ) return defaultTicket }

// DefaultTicket returns a ticket used for background context or dev_appserver.

DefaultTicket returns a ticket used for background context or dev_appserver .


func (c *context) flushLog(force bool) (flushed bool) {
	c.pendingLogs.Lock()
	// Grab up to 30 MB. We can get away with up to 32 MB, but let's be cautious.
	n, rem := 0, 30<<20
	for ; n < len(c.pendingLogs.lines); n++ {
		ll := c.pendingLogs.lines[n]
		// Each log line will require about 3 bytes of overhead.
		nb := proto.Size(ll) + 3
		if nb > rem {
			break
		}
		rem -= nb
	}
	lines := c.pendingLogs.lines[:n]
	c.pendingLogs.lines = c.pendingLogs.lines[n:]
	c.pendingLogs.Unlock()

	if len(lines) == 0 && !force {
		// Nothing to flush.
		return false
	}

	rescueLogs := false
	defer func() {
		if rescueLogs {
			c.pendingLogs.Lock()
			c.pendingLogs.lines = append(lines, c.pendingLogs.lines...)
			c.pendingLogs.Unlock()
		}
	}()

	buf, err := proto.Marshal(&logpb.UserAppLogGroup{
		LogLine: lines,
	})
	if err != nil {
		log.Printf("internal.flushLog: marshaling UserAppLogGroup: %v", err)
		rescueLogs = true
		return false
	}

	req := &logpb.FlushRequest{
		Logs: buf,
	}
	res := &basepb.VoidProto{}
	c.pendingLogs.Lock()
	c.pendingLogs.flushes++
	c.pendingLogs.Unlock()
	if err := Call(toContext(c), "logservice", "Flush", req, res); err != nil {
		log.Printf("internal.flushLog: Flush RPC: %v", err)
		rescueLogs = true
		return false
	}
	return true
}

// flushLog attempts to flush any pending logs to the appserver.
// It should not be called concurrently.

flushLog attempts to flush any pending logs to the appserver . It should not be called concurrently .


func withDeadline(parent context.Context, deadline time.Time) (context.Context, context.CancelFunc) {
	if deadline.IsZero() {
		return parent, func() {}
	}
	return context.WithDeadline(parent, deadline)
}

func withDeadline ( parent context . Context , deadline time . Time ) ( context . Context , context . CancelFunc ) { if deadline . IsZero ( ) { return parent , func ( ) { } } return context . WithDeadline ( parent , deadline ) }

// withDeadline is like context.WithDeadline, except it ignores the zero deadline.

withDeadline is like context . WithDeadline except it ignores the zero deadline .


func (cn *Conn) KeepAlive() error {
	req := &pb.GetSocketNameRequest{
		SocketDescriptor: &cn.desc,
	}
	res := &pb.GetSocketNameReply{}
	return internal.Call(cn.ctx, "remote_socket", "GetSocketName", req, res)
}

func ( cn * Conn ) KeepAlive ( ) error { req := & pb . GetSocketNameRequest { SocketDescriptor : & cn . desc , } res := & pb . GetSocketNameReply { } return internal . Call ( cn . ctx , " " , " " , req , res ) }

// KeepAlive signals that the connection is still in use.
// It may be called to prevent the socket being closed due to inactivity.

KeepAlive signals that the connection is still in use . It may be called to prevent the socket being closed due to inactivity .


func applyTransaction(pb proto.Message, t *pb.Transaction) {
	v := reflect.ValueOf(pb)
	if f, ok := transactionSetters[v.Type()]; ok {
		f.Call([]reflect.Value{v, reflect.ValueOf(t)})
	}
}

func applyTransaction ( pb proto . Message , t * pb . Transaction ) { v := reflect . ValueOf ( pb ) if f , ok := transactionSetters [ v . Type ( ) ] ; ok { f . Call ( [ ] reflect . Value { v , reflect . ValueOf ( t ) } ) } }

// applyTransaction applies the transaction t to message pb
// by using the relevant setter passed to RegisterTransactionSetter.

applyTransaction applies the transaction t to message pb by using the relevant setter passed to RegisterTransactionSetter .


func analyze(tags []string) (*app, error) {
	ctxt := buildContext(tags)
	hasMain, appFiles, err := checkMain(ctxt)
	if err != nil {
		return nil, err
	}
	gopath := filepath.SplitList(ctxt.GOPATH)
	im, err := imports(ctxt, *rootDir, gopath)
	return &app{
		hasMain:  hasMain,
		appFiles: appFiles,
		imports:  im,
	}, err
}

func analyze ( tags [ ] string ) ( * app , error ) { ctxt := buildContext ( tags ) hasMain , appFiles , err := checkMain ( ctxt ) if err != nil { return nil , err } gopath := filepath . SplitList ( ctxt . GOPATH ) im , err := imports ( ctxt , * rootDir , gopath ) return & app { hasMain : hasMain , appFiles : appFiles , imports : im , } , err }

// analyze checks the app for building with the given build tags and returns hasMain,
// app files, and a map of full directory import names to original import names.

analyze checks the app for building with the given build tags and returns hasMain app files and a map of full directory import names to original import names .


func buildContext(tags []string) *build.Context {
	return &build.Context{
		GOARCH:    build.Default.GOARCH,
		GOOS:      build.Default.GOOS,
		GOROOT:    build.Default.GOROOT,
		GOPATH:    build.Default.GOPATH,
		Compiler:  build.Default.Compiler,
		BuildTags: append(build.Default.BuildTags, tags...),
	}
}

func buildContext ( tags [ ] string ) * build . Context { return & build . Context { GOARCH : build . Default . GOARCH , GOOS : build . Default . GOOS , GOROOT : build . Default . GOROOT , GOPATH : build . Default . GOPATH , Compiler : build . Default . Compiler , BuildTags : append ( build . Default . BuildTags , tags ... ) , } }

// buildContext returns the context for building the source.

buildContext returns the context for building the source .


func synthesizeMain(tw *tar.Writer, appFiles []string) error {
	appMap := make(map[string]bool)
	for _, f := range appFiles {
		appMap[f] = true
	}
	var f string
	for i := 0; i < 100; i++ {
		f = fmt.Sprintf("app_main%d.go", i)
		if !appMap[filepath.Join(*rootDir, f)] {
			break
		}
	}
	if appMap[filepath.Join(*rootDir, f)] {
		return fmt.Errorf("unable to find unique name for %v", f)
	}
	hdr := &tar.Header{
		Name: f,
		Mode: 0644,
		Size: int64(len(newMain)),
	}
	if err := tw.WriteHeader(hdr); err != nil {
		return fmt.Errorf("unable to write header for %v: %v", f, err)
	}
	if _, err := tw.Write([]byte(newMain)); err != nil {
		return fmt.Errorf("unable to write %v to tar file: %v", f, err)
	}
	return nil
}

func synthesizeMain ( tw * tar . Writer , appFiles [ ] string ) error { appMap := make ( map [ string ] bool ) for _ , f := range appFiles { appMap [ f ] = true } var f string for i := 0 ; i < 100 ; i ++ { f = fmt . Sprintf ( " " , i ) if ! appMap [ filepath . Join ( * rootDir , f ) ] { break } } if appMap [ filepath . Join ( * rootDir , f ) ] { return fmt . Errorf ( " " , f ) } hdr := & tar . Header { Name : f , Mode : 0644 , Size : int64 ( len ( newMain ) ) , } if err := tw . WriteHeader ( hdr ) ; err != nil { return fmt . Errorf ( " " , f , err ) } if _ , err := tw . Write ( [ ] byte ( newMain ) ) ; err != nil { return fmt . Errorf ( " " , f , err ) } return nil }

// synthesizeMain generates a new main func and writes it to the tarball.

synthesizeMain generates a new main func and writes it to the tarball .


func findInGopath(dir string, gopath []string) (string, error) {
	for _, v := range gopath {
		dst := filepath.Join(v, "src", dir)
		if _, err := os.Stat(dst); err == nil {
			return dst, nil
		}
	}
	return "", fmt.Errorf("unable to find package %v in gopath %v", dir, gopath)
}

func findInGopath ( dir string , gopath [ ] string ) ( string , error ) { for _ , v := range gopath { dst := filepath . Join ( v , " " , dir ) if _ , err := os . Stat ( dst ) ; err == nil { return dst , nil } } return " " , fmt . Errorf ( " " , dir , gopath ) }

// findInGopath searches the gopath for the named import directory.

findInGopath searches the gopath for the named import directory .


func copyTree(tw *tar.Writer, dstDir, srcDir string) error {
	entries, err := ioutil.ReadDir(srcDir)
	if err != nil {
		return fmt.Errorf("unable to read dir %v: %v", srcDir, err)
	}
	for _, entry := range entries {
		n := entry.Name()
		if skipFiles[n] {
			continue
		}
		s := filepath.Join(srcDir, n)
		d := filepath.Join(dstDir, n)
		if entry.IsDir() {
			if err := copyTree(tw, d, s); err != nil {
				return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err)
			}
			continue
		}
		if err := copyFile(tw, d, s); err != nil {
			return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err)
		}
	}
	return nil
}

func copyTree ( tw * tar . Writer , dstDir , srcDir string ) error { entries , err := ioutil . ReadDir ( srcDir ) if err != nil { return fmt . Errorf ( " " , srcDir , err ) } for _ , entry := range entries { n := entry . Name ( ) if skipFiles [ n ] { continue } s := filepath . Join ( srcDir , n ) d := filepath . Join ( dstDir , n ) if entry . IsDir ( ) { if err := copyTree ( tw , d , s ) ; err != nil { return fmt . Errorf ( " " , s , d , err ) } continue } if err := copyFile ( tw , d , s ) ; err != nil { return fmt . Errorf ( " " , s , d , err ) } } return nil }

// copyTree copies srcDir to tar file dstDir, ignoring skipFiles.

copyTree copies srcDir to tar file dstDir ignoring skipFiles .


func copyFile(tw *tar.Writer, dst, src string) error {
	s, err := os.Open(src)
	if err != nil {
		return fmt.Errorf("unable to open %v: %v", src, err)
	}
	defer s.Close()
	fi, err := s.Stat()
	if err != nil {
		return fmt.Errorf("unable to stat %v: %v", src, err)
	}

	hdr, err := tar.FileInfoHeader(fi, dst)
	if err != nil {
		return fmt.Errorf("unable to create tar header for %v: %v", dst, err)
	}
	hdr.Name = dst
	if err := tw.WriteHeader(hdr); err != nil {
		return fmt.Errorf("unable to write header for %v: %v", dst, err)
	}
	_, err = io.Copy(tw, s)
	if err != nil {
		return fmt.Errorf("unable to copy %v to %v: %v", src, dst, err)
	}
	return nil
}

func copyFile ( tw * tar . Writer , dst , src string ) error { s , err := os . Open ( src ) if err != nil { return fmt . Errorf ( " " , src , err ) } defer s . Close ( ) fi , err := s . Stat ( ) if err != nil { return fmt . Errorf ( " " , src , err ) } hdr , err := tar . FileInfoHeader ( fi , dst ) if err != nil { return fmt . Errorf ( " " , dst , err ) } hdr . Name = dst if err := tw . WriteHeader ( hdr ) ; err != nil { return fmt . Errorf ( " " , dst , err ) } _ , err = io . Copy ( tw , s ) if err != nil { return fmt . Errorf ( " " , src , dst , err ) } return nil }


func checkMain(ctxt *build.Context) (bool, []string, error) {
	pkg, err := ctxt.ImportDir(*rootDir, 0)
	if err != nil {
		return false, nil, fmt.Errorf("unable to analyze source: %v", err)
	}
	if !pkg.IsCommand() {
		errorf("Your app's package needs to be changed from %q to \"main\".\n", pkg.Name)
	}
	// Search for a "func main"
	var hasMain bool
	var appFiles []string
	for _, f := range pkg.GoFiles {
		n := filepath.Join(*rootDir, f)
		appFiles = append(appFiles, n)
		if hasMain, err = readFile(n); err != nil {
			return false, nil, fmt.Errorf("error parsing %q: %v", n, err)
		}
	}
	return hasMain, appFiles, nil
}

func
checkMain
(
ctxt
*
build
.
Context
)
(
bool
,
[
]
string
,
error
)
{
pkg
,
err
:=
ctxt
.
ImportDir
(
*
rootDir
,
0
)
if
err
!=
{
return
false
,
,
fmt
.
Errorf
(
"
"
,
err
)
}
if
!
pkg
.
IsCommand
(
)
{
errorf
(
"
\"
\"
\n
"
,
pkg
.
Name
)
}
// Search for a "func main"
var
hasMain
bool
var
appFiles
[
]
string
for
_
,
f
:=
range
pkg
.
GoFiles
{
n
:=
filepath
.
Join
(
*
rootDir
,
f
)
appFiles
=
append
(
appFiles
,
n
)
if
hasMain
,
err
=
readFile
(
n
)
;
err
!=
{
return
false
,
,
fmt
.
Errorf
(
"
"
,
n
,
err
)
}
}
return
hasMain
,
appFiles
,
}

// checkMain verifies that there is a single "main" function.
// It also returns a list of all Go source files in the app.

checkMain verifies that there is a single main function . It also returns a list of all Go source files in the app .


func isMain(f *ast.FuncDecl) bool {
	ft := f.Type
	return f.Name.Name == "main" && f.Recv == nil && ft.Params.NumFields() == 0 && ft.Results.NumFields() == 0
}

func isMain ( f * ast . FuncDecl ) bool { ft := f . Type return f . Name . Name == " " && f . Recv == nil && ft . Params . NumFields ( ) == 0 && ft . Results . NumFields ( ) == 0 }

// isMain returns whether the given function declaration is a main function.
// Such a function must be called "main", not have a receiver, and have no arguments or return types.

isMain returns whether the given function declaration is a main function . Such a function must be called main not have a receiver and have no arguments or return types .


func readFile(filename string) (hasMain bool, err error) {
	var src []byte
	src, err = ioutil.ReadFile(filename)
	if err != nil {
		return
	}
	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, filename, src, 0)
	for _, decl := range file.Decls {
		funcDecl, ok := decl.(*ast.FuncDecl)
		if !ok {
			continue
		}
		if !isMain(funcDecl) {
			continue
		}
		hasMain = true
		break
	}
	return
}

func readFile ( filename string ) ( hasMain bool , err error ) { var src [ ] byte src , err = ioutil . ReadFile ( filename ) if err != nil { return } fset := token . NewFileSet ( ) file , err := parser . ParseFile ( fset , filename , src , 0 ) for _ , decl := range file . Decls { funcDecl , ok := decl . ( * ast . FuncDecl ) if ! ok { continue } if ! isMain ( funcDecl ) { continue } hasMain = true break } return }

// readFile reads and parses the Go source code file and returns whether it has a main function.

readFile reads and parses the Go source code file and returns whether it has a main function .


func initField(val reflect.Value, index []int) reflect.Value {
	for _, i := range index[:len(index)-1] {
		val = val.Field(i)
		if val.Kind() == reflect.Ptr {
			if val.IsNil() {
				val.Set(reflect.New(val.Type().Elem()))
			}
			val = val.Elem()
		}
	}
	return val.Field(index[len(index)-1])
}

func initField ( val reflect . Value , index [ ] int ) reflect . Value { for _ , i := range index [ : len ( index ) - 1 ] { val = val . Field ( i ) if val . Kind ( ) == reflect . Ptr { if val . IsNil ( ) { val . Set ( reflect . New ( val . Type ( ) . Elem ( ) ) ) } val = val . Elem ( ) } } return val . Field ( index [ len ( index ) - 1 ] ) }

// initField is similar to reflect's Value.FieldByIndex, in that it
// returns the nested struct field corresponding to index, but it
// initialises any nil pointers encountered when traversing the structure.

initField is similar to reflect s Value . FieldByIndex in that it returns the nested struct field corresponding to index but it initialises any nil pointers encountered when traversing the structure .


func loadEntity(dst interface{}, src *pb.EntityProto) (err error) {
	ent, err := protoToEntity(src)
	if err != nil {
		return err
	}
	if e, ok := dst.(PropertyLoadSaver); ok {
		return e.Load(ent.Properties)
	}
	return LoadStruct(dst, ent.Properties)
}

func loadEntity ( dst interface { } , src * pb . EntityProto ) ( err error ) { ent , err := protoToEntity ( src ) if err != nil { return err } if e , ok := dst . ( PropertyLoadSaver ) ; ok { return e . Load ( ent . Properties ) } return LoadStruct ( dst , ent . Properties ) }

// loadEntity loads an EntityProto into PropertyLoadSaver or struct pointer.

loadEntity loads an EntityProto into PropertyLoadSaver or struct pointer .


func validIndexNameOrDocID(s string) bool {
	if strings.HasPrefix(s, "!") {
		return false
	}
	for _, c := range s {
		if c < 0x21 || 0x7f <= c {
			return false
		}
	}
	return true
}

func validIndexNameOrDocID ( s string ) bool { if strings . HasPrefix ( s , " " ) { return false } for _ , c := range s { if c < 0x21 || 0x7f <= c { return false } } return true }

// validIndexNameOrDocID is the Go equivalent of Python's
// _ValidateVisiblePrintableAsciiNotReserved.


func Open(name string) (*Index, error) {
	if !validIndexNameOrDocID(name) {
		return nil, fmt.Errorf("search: invalid index name %q", name)
	}
	return &Index{
		spec: pb.IndexSpec{
			Name: &name,
		},
	}, nil
}

func Open ( name string ) ( * Index , error ) { if ! validIndexNameOrDocID ( name ) { return nil , fmt . Errorf ( " " , name ) } return & Index { spec : pb . IndexSpec { Name : & name , } , } , nil }

// Open opens the index with the given name. The index is created if it does
// not already exist.
//
// The name is a human-readable ASCII string. It must contain no whitespace
// characters and not start with "!".

Open opens the index with the given name . The index is created if it does not already exist . The name is a human - readable ASCII string . It must contain no whitespace characters and not start with ! .


func (x *Index) Put(c context.Context, id string, src interface{}) (string, error) {
	ids, err := x.PutMulti(c, []string{id}, []interface{}{src})
	if err != nil {
		return "", err
	}
	return ids[0], nil
}

func ( x * Index ) Put ( c context . Context , id string , src interface { } ) ( string , error ) { ids , err := x . PutMulti ( c , [ ] string { id } , [ ] interface { } { src } ) if err != nil { return " " , err } return ids [ 0 ] , nil }

// Put saves src to the index. If id is empty, a new ID is allocated by the
// service and returned. If id is not empty, any existing index entry for that
// ID is replaced.
//
// The ID is a human-readable ASCII string. It must contain no whitespace
// characters and not start with "!".
//
// src must be a non-nil struct pointer or implement the FieldLoadSaver
// interface.

Put saves src to the index . If id is empty a new ID is allocated by the service and returned . If id is not empty any existing index entry for that ID is replaced . The ID is a human - readable ASCII string . It must contain no whitespace characters and not start with ! . src must be a non - nil struct pointer or implement the FieldLoadSaver interface .


func (x *Index) Get(c context.Context, id string, dst interface{}) error {
	if id == "" || !validIndexNameOrDocID(id) {
		return fmt.Errorf("search: invalid ID %q", id)
	}
	req := &pb.ListDocumentsRequest{
		Params: &pb.ListDocumentsParams{
			IndexSpec:  &x.spec,
			StartDocId: proto.String(id),
			Limit:      proto.Int32(1),
		},
	}
	res := &pb.ListDocumentsResponse{}
	if err := internal.Call(c, "search", "ListDocuments", req, res); err != nil {
		return err
	}
	if res.Status == nil || res.Status.GetCode() != pb.SearchServiceError_OK {
		return fmt.Errorf("search: %s: %s", res.Status.GetCode(), res.Status.GetErrorDetail())
	}
	if len(res.Document) != 1 || res.Document[0].GetId() != id {
		return ErrNoSuchDocument
	}
	return loadDoc(dst, res.Document[0], nil)
}

func ( x * Index ) Get ( c context . Context , id string , dst interface { } ) error { if id == " " || ! validIndexNameOrDocID ( id ) { return fmt . Errorf ( " " , id ) } req := & pb . ListDocumentsRequest { Params : & pb . ListDocumentsParams { IndexSpec : & x . spec , StartDocId : proto . String ( id ) , Limit : proto . Int32 ( 1 ) , } , } res := & pb . ListDocumentsResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return err } if res . Status == nil || res . Status . GetCode ( ) != pb . SearchServiceError_OK { return fmt . Errorf ( " " , res . Status . GetCode ( ) , res . Status . GetErrorDetail ( ) ) } if len ( res . Document ) != 1 || res . Document [ 0 ] . GetId ( ) != id { return ErrNoSuchDocument } return loadDoc ( dst , res . Document [ 0 ] , nil ) }

// Get loads the document with the given ID into dst.
//
// The ID is a human-readable ASCII string. It must be non-empty, contain no
// whitespace characters and not start with "!".
//
// dst must be a non-nil struct pointer or implement the FieldLoadSaver
// interface.
//
// ErrFieldMismatch is returned when a field is to be loaded into a different
// type than the one it was stored from, or when a field is missing or
// unexported in the destination struct. ErrFieldMismatch is only returned if
// dst is a struct pointer. It is up to the callee to decide whether this error
// is fatal, recoverable, or ignorable.

Get loads the document with the given ID into dst . The ID is a human - readable ASCII string . It must be non - empty contain no whitespace characters and not start with ! . dst must be a non - nil struct pointer or implement the FieldLoadSaver interface . ErrFieldMismatch is returned when a field is to be loaded into a different type than the one it was stored from or when a field is missing or unexported in the destination struct . ErrFieldMismatch is only returned if dst is a struct pointer . It is up to the callee to decide whether this error is fatal recoverable or ignorable .


func (x *Index) Delete(c context.Context, id string) error {
	return x.DeleteMulti(c, []string{id})
}

func ( x * Index ) Delete ( c context . Context , id string ) error { return x . DeleteMulti ( c , [ ] string { id } ) }

// Delete deletes a document from the index.

Delete deletes a document from the index .


func (x *Index) DeleteMulti(c context.Context, ids []string) error {
	if len(ids) > maxDocumentsPerPutDelete {
		return ErrTooManyDocuments
	}

	req := &pb.DeleteDocumentRequest{
		Params: &pb.DeleteDocumentParams{
			DocId:     ids,
			IndexSpec: &x.spec,
		},
	}
	res := &pb.DeleteDocumentResponse{}
	if err := internal.Call(c, "search", "DeleteDocument", req, res); err != nil {
		return err
	}
	if len(res.Status) != len(ids) {
		return fmt.Errorf("search: internal error: wrong number of results (%d, expected %d)",
			len(res.Status), len(ids))
	}
	multiErr, hasErr := make(appengine.MultiError, len(ids)), false
	for i, s := range res.Status {
		if s.GetCode() != pb.SearchServiceError_OK {
			multiErr[i] = fmt.Errorf("search: %s: %s", s.GetCode(), s.GetErrorDetail())
			hasErr = true
		}
	}
	if hasErr {
		return multiErr
	}
	return nil
}

func ( x * Index ) DeleteMulti ( c context . Context , ids [ ] string ) error { if len ( ids ) > maxDocumentsPerPutDelete { return ErrTooManyDocuments } req := & pb . DeleteDocumentRequest { Params : & pb . DeleteDocumentParams { DocId : ids , IndexSpec : & x . spec , } , } res := & pb . DeleteDocumentResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return err } if len ( res . Status ) != len ( ids ) { return fmt . Errorf ( " " , len ( res . Status ) , len ( ids ) ) } multiErr , hasErr := make ( appengine . MultiError , len ( ids ) ) , false for i , s := range res . Status { if s . GetCode ( ) != pb . SearchServiceError_OK { multiErr [ i ] = fmt . Errorf ( " " , s . GetCode ( ) , s . GetErrorDetail ( ) ) hasErr = true } } if hasErr { return multiErr } return nil }

// DeleteMulti deletes multiple documents from the index.
//
// The returned error may be an instance of appengine.MultiError, in which case
// it will be the same size as srcs and the individual errors inside will
// correspond with the items in srcs.

DeleteMulti deletes multiple documents from the index . The returned error may be an instance of appengine . MultiError in which case it will be the same size as srcs and the individual errors inside will correspond with the items in srcs .


func (x *Index) Search(c context.Context, query string, opts *SearchOptions) *Iterator {
	t := &Iterator{
		c:           c,
		index:       x,
		searchQuery: query,
		more:        moreSearch,
	}
	if opts != nil {
		if opts.Cursor != "" {
			if opts.Offset != 0 {
				return errIter("at most one of Cursor and Offset may be specified")
			}
			t.searchCursor = proto.String(string(opts.Cursor))
		}
		t.limit = opts.Limit
		t.fields = opts.Fields
		t.idsOnly = opts.IDsOnly
		t.sort = opts.Sort
		t.exprs = opts.Expressions
		t.refinements = opts.Refinements
		t.facetOpts = opts.Facets
		t.searchOffset = opts.Offset
		t.countAccuracy = opts.CountAccuracy
	}
	return t
}

func ( x * Index ) Search ( c context . Context , query string , opts * SearchOptions ) * Iterator { t := & Iterator { c : c , index : x , searchQuery : query , more : moreSearch , } if opts != nil { if opts . Cursor != " " { if opts . Offset != 0 { return errIter ( " " ) } t . searchCursor = proto . String ( string ( opts . Cursor ) ) } t . limit = opts . Limit t . fields = opts . Fields t . idsOnly = opts . IDsOnly t . sort = opts . Sort t . exprs = opts . Expressions t . refinements = opts . Refinements t . facetOpts = opts . Facets t . searchOffset = opts . Offset t . countAccuracy = opts . CountAccuracy } return t }

// Search searches the index for the given query.

Search searches the index for the given query .


func (t *Iterator) fetchMore() {
	if t.err == nil && len(t.listRes)+len(t.searchRes) == 0 && t.more != nil {
		t.err = t.more(t)
	}
}

func ( t * Iterator ) fetchMore ( ) { if t . err == nil && len ( t . listRes ) + len ( t . searchRes ) == 0 && t . more != nil { t . err = t . more ( t ) } }

// fetchMore retrieves more results, if there are no errors or pending results.

fetchMore retrieves more results if there are no errors or pending results .


func (t *Iterator) Next(dst interface{}) (string, error) {
	t.fetchMore()
	if t.err != nil {
		return "", t.err
	}

	var doc *pb.Document
	var exprs []*pb.Field
	switch {
	case len(t.listRes) != 0:
		doc = t.listRes[0]
		t.listRes = t.listRes[1:]
	case len(t.searchRes) != 0:
		doc = t.searchRes[0].Document
		exprs = t.searchRes[0].Expression
		t.searchCursor = t.searchRes[0].Cursor
		t.searchRes = t.searchRes[1:]
	default:
		return "", Done
	}
	if doc == nil {
		return "", errors.New("search: internal error: no document returned")
	}
	if !t.idsOnly && dst != nil {
		if err := loadDoc(dst, doc, exprs); err != nil {
			return "", err
		}
	}
	return doc.GetId(), nil
}

func ( t * Iterator ) Next ( dst interface { } ) ( string , error ) { t . fetchMore ( ) if t . err != nil { return " " , t . err } var doc * pb . Document var exprs [ ] * pb . Field switch { case len ( t . listRes ) != 0 : doc = t . listRes [ 0 ] t . listRes = t . listRes [ 1 : ] case len ( t . searchRes ) != 0 : doc = t . searchRes [ 0 ] . Document exprs = t . searchRes [ 0 ] . Expression t . searchCursor = t . searchRes [ 0 ] . Cursor t . searchRes = t . searchRes [ 1 : ] default : return " " , Done } if doc == nil { return " " , errors . New ( " " ) } if ! t . idsOnly && dst != nil { if err := loadDoc ( dst , doc , exprs ) ; err != nil { return " " , err } } return doc . GetId ( ) , nil }

// Next returns the ID of the next result. When there are no more results,
// Done is returned as the error.
//
// dst must be a non-nil struct pointer, implement the FieldLoadSaver
// interface, or be a nil interface value. If a non-nil dst is provided, it
// will be filled with the indexed fields. dst is ignored if this iterator was
// created with an IDsOnly option.

Next returns the ID of the next result . When there are no more results Done is returned as the error . dst must be a non - nil struct pointer implement the FieldLoadSaver interface or be a nil interface value . If a non - nil dst is provided it will be filled with the indexed fields . dst is ignored if this iterator was created with an IDsOnly option .


func (t *Iterator) Facets() ([][]FacetResult, error) {
	t.fetchMore()
	if t.err != nil && t.err != Done {
		return nil, t.err
	}

	var facets [][]FacetResult
	for _, f := range t.facetRes {
		fres := make([]FacetResult, 0, len(f.Value))
		for _, v := range f.Value {
			ref := v.Refinement
			facet := FacetResult{
				Facet: Facet{Name: ref.GetName()},
				Count: int(v.GetCount()),
			}
			if ref.Value != nil {
				facet.Value = Atom(*ref.Value)
			} else {
				facet.Value = protoToRange(ref.Range)
			}
			fres = append(fres, facet)
		}
		facets = append(facets, fres)
	}
	return facets, nil
}

func ( t * Iterator ) Facets ( ) ( [ ] [ ] FacetResult , error ) { t . fetchMore ( ) if t . err != nil && t . err != Done { return nil , t . err } var facets [ ] [ ] FacetResult for _ , f := range t . facetRes { fres := make ( [ ] FacetResult , 0 , len ( f . Value ) ) for _ , v := range f . Value { ref := v . Refinement facet := FacetResult { Facet : Facet { Name : ref . GetName ( ) } , Count : int ( v . GetCount ( ) ) , } if ref . Value != nil { facet . Value = Atom ( * ref . Value ) } else { facet . Value = protoToRange ( ref . Range ) } fres = append ( fres , facet ) } facets = append ( facets , fres ) } return facets , nil }

// Facets returns the facets found within the search results, if any facets
// were requested in the SearchOptions.

Facets returns the facets found within the search results if any facets were requested in the SearchOptions .


func DefaultBucketName(c context.Context) (string, error) {
	req := &aipb.GetDefaultGcsBucketNameRequest{}
	res := &aipb.GetDefaultGcsBucketNameResponse{}

	err := internal.Call(c, "app_identity_service", "GetDefaultGcsBucketName", req, res)
	if err != nil {
		return "", fmt.Errorf("file: no default bucket name returned in RPC response: %v", res)
	}
	return res.GetDefaultGcsBucketName(), nil
}

func DefaultBucketName ( c context . Context ) ( string , error ) { req := & aipb . GetDefaultGcsBucketNameRequest { } res := & aipb . GetDefaultGcsBucketNameResponse { } err := internal . Call ( c , " " , " " , req , res ) if err != nil { return " " , fmt . Errorf ( " " , res ) } return res . GetDefaultGcsBucketName ( ) , nil }

// DefaultBucketName returns the name of this application's
// default Google Cloud Storage bucket.

DefaultBucketName returns the name of this application s default Google Cloud Storage bucket .


func (k *Key) valid() bool {
	if k == nil {
		return false
	}
	for ; k != nil; k = k.parent {
		if k.kind == "" || k.appID == "" {
			return false
		}
		if k.stringID != "" && k.intID != 0 {
			return false
		}
		if k.parent != nil {
			if k.parent.Incomplete() {
				return false
			}
			if k.parent.appID != k.appID || k.parent.namespace != k.namespace {
				return false
			}
		}
	}
	return true
}

func ( k * Key ) valid ( ) bool { if k == nil { return false } for ; k != nil ; k = k . parent { if k . kind == " " || k . appID == " " { return false } if k . stringID != " " && k . intID != 0 { return false } if k . parent != nil { if k . parent . Incomplete ( ) { return false } if k . parent . appID != k . appID || k . parent . namespace != k . namespace { return false } } } return true }

// valid returns whether the key is valid.

valid returns whether the key is valid .


func (k *Key) Equal(o *Key) bool {
	for k != nil && o != nil {
		if k.kind != o.kind || k.stringID != o.stringID || k.intID != o.intID || k.appID != o.appID || k.namespace != o.namespace {
			return false
		}
		k, o = k.parent, o.parent
	}
	return k == o
}

func ( k * Key ) Equal ( o * Key ) bool { for k != nil && o != nil { if k . kind != o . kind || k . stringID != o . stringID || k . intID != o . intID || k . appID != o . appID || k . namespace != o . namespace { return false } k , o = k . parent , o . parent } return k == o }

// Equal returns whether two keys are equal.

Equal returns whether two keys are equal .


func (k *Key) root() *Key {
	for k.parent != nil {
		k = k.parent
	}
	return k
}

func ( k * Key ) root ( ) * Key { for k . parent != nil { k = k . parent } return k }

// root returns the furthest ancestor of a key, which may be itself.

root returns the furthest ancestor of a key which may be itself .


func (k *Key) marshal(b *bytes.Buffer) {
	if k.parent != nil {
		k.parent.marshal(b)
	}
	b.WriteByte('/')
	b.WriteString(k.kind)
	b.WriteByte(',')
	if k.stringID != "" {
		b.WriteString(k.stringID)
	} else {
		b.WriteString(strconv.FormatInt(k.intID, 10))
	}
}

func ( k * Key ) marshal ( b * bytes . Buffer ) { if k . parent != nil { k . parent . marshal ( b ) } b . WriteByte ( '/' ) b . WriteString ( k . kind ) b . WriteByte ( ',' ) if k . stringID != " " { b . WriteString ( k . stringID ) } else { b . WriteString ( strconv . FormatInt ( k . intID , 10 ) ) } }

// marshal marshals the key's string representation to the buffer.

marshal marshals the key s string representation to the buffer .


func (k *Key) String() string {
	if k == nil {
		return ""
	}
	b := bytes.NewBuffer(make([]byte, 0, 512))
	k.marshal(b)
	return b.String()
}

func ( k * Key ) String ( ) string { if k == nil { return " " } b := bytes . NewBuffer ( make ( [ ] byte , 0 , 512 ) ) k . marshal ( b ) return b . String ( ) }

// String returns a string representation of the key.

String returns a string representation of the key .


func (k *Key) Encode() string {
	ref := keyToProto("", k)

	b, err := proto.Marshal(ref)
	if err != nil {
		panic(err)
	}

	// Trailing padding is stripped.
	return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=")
}

func
(
k
*
Key
)
Encode
(
)
string
{
ref
:=
keyToProto
(
"
"
,
k
)
b
,
err
:=
proto
.
Marshal
(
ref
)
if
err
!=
{
panic
(
err
)
}
// Trailing padding is stripped.
return
strings
.
TrimRight
(
base64
.
URLEncoding
.
EncodeToString
(
b
)
,
"
"
)
}

// Encode returns an opaque representation of the key
// suitable for use in HTML and URLs.
// This is compatible with the Python and Java runtimes.

Encode returns an opaque representation of the key suitable for use in HTML and URLs . This is compatible with the Python and Java runtimes .


func DecodeKey(encoded string) (*Key, error) {
	// Re-add padding.
	if m := len(encoded) % 4; m != 0 {
		encoded += strings.Repeat("=", 4-m)
	}

	b, err := base64.URLEncoding.DecodeString(encoded)
	if err != nil {
		return nil, err
	}

	ref := new(pb.Reference)
	if err := proto.Unmarshal(b, ref); err != nil {
		return nil, err
	}

	return protoToKey(ref)
}

func
DecodeKey
(
encoded
string
)
(
*
Key
,
error
)
{
// Re-add padding.
if
m
:=
len
(
encoded
)
%
4
;
m
!=
0
{
encoded
+=
strings
.
Repeat
(
"
"
,
4
m
)
}
b
,
err
:=
base64
.
URLEncoding
.
DecodeString
(
encoded
)
if
err
!=
{
return
,
err
}
ref
:=
new
(
pb
.
Reference
)
if
err
:=
proto
.
Unmarshal
(
b
,
ref
)
;
err
!=
{
return
,
err
}
return
protoToKey
(
ref
)
}

// DecodeKey decodes a key from the opaque representation returned by Encode.

DecodeKey decodes a key from the opaque representation returned by Encode .


func NewIncompleteKey(c context.Context, kind string, parent *Key) *Key {
	return NewKey(c, kind, "", 0, parent)
}

func NewIncompleteKey ( c context . Context , kind string , parent * Key ) * Key { return NewKey ( c , kind , " " , 0 , parent ) }

// NewIncompleteKey creates a new incomplete key.
// kind cannot be empty.

NewIncompleteKey creates a new incomplete key . kind cannot be empty .


func NewKey(c context.Context, kind, stringID string, intID int64, parent *Key) *Key {
	// If there's a parent key, use its namespace.
	// Otherwise, use any namespace attached to the context.
	var namespace string
	if parent != nil {
		namespace = parent.namespace
	} else {
		namespace = internal.NamespaceFromContext(c)
	}

	return &Key{
		kind:      kind,
		stringID:  stringID,
		intID:     intID,
		parent:    parent,
		appID:     internal.FullyQualifiedAppID(c),
		namespace: namespace,
	}
}

// NewKey creates a new key.
// kind cannot be empty.
// Either one or both of stringID and intID must be zero. If both are zero,
// the key returned is incomplete.
// parent must either be a complete key or nil.

NewKey creates a new key . kind cannot be empty . Either one or both of stringID and intID must be zero . If both are zero the key returned is incomplete . parent must either be a complete key or nil .


func AllocateIDs(c context.Context, kind string, parent *Key, n int) (low, high int64, err error) {
	if kind == "" {
		return 0, 0, errors.New("datastore: AllocateIDs given an empty kind")
	}
	if n < 0 {
		return 0, 0, fmt.Errorf("datastore: AllocateIDs given a negative count: %d", n)
	}
	if n == 0 {
		return 0, 0, nil
	}
	req := &pb.AllocateIdsRequest{
		ModelKey: keyToProto("", NewIncompleteKey(c, kind, parent)),
		Size:     proto.Int64(int64(n)),
	}
	res := &pb.AllocateIdsResponse{}
	if err := internal.Call(c, "datastore_v3", "AllocateIds", req, res); err != nil {
		return 0, 0, err
	}
	// The protobuf is inclusive at both ends. Idiomatic Go (e.g. slices, for loops)
	// is inclusive at the low end and exclusive at the high end, so we add 1.
	low = res.GetStart()
	high = res.GetEnd() + 1
	if low+int64(n) != high {
		return 0, 0, fmt.Errorf("datastore: internal error: could not allocate %d IDs", n)
	}
	return low, high, nil
}

// AllocateIDs returns a range of n integer IDs with the given kind and parent
// combination. kind cannot be empty; parent may be nil. The IDs in the range
// returned will not be used by the datastore's automatic ID sequence generator
// and may be used with NewKey without conflict.
//
// The range is inclusive at the low end and exclusive at the high end. In
// other words, valid intIDs x satisfy low <= x && x < high.
//
// If no error is returned, low + n == high.

AllocateIDs returns a range of n integer IDs with the given kind and parent combination . kind cannot be empty ; parent may be nil . The IDs in the range returned will not be used by the datastore s automatic ID sequence generator and may be used with NewKey without conflict . The range is inclusive at the low end and exclusive at the high end . In other words valid intIDs x satisfy low < = x && x < high . If no error is returned low + n == high .


func IsOverQuota(err error) bool {
	callErr, ok := err.(*internal.CallError)
	return ok && callErr.Code == 4
}

func IsOverQuota ( err error ) bool { callErr , ok := err . ( * internal . CallError ) return ok && callErr . Code == 4 }

// IsOverQuota reports whether err represents an API call failure
// due to insufficient available quota.

IsOverQuota reports whether err represents an API call failure due to insufficient available quota .


func ClassicContextFromContext(ctx netcontext.Context) (appengine.Context, error) {
	c := fromContext(ctx)
	if c == nil {
		return nil, errNotAppEngineContext
	}
	return c, nil
}

func ClassicContextFromContext ( ctx netcontext . Context ) ( appengine . Context , error ) { c := fromContext ( ctx ) if c == nil { return nil , errNotAppEngineContext } return c , nil }

// This is only for classic App Engine adapters.

This is only for classic App Engine adapters .


func Send(c context.Context, msg *Message) error {
	return send(c, "Send", msg)
}

func Send ( c context . Context , msg * Message ) error { return send ( c , " " , msg ) }


func SendToAdmins(c context.Context, msg *Message) error {
	return send(c, "SendToAdmins", msg)
}

func SendToAdmins ( c context . Context , msg * Message ) error { return send ( c , " " , msg ) }

// SendToAdmins sends an email message to the application's administrators.

SendToAdmins sends an email message to the application s administrators .


func (r *Report) Failures() int {
	count := 0

	for _, p := range r.Packages {
		for _, t := range p.Tests {
			if t.Result == FAIL {
				count++
			}
		}
	}

	return count
}

func ( r * Report ) Failures ( ) int { count := 0 for _ , p := range r . Packages { for _ , t := range p . Tests { if t . Result == FAIL { count ++ } } } return count }

// Failures counts the number of failed tests in this report


func decodeFieldNumberAndTyp3(bz []byte) (num uint32, typ Typ3, n int, err error) {

	// Read uvarint value.
	var value64 = uint64(0)
	value64, n, err = DecodeUvarint(bz)
	if err != nil {
		return
	}

	// Decode first typ3 byte.
	typ = Typ3(value64 & 0x07)

	// Decode num.
	var num64 uint64
	num64 = value64 >> 3
	if num64 > (1<<29 - 1) {
		err = fmt.Errorf("invalid field num %v", num64)
		return
	}
	num = uint32(num64)
	return
}

func
decodeFieldNumberAndTyp3
(
bz
[
]
byte
)
(
num
uint32
,
typ
Typ3
,
n
int
,
err
error
)
{
// Read uvarint value.
var
value64
=
uint64
(
0
)
value64
,
n
,
err
=
DecodeUvarint
(
bz
)
if
err
!=
{
return
}
// Decode first typ3 byte.
typ
=
Typ3
(
value64
&
0x07
)
// Decode num.
var
num64
uint64
num64
=
value64
>>
3
if
num64
>
(
1
<<
29
1
)
{
err
=
fmt
.
Errorf
(
"
"
,
num64
)
return
}
num
=
uint32
(
num64
)
return
}


func checkTyp3(rt reflect.Type, typ Typ3, fopts FieldOptions) (err error) {
	typWanted := typeToTyp3(rt, fopts)
	if typ != typWanted {
		err = fmt.Errorf("unexpected Typ3. want %v, got %v", typWanted, typ)
	}
	return
}

func checkTyp3 ( rt reflect . Type , typ Typ3 , fopts FieldOptions ) ( err error ) { typWanted := typeToTyp3 ( rt , fopts ) if typ != typWanted { err = fmt . Errorf ( " " , typWanted , typ ) } return }


func decodeTyp3(bz []byte) (typ Typ3, n int, err error) {
	if len(bz) == 0 {
		err = fmt.Errorf("EOF while reading typ3 byte")
		return
	}
	if bz[0]&0xF8 != 0 {
		err = fmt.Errorf("invalid typ3 byte: %v", Typ3(bz[0]).String())
		return
	}
	typ = Typ3(bz[0])
	n = 1
	return
}

func decodeTyp3 ( bz [ ] byte ) ( typ Typ3 , n int , err error ) { if len ( bz ) == 0 { err = fmt . Errorf ( " " ) return } if bz [ 0 ] & 0xF8 != 0 { err = fmt . Errorf ( " " , Typ3 ( bz [ 0 ] ) . String ( ) ) return } typ = Typ3 ( bz [ 0 ] ) n = 1 return }


func NewPrefixBytes(prefixBytes []byte) PrefixBytes {
	pb := PrefixBytes{}
	copy(pb[:], prefixBytes)
	return pb
}

func NewPrefixBytes ( prefixBytes [ ] byte ) PrefixBytes { pb := PrefixBytes { } copy ( pb [ : ] , prefixBytes ) return pb }


func getLengthStr(info *TypeInfo) string {
	switch info.Type.Kind() {
	case reflect.Array,
		reflect.Int8,
		reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Float32, reflect.Float64,
		reflect.Complex64, reflect.Complex128:
		s := info.Type.Size()
		return fmt.Sprintf("0x%X", s)
	default:
		return "variable"
	}
}

func getLengthStr ( info * TypeInfo ) string { switch info . Type . Kind ( ) { case reflect . Array , reflect . Int8 , reflect . Int16 , reflect . Int32 , reflect . Int64 , reflect . Float32 , reflect . Float64 , reflect . Complex64 , reflect . Complex128 : s := info . Type . Size ( ) return fmt . Sprintf ( " " , s ) default : return " " } }

// A heuristic to guess the size of a registered type and return it as a string.
// If the size is not fixed it returns "variable".

A heuristic to guess the size of a registered type and return it as a string . If the size is not fixed it returns variable .


func (cdc *Codec) collectImplementers_nolock(info *TypeInfo) {
	for _, cinfo := range cdc.concreteInfos {
		if cinfo.PtrToType.Implements(info.Type) {
			info.Implementers[cinfo.Prefix] = append(
				info.Implementers[cinfo.Prefix], cinfo)
		}
	}
}

func ( cdc * Codec ) collectImplementers_nolock ( info * TypeInfo ) { for _ , cinfo := range cdc . concreteInfos { if cinfo . PtrToType . Implements ( info . Type ) { info . Implementers [ cinfo . Prefix ] = append ( info . Implementers [ cinfo . Prefix ] , cinfo ) } } }

// Find all conflicting prefixes for concrete types
// that "implement" the interface.  "Implement" in quotes because
// we only consider the pointer, for extra safety.

Find all conflicting prefixes for concrete types that implement the interface . Implement in quotes because we only consider the pointer for extra safety .


func (cdc *Codec) checkConflictsInPrio_nolock(iinfo *TypeInfo) error {

	for _, cinfos := range iinfo.Implementers {
		if len(cinfos) < 2 {
			continue
		}
		for _, cinfo := range cinfos {
			var inPrio = false
			for _, disfix := range iinfo.InterfaceInfo.Priority {
				if cinfo.GetDisfix() == disfix {
					inPrio = true
				}
			}
			if !inPrio {
				return fmt.Errorf("%v conflicts with %v other(s). Add it to the priority list for %v.",
					cinfo.Type, len(cinfos), iinfo.Type)
			}
		}
	}
	return nil
}

func ( cdc * Codec ) checkConflictsInPrio_nolock ( iinfo * TypeInfo ) error { for _ , cinfos := range iinfo . Implementers { if len ( cinfos ) < 2 { continue } for _ , cinfo := range cinfos { var inPrio = false for _ , disfix := range iinfo . InterfaceInfo . Priority { if cinfo . GetDisfix ( ) == disfix { inPrio = true } } if ! inPrio { return fmt . Errorf ( " " , cinfo . Type , len ( cinfos ) , iinfo . Type ) } } } return nil }

// Ensure that prefix-conflicting implementing concrete types
// are all registered in the priority list.
// Returns an error if a disamb conflict is found.

Ensure that prefix - conflicting implementing concrete types are all registered in the priority list . Returns an error if a disamb conflict is found .


func constructConcreteType(cinfo *TypeInfo) (crv, irvSet reflect.Value) {
	// Construct new concrete type.
	if cinfo.PointerPreferred {
		cPtrRv := reflect.New(cinfo.Type)
		crv = cPtrRv.Elem()
		irvSet = cPtrRv
	} else {
		crv = reflect.New(cinfo.Type).Elem()
		irvSet = crv
	}
	return
}

func
constructConcreteType
(
cinfo
*
TypeInfo
)
(
crv
,
irvSet
reflect
.
Value
)
{
// Construct new concrete type.
if
cinfo
.
PointerPreferred
{
cPtrRv
:=
reflect
.
New
(
cinfo
.
Type
)
crv
=
cPtrRv
.
Elem
(
)
irvSet
=
cPtrRv
}
else
{
crv
=
reflect
.
New
(
cinfo
.
Type
)
.
Elem
(
)
irvSet
=
crv
}
return
}

// constructConcreteType creates the concrete value as
// well as the corresponding settable value for it.
// Return irvSet which should be set on caller's interface rv.

constructConcreteType creates the concrete value as well as the corresponding settable value for it . Return irvSet which should be set on caller s interface rv .