func (s *Source) loadTarManifest() ([]ManifestItem, error) {
	// FIXME? Do we need to deal with the legacy format?
	bytes, err := s.readTarComponent(manifestFileName)
	if err != nil {
		return nil, err
	}
	var items []ManifestItem
	if err := json.Unmarshal(bytes, &items); err != nil {
		return nil, errors.Wrap(err, "Error decoding tar manifest.json")
	}
	return items, nil
}

// loadTarManifest loads and decodes the manifest.json.

loadTarManifest loads and decodes the manifest . json .


func (s *Source) Close() error {
	if s.removeTarPathOnClose {
		return os.Remove(s.tarPath)
	}
	return nil
}

func ( s * Source ) Close ( ) error { if s . removeTarPathOnClose { return os . Remove ( s . tarPath ) } return nil }

// Close removes resources associated with an initialized Source, if any.

Close removes resources associated with an initialized Source if any .


func newImageDestination(ctx context.Context, sys *types.SystemContext, ref daemonReference) (types.ImageDestination, error) {
	if ref.ref == nil {
		return nil, errors.Errorf("Invalid destination docker-daemon:%s: a destination must be a name:tag", ref.StringWithinTransport())
	}
	namedTaggedRef, ok := ref.ref.(reference.NamedTagged)
	if !ok {
		return nil, errors.Errorf("Invalid destination docker-daemon:%s: a destination must be a name:tag", ref.StringWithinTransport())
	}

	var mustMatchRuntimeOS = true
	if sys != nil && sys.DockerDaemonHost != client.DefaultDockerHost {
		mustMatchRuntimeOS = false
	}

	c, err := newDockerClient(sys)
	if err != nil {
		return nil, errors.Wrap(err, "Error initializing docker engine client")
	}

	reader, writer := io.Pipe()
	// Commit() may never be called, so we may never read from this channel; so, make this buffered to allow imageLoadGoroutine to write status and terminate even if we never read it.
	statusChannel := make(chan error, 1)

	goroutineContext, goroutineCancel := context.WithCancel(ctx)
	go imageLoadGoroutine(goroutineContext, c, reader, statusChannel)

	return &daemonImageDestination{
		ref:                ref,
		mustMatchRuntimeOS: mustMatchRuntimeOS,
		Destination:        tarfile.NewDestination(writer, namedTaggedRef),
		goroutineCancel:    goroutineCancel,
		statusChannel:      statusChannel,
		writer:             writer,
		committed:          false,
	}, nil
}

// newImageDestination returns a types.ImageDestination for the specified image reference.

newImageDestination returns a types . ImageDestination for the specified image reference .


func imageLoadGoroutine(ctx context.Context, c *client.Client, reader *io.PipeReader, statusChannel chan<- error) {
	err := errors.New("Internal error: unexpected panic in imageLoadGoroutine")
	defer func() {
		logrus.Debugf("docker-daemon: sending done, status %v", err)
		statusChannel <- err
	}()
	defer func() {
		if err == nil {
			reader.Close()
		} else {
			reader.CloseWithError(err)
		}
	}()

	resp, err := c.ImageLoad(ctx, reader, true)
	if err != nil {
		err = errors.Wrap(err, "Error saving image to docker engine")
		return
	}
	defer resp.Body.Close()
}

func imageLoadGoroutine ( ctx context . Context , c * client . Client , reader * io . PipeReader , statusChannel chan <- error ) { err := errors . New ( " " ) defer func ( ) { logrus . Debugf ( " " , err ) statusChannel <- err } ( ) defer func ( ) { if err == nil { reader . Close ( ) } else { reader . CloseWithError ( err ) } } ( ) resp , err := c . ImageLoad ( ctx , reader , true ) if err != nil { err = errors . Wrap ( err , " " ) return } defer resp . Body . Close ( ) }

// imageLoadGoroutine accepts tar stream on reader, sends it to c, and reports error or success by writing to statusChannel

imageLoadGoroutine accepts tar stream on reader sends it to c and reports error or success by writing to statusChannel


func NewReference(file, image string) (types.ImageReference, error) {
	resolved, err := explicitfilepath.ResolvePathToFullyExplicit(file)
	if err != nil {
		return nil, err
	}

	if err := internal.ValidateOCIPath(file); err != nil {
		return nil, err
	}

	if err := internal.ValidateImageName(image); err != nil {
		return nil, err
	}

	return ociArchiveReference{file: file, resolvedFile: resolved, image: image}, nil
}

func NewReference ( file , image string ) ( types . ImageReference , error ) { resolved , err := explicitfilepath . ResolvePathToFullyExplicit ( file ) if err != nil { return nil , err } if err := internal . ValidateOCIPath ( file ) ; err != nil { return nil , err } if err := internal . ValidateImageName ( image ) ; err != nil { return nil , err } return ociArchiveReference { file : file , resolvedFile : resolved , image : image } , nil }

// NewReference returns an OCI reference for a file and a image.

NewReference returns an OCI reference for a file and a image .


func createOCIRef(image string) (tempDirOCIRef, error) {
	dir, err := ioutil.TempDir(tmpdir.TemporaryDirectoryForBigFiles(), "oci")
	if err != nil {
		return tempDirOCIRef{}, errors.Wrapf(err, "error creating temp directory")
	}
	ociRef, err := ocilayout.NewReference(dir, image)
	if err != nil {
		return tempDirOCIRef{}, err
	}

	tempDirRef := tempDirOCIRef{tempDirectory: dir, ociRefExtracted: ociRef}
	return tempDirRef, nil
}

func createOCIRef ( image string ) ( tempDirOCIRef , error ) { dir , err := ioutil . TempDir ( tmpdir . TemporaryDirectoryForBigFiles ( ) , " " ) if err != nil { return tempDirOCIRef { } , errors . Wrapf ( err , " " ) } ociRef , err := ocilayout . NewReference ( dir , image ) if err != nil { return tempDirOCIRef { } , err } tempDirRef := tempDirOCIRef { tempDirectory : dir , ociRefExtracted : ociRef } return tempDirRef , nil }

// createOCIRef creates the oci reference of the image


func createUntarTempDir(ref ociArchiveReference) (tempDirOCIRef, error) {
	tempDirRef, err := createOCIRef(ref.image)
	if err != nil {
		return tempDirOCIRef{}, errors.Wrap(err, "error creating oci reference")
	}
	src := ref.resolvedFile
	dst := tempDirRef.tempDirectory
	// TODO: This can take quite some time, and should ideally be cancellable using a context.Context.
	if err := archive.UntarPath(src, dst); err != nil {
		if err := tempDirRef.deleteTempDir(); err != nil {
			return tempDirOCIRef{}, errors.Wrapf(err, "error deleting temp directory %q", tempDirRef.tempDirectory)
		}
		return tempDirOCIRef{}, errors.Wrapf(err, "error untarring file %q", tempDirRef.tempDirectory)
	}
	return tempDirRef, nil
}

// creates the temporary directory and copies the tarred content to it


func destructivelyPrioritizeReplacementCandidatesWithMax(cs []CandidateWithTime, primaryDigest, uncompressedDigest digest.Digest, maxCandidates int) []types.BICReplacementCandidate {
	// We don't need to use sort.Stable() because nanosecond timestamps are (presumably?) unique, so no two elements should
	// compare equal.
	sort.Sort(&candidateSortState{
		cs:                 cs,
		primaryDigest:      primaryDigest,
		uncompressedDigest: uncompressedDigest,
	})

	resLength := len(cs)
	if resLength > maxCandidates {
		resLength = maxCandidates
	}
	res := make([]types.BICReplacementCandidate, resLength)
	for i := range res {
		res[i] = cs[i].Candidate
	}
	return res
}

// destructivelyPrioritizeReplacementCandidatesWithMax is destructivelyPrioritizeReplacementCandidates with a parameter for the
// number of entries to limit, only to make testing simpler.


func newImageDestination(ref ostreeReference, tmpDirPath string) (types.ImageDestination, error) {
	tmpDirPath = filepath.Join(tmpDirPath, ref.branchName)
	if err := ensureDirectoryExists(tmpDirPath); err != nil {
		return nil, err
	}
	return &ostreeImageDestination{ref, "", manifestSchema{}, tmpDirPath, map[string]*blobToImport{}, "", 0, nil}, nil
}

func newImageDestination ( ref ostreeReference , tmpDirPath string ) ( types . ImageDestination , error ) { tmpDirPath = filepath . Join ( tmpDirPath , ref . branchName ) if err := ensureDirectoryExists ( tmpDirPath ) ; err != nil { return nil , err } return & ostreeImageDestination { ref , " " , manifestSchema { } , tmpDirPath , map [ string ] * blobToImport { } , " " , 0 , nil } , nil }

// newImageDestination returns an ImageDestination for writing to an existing ostree.

newImageDestination returns an ImageDestination for writing to an existing ostree .


func resolveExistingPathToFullyExplicit(path string) (string, error) {
	resolved, err := filepath.Abs(path)
	if err != nil {
		return "", err // Coverage: This can fail only if os.Getwd() fails.
	}
	resolved, err = filepath.EvalSymlinks(resolved)
	if err != nil {
		return "", err
	}
	return filepath.Clean(resolved), nil
}

// resolveExistingPathToFullyExplicit is the same as ResolvePathToFullyExplicit,
// but without the special case for missing final component.

resolveExistingPathToFullyExplicit is the same as ResolvePathToFullyExplicit but without the special case for missing final component .


func newImageDestination(ref dirReference, compress bool) (types.ImageDestination, error) {
	d := &dirImageDestination{ref: ref, compress: compress}

	// If directory exists check if it is empty
	// if not empty, check whether the contents match that of a container image directory and overwrite the contents
	// if the contents don't match throw an error
	dirExists, err := pathExists(d.ref.resolvedPath)
	if err != nil {
		return nil, errors.Wrapf(err, "error checking for path %q", d.ref.resolvedPath)
	}
	if dirExists {
		isEmpty, err := isDirEmpty(d.ref.resolvedPath)
		if err != nil {
			return nil, err
		}

		if !isEmpty {
			versionExists, err := pathExists(d.ref.versionPath())
			if err != nil {
				return nil, errors.Wrapf(err, "error checking if path exists %q", d.ref.versionPath())
			}
			if versionExists {
				contents, err := ioutil.ReadFile(d.ref.versionPath())
				if err != nil {
					return nil, err
				}
				// check if contents of version file is what we expect it to be
				if string(contents) != version {
					return nil, ErrNotContainerImageDir
				}
			} else {
				return nil, ErrNotContainerImageDir
			}
			// delete directory contents so that only one image is in the directory at a time
			if err = removeDirContents(d.ref.resolvedPath); err != nil {
				return nil, errors.Wrapf(err, "error erasing contents in %q", d.ref.resolvedPath)
			}
			logrus.Debugf("overwriting existing container image directory %q", d.ref.resolvedPath)
		}
	} else {
		// create directory if it doesn't exist
		if err := os.MkdirAll(d.ref.resolvedPath, 0755); err != nil {
			return nil, errors.Wrapf(err, "unable to create directory %q", d.ref.resolvedPath)
		}
	}
	// create version file
	err = ioutil.WriteFile(d.ref.versionPath(), []byte(version), 0644)
	if err != nil {
		return nil, errors.Wrapf(err, "error creating version file %q", d.ref.versionPath())
	}
	return d, nil
}

// newImageDestination returns an ImageDestination for writing to a directory.

newImageDestination returns an ImageDestination for writing to a directory .


func isDirEmpty(path string) (bool, error) {
	files, err := ioutil.ReadDir(path)
	if err != nil {
		return false, err
	}
	return len(files) == 0, nil
}

func isDirEmpty ( path string ) ( bool , error ) { files , err := ioutil . ReadDir ( path ) if err != nil { return false , err } return len ( files ) == 0 , nil }


func removeDirContents(path string) error {
	files, err := ioutil.ReadDir(path)
	if err != nil {
		return err
	}

	for _, file := range files {
		if err := os.RemoveAll(filepath.Join(path, file.Name())); err != nil {
			return err
		}
	}
	return nil
}

func removeDirContents ( path string ) error { files , err := ioutil . ReadDir ( path ) if err != nil { return err } for _ , file := range files { if err := os . RemoveAll ( filepath . Join ( path , file . Name ( ) ) ) ; err != nil { return err } } return nil }


func GetRepositoryTags(ctx context.Context, sys *types.SystemContext, ref types.ImageReference) ([]string, error) {
	dr, ok := ref.(dockerReference)
	if !ok {
		return nil, errors.Errorf("ref must be a dockerReference")
	}

	path := fmt.Sprintf(tagsPath, reference.Path(dr.ref))
	client, err := newDockerClientFromRef(sys, dr, false, "pull")
	if err != nil {
		return nil, errors.Wrap(err, "failed to create client")
	}

	tags := make([]string, 0)

	for {
		res, err := client.makeRequest(ctx, "GET", path, nil, nil, v2Auth, nil)
		if err != nil {
			return nil, err
		}
		defer res.Body.Close()
		if res.StatusCode != http.StatusOK {
			// print url also
			return nil, errors.Errorf("Invalid status code returned when fetching tags list %d (%s)", res.StatusCode, http.StatusText(res.StatusCode))
		}

		var tagsHolder struct {
			Tags []string
		}
		if err = json.NewDecoder(res.Body).Decode(&tagsHolder); err != nil {
			return nil, err
		}
		tags = append(tags, tagsHolder.Tags...)

		link := res.Header.Get("Link")
		if link == "" {
			break
		}

		linkURLStr := strings.Trim(strings.Split(link, ";")[0], "<>")
		linkURL, err := url.Parse(linkURLStr)
		if err != nil {
			return tags, err
		}

		// can be relative or absolute, but we only want the path (and I
		// guess we're in trouble if it forwards to a new place...)
		path = linkURL.Path
		if linkURL.RawQuery != "" {
			path += "?"
			path += linkURL.RawQuery
		}
	}
	return tags, nil
}

// GetRepositoryTags list all tags available in the repository. The tag
// provided inside the ImageReference will be ignored.

GetRepositoryTags list all tags available in the repository . The tag provided inside the ImageReference will be ignored .


func DefaultCache(sys *types.SystemContext) types.BlobInfoCache {
	dir, err := blobInfoCacheDir(sys, getRootlessUID())
	if err != nil {
		logrus.Debugf("Error determining a location for %s, using a memory-only cache", blobInfoCacheFilename)
		return memory.New()
	}
	path := filepath.Join(dir, blobInfoCacheFilename)
	if err := os.MkdirAll(dir, 0700); err != nil {
		logrus.Debugf("Error creating parent directories for %s, using a memory-only cache: %v", blobInfoCacheFilename, err)
		return memory.New()
	}

	logrus.Debugf("Using blob info cache at %s", path)
	return boltdb.New(path)
}

func DefaultCache ( sys * types . SystemContext ) types . BlobInfoCache { dir , err := blobInfoCacheDir ( sys , getRootlessUID ( ) ) if err != nil { logrus . Debugf ( " " , blobInfoCacheFilename ) return memory . New ( ) } path := filepath . Join ( dir , blobInfoCacheFilename ) if err := os . MkdirAll ( dir , 0700 ) ; err != nil { logrus . Debugf ( " " , blobInfoCacheFilename , err ) return memory . New ( ) } logrus . Debugf ( " " , path ) return boltdb . New ( path ) }

// DefaultCache returns the default BlobInfoCache implementation appropriate for sys.

DefaultCache returns the default BlobInfoCache implementation appropriate for sys .


func (mem *cache) uncompressedDigestLocked(anyDigest digest.Digest) digest.Digest {
	if d, ok := mem.uncompressedDigests[anyDigest]; ok {
		return d
	}
	// Presence in digestsByUncompressed implies that anyDigest must already refer to an uncompressed digest.
	// This way we don't have to waste storage space with trivial (uncompressed, uncompressed) mappings
	// when we already record a (compressed, uncompressed) pair.
	if m, ok := mem.digestsByUncompressed[anyDigest]; ok && len(m) > 0 {
		return anyDigest
	}
	return ""
}

// uncompressedDigestLocked implements types.BlobInfoCache.UncompressedDigest, but must be called only with mem.mutex held.

uncompressedDigestLocked implements types . BlobInfoCache . UncompressedDigest but must be called only with mem . mutex held .


func (d *ociArchiveImageDestination) Close() error {
	defer d.tempDirRef.deleteTempDir()
	return d.unpackedDest.Close()
}

func ( d * ociArchiveImageDestination ) Close ( ) error { defer d . tempDirRef . deleteTempDir ( ) return d . unpackedDest . Close ( ) }

// Close removes resources associated with an initialized ImageDestination, if any
// Close deletes the temp directory of the oci-archive image

Close removes resources associated with an initialized ImageDestination if any Close deletes the temp directory of the oci - archive image


func (d *ociArchiveImageDestination) PutManifest(ctx context.Context, m []byte) error {
	return d.unpackedDest.PutManifest(ctx, m)
}

func ( d * ociArchiveImageDestination ) PutManifest ( ctx context . Context , m [ ] byte ) error { return d . unpackedDest . PutManifest ( ctx , m ) }

// PutManifest writes manifest to the destination


func (d *ociArchiveImageDestination) Commit(ctx context.Context) error {
	if err := d.unpackedDest.Commit(ctx); err != nil {
		return errors.Wrapf(err, "error storing image %q", d.ref.image)
	}

	// path of directory to tar up
	src := d.tempDirRef.tempDirectory
	// path to save tarred up file
	dst := d.ref.resolvedFile
	return tarDirectory(src, dst)
}

func
(
d
*
ociArchiveImageDestination
)
Commit
(
ctx
context
.
Context
)
error
{
if
err
:=
d
.
unpackedDest
.
Commit
(
ctx
)
;
err
!=
{
return
errors
.
Wrapf
(
err
,
"
"
,
d
.
ref
.
image
)
}
// path of directory to tar up
src
:=
d
.
tempDirRef
.
tempDirectory
// path to save tarred up file
dst
:=
d
.
ref
.
resolvedFile
return
tarDirectory
(
src
,
dst
)
}

// Commit marks the process of storing the image as successful and asks for the image to be persisted
// after the directory is made, it is tarred up into a file and the directory is deleted

Commit marks the process of storing the image as successful and asks for the image to be persisted after the directory is made it is tarred up into a file and the directory is deleted


func tarDirectory(src, dst string) error {
	// input is a stream of bytes from the archive of the directory at path
	input, err := archive.Tar(src, archive.Uncompressed)
	if err != nil {
		return errors.Wrapf(err, "error retrieving stream of bytes from %q", src)
	}

	// creates the tar file
	outFile, err := os.Create(dst)
	if err != nil {
		return errors.Wrapf(err, "error creating tar file %q", dst)
	}
	defer outFile.Close()

	// copies the contents of the directory to the tar file
	// TODO: This can take quite some time, and should ideally be cancellable using a context.Context.
	_, err = io.Copy(outFile, input)

	return err
}

// tar converts the directory at src and saves it to dst


func (s storageTransport) ParseStoreReference(store storage.Store, ref string) (*storageReference, error) {
	if ref == "" {
		return nil, errors.Wrapf(ErrInvalidReference, "%q is an empty reference", ref)
	}
	if ref[0] == '[' {
		// Ignore the store specifier.
		closeIndex := strings.IndexRune(ref, ']')
		if closeIndex < 1 {
			return nil, errors.Wrapf(ErrInvalidReference, "store specifier in %q did not end", ref)
		}
		ref = ref[closeIndex+1:]
	}

	// The reference may end with an image ID.  Image IDs and digests use the same "@" separator;
	// here we only peel away an image ID, and leave digests alone.
	split := strings.LastIndex(ref, "@")
	id := ""
	if split != -1 {
		possibleID := ref[split+1:]
		if possibleID == "" {
			return nil, errors.Wrapf(ErrInvalidReference, "empty trailing digest or ID in %q", ref)
		}
		// If it looks like a digest, leave it alone for now.
		if _, err := digest.Parse(possibleID); err != nil {
			// Otherwise…
			if idSum, err := digest.Parse("sha256:" + possibleID); err == nil && idSum.Validate() == nil {
				id = possibleID // … it is a full ID
			} else if img, err := store.Image(possibleID); err == nil && img != nil && len(possibleID) >= minimumTruncatedIDLength && strings.HasPrefix(img.ID, possibleID) {
				// … it is a truncated version of the ID of an image that's present in local storage,
				// so we might as well use the expanded value.
				id = img.ID
			} else {
				return nil, errors.Wrapf(ErrInvalidReference, "%q does not look like an image ID or digest", possibleID)
			}
			// We have recognized an image ID; peel it off.
			ref = ref[:split]
		}
	}

	// If we only have one @-delimited portion, then _maybe_ it's a truncated image ID.  Only check on that if it's
	// at least of what we guess is a reasonable minimum length, because we don't want a really short value
	// like "a" matching an image by ID prefix when the input was actually meant to specify an image name.
	if id == "" && len(ref) >= minimumTruncatedIDLength && !strings.ContainsAny(ref, "@:") {
		if img, err := store.Image(ref); err == nil && img != nil && strings.HasPrefix(img.ID, ref) {
			// It's a truncated version of the ID of an image that's present in local storage;
			// we need to expand it.
			id = img.ID
			ref = ""
		}
	}

	var named reference.Named
	// Unless we have an un-named "ID" or "@ID" reference (where ID might only have been a prefix), which has been
	// completely parsed above, the initial portion should be a name, possibly with a tag and/or a digest..
	if ref != "" {
		var err error
		named, err = reference.ParseNormalizedNamed(ref)
		if err != nil {
			return nil, errors.Wrapf(err, "error parsing named reference %q", ref)
		}
		named = reference.TagNameOnly(named)
	}

	result, err := newReference(storageTransport{store: store, defaultUIDMap: s.defaultUIDMap, defaultGIDMap: s.defaultGIDMap}, named, id)
	if err != nil {
		return nil, err
	}
	logrus.Debugf("parsed reference into %q", result.StringWithinTransport())
	return result, nil
}

// ParseStoreReference takes a name or an ID, tries to figure out which it is
// relative to the given store, and returns it in a reference object.

ParseStoreReference takes a name or an ID tries to figure out which it is relative to the given store and returns it in a reference object .


func chooseDigestFromManifestList(sys *types.SystemContext, blob []byte) (digest.Digest, error) {
	wantedArch := runtime.GOARCH
	if sys != nil && sys.ArchitectureChoice != "" {
		wantedArch = sys.ArchitectureChoice
	}
	wantedOS := runtime.GOOS
	if sys != nil && sys.OSChoice != "" {
		wantedOS = sys.OSChoice
	}

	list := manifestList{}
	if err := json.Unmarshal(blob, &list); err != nil {
		return "", err
	}
	for _, d := range list.Manifests {
		if d.Platform.Architecture == wantedArch && d.Platform.OS == wantedOS {
			return d.Digest, nil
		}
	}
	return "", fmt.Errorf("no image found in manifest list for architecture %s, OS %s", wantedArch, wantedOS)
}

func chooseDigestFromManifestList ( sys * types . SystemContext , blob [ ] byte ) ( digest . Digest , error ) { wantedArch := runtime . GOARCH if sys != nil && sys . ArchitectureChoice != " " { wantedArch = sys . ArchitectureChoice } wantedOS := runtime . GOOS if sys != nil && sys . OSChoice != " " { wantedOS = sys . OSChoice } list := manifestList { } if err := json . Unmarshal ( blob , & list ) ; err != nil { return " " , err } for _ , d := range list . Manifests { if d . Platform . Architecture == wantedArch && d . Platform . OS == wantedOS { return d . Digest , nil } } return " " , fmt . Errorf ( " " , wantedArch , wantedOS ) }

// chooseDigestFromManifestList parses blob as a schema2 manifest list,
// and returns the digest of the image appropriate for the current environment.

chooseDigestFromManifestList parses blob as a schema2 manifest list and returns the digest of the image appropriate for the current environment .


func ChooseManifestInstanceFromManifestList(ctx context.Context, sys *types.SystemContext, src types.UnparsedImage) (digest.Digest, error) {
	// For now this only handles manifest.DockerV2ListMediaType; we can generalize it later,
	// probably along with manifest list editing.
	blob, mt, err := src.Manifest(ctx)
	if err != nil {
		return "", err
	}
	if mt != manifest.DockerV2ListMediaType {
		return "", fmt.Errorf("Internal error: Trying to select an image from a non-manifest-list manifest type %s", mt)
	}
	return chooseDigestFromManifestList(sys, blob)
}

// ChooseManifestInstanceFromManifestList returns a digest of a manifest appropriate
// for the current system from the manifest available from src.

ChooseManifestInstanceFromManifestList returns a digest of a manifest appropriate for the current system from the manifest available from src .


func manifestSchema1FromComponents(ref reference.Named, fsLayers []manifest.Schema1FSLayers, history []manifest.Schema1History, architecture string) (genericManifest, error) {
	m, err := manifest.Schema1FromComponents(ref, fsLayers, history, architecture)
	if err != nil {
		return nil, err
	}
	return &manifestSchema1{m: m}, nil
}

func manifestSchema1FromComponents ( ref reference . Named , fsLayers [ ] manifest . Schema1FSLayers , history [ ] manifest . Schema1History , architecture string ) ( genericManifest , error ) { m , err := manifest . Schema1FromComponents ( ref , fsLayers , history , architecture ) if err != nil { return nil , err } return & manifestSchema1 { m : m } , nil }

// manifestSchema1FromComponents builds a new manifestSchema1 from the supplied data.

manifestSchema1FromComponents builds a new manifestSchema1 from the supplied data .


func (s *dockerImageSource) manifestDigest(ctx context.Context, instanceDigest *digest.Digest) (digest.Digest, error) {
	if instanceDigest != nil {
		return *instanceDigest, nil
	}
	if digested, ok := s.ref.ref.(reference.Digested); ok {
		d := digested.Digest()
		if d.Algorithm() == digest.Canonical {
			return d, nil
		}
	}
	if err := s.ensureManifestIsLoaded(ctx); err != nil {
		return "", err
	}
	return manifest.Digest(s.cachedManifest)
}

func ( s * dockerImageSource ) manifestDigest ( ctx context . Context , instanceDigest * digest . Digest ) ( digest . Digest , error ) { if instanceDigest != nil { return * instanceDigest , nil } if digested , ok := s . ref . ref . ( reference . Digested ) ; ok { d := digested . Digest ( ) if d . Algorithm ( ) == digest . Canonical { return d , nil } } if err := s . ensureManifestIsLoaded ( ctx ) ; err != nil { return " " , err } return manifest . Digest ( s . cachedManifest ) }

// manifestDigest returns a digest of the manifest, from instanceDigest if non-nil; or from the supplied reference,
// or finally, from a fetched manifest.

manifestDigest returns a digest of the manifest from instanceDigest if non - nil ; or from the supplied reference or finally from a fetched manifest .


func deleteImage(ctx context.Context, sys *types.SystemContext, ref dockerReference) error {
	// docker/distribution does not document what action should be used for deleting images.
	//
	// Current docker/distribution requires "pull" for reading the manifest and "delete" for deleting it.
	// quay.io requires "push" (an explicit "pull" is unnecessary), does not grant any token (fails parsing the request) if "delete" is included.
	// OpenShift ignores the action string (both the password and the token is an OpenShift API token identifying a user).
	//
	// We have to hard-code a single string, luckily both docker/distribution and quay.io support "*" to mean "everything".
	c, err := newDockerClientFromRef(sys, ref, true, "*")
	if err != nil {
		return err
	}

	// When retrieving the digest from a registry >= 2.3 use the following header:
	//   "Accept": "application/vnd.docker.distribution.manifest.v2+json"
	headers := make(map[string][]string)
	headers["Accept"] = []string{manifest.DockerV2Schema2MediaType}

	refTail, err := ref.tagOrDigest()
	if err != nil {
		return err
	}
	getPath := fmt.Sprintf(manifestPath, reference.Path(ref.ref), refTail)
	get, err := c.makeRequest(ctx, "GET", getPath, headers, nil, v2Auth, nil)
	if err != nil {
		return err
	}
	defer get.Body.Close()
	manifestBody, err := ioutil.ReadAll(get.Body)
	if err != nil {
		return err
	}
	switch get.StatusCode {
	case http.StatusOK:
	case http.StatusNotFound:
		return errors.Errorf("Unable to delete %v. Image may not exist or is not stored with a v2 Schema in a v2 registry", ref.ref)
	default:
		return errors.Errorf("Failed to delete %v: %s (%v)", ref.ref, manifestBody, get.Status)
	}

	digest := get.Header.Get("Docker-Content-Digest")
	deletePath := fmt.Sprintf(manifestPath, reference.Path(ref.ref), digest)

	// When retrieving the digest from a registry >= 2.3 use the following header:
	//   "Accept": "application/vnd.docker.distribution.manifest.v2+json"
	delete, err := c.makeRequest(ctx, "DELETE", deletePath, headers, nil, v2Auth, nil)
	if err != nil {
		return err
	}
	defer delete.Body.Close()

	body, err := ioutil.ReadAll(delete.Body)
	if err != nil {
		return err
	}
	if delete.StatusCode != http.StatusAccepted {
		return errors.Errorf("Failed to delete %v: %s (%v)", deletePath, string(body), delete.Status)
	}

	if c.signatureBase != nil {
		manifestDigest, err := manifest.Digest(manifestBody)
		if err != nil {
			return err
		}

		for i := 0; ; i++ {
			url := signatureStorageURL(c.signatureBase, manifestDigest, i)
			if url == nil {
				return errors.Errorf("Internal error: signatureStorageURL with non-nil base returned nil")
			}
			missing, err := c.deleteOneSignature(url)
			if err != nil {
				return err
			}
			if missing {
				break
			}
		}
	}

	return nil
}

// deleteImage deletes the named image from the registry, if supported.

deleteImage deletes the named image from the registry if supported .


func Schema1FromComponents(ref reference.Named, fsLayers []Schema1FSLayers, history []Schema1History, architecture string) (*Schema1, error) {
	var name, tag string
	if ref != nil { // Well, what to do if it _is_ nil? Most consumers actually don't use these fields nowadays, so we might as well try not supplying them.
		name = reference.Path(ref)
		if tagged, ok := ref.(reference.NamedTagged); ok {
			tag = tagged.Tag()
		}
	}
	s1 := Schema1{
		Name:          name,
		Tag:           tag,
		Architecture:  architecture,
		FSLayers:      fsLayers,
		History:       history,
		SchemaVersion: 1,
	}
	if err := s1.initialize(); err != nil {
		return nil, err
	}
	return &s1, nil
}

// Schema1FromComponents creates an Schema1 manifest instance from the supplied data.

Schema1FromComponents creates an Schema1 manifest instance from the supplied data .


func (m *Schema1) initialize() error {
	if len(m.FSLayers) != len(m.History) {
		return errors.New("length of history not equal to number of layers")
	}
	if len(m.FSLayers) == 0 {
		return errors.New("no FSLayers in manifest")
	}
	m.ExtractedV1Compatibility = make([]Schema1V1Compatibility, len(m.History))
	for i, h := range m.History {
		if err := json.Unmarshal([]byte(h.V1Compatibility), &m.ExtractedV1Compatibility[i]); err != nil {
			return errors.Wrapf(err, "Error parsing v2s1 history entry %d", i)
		}
	}
	return nil
}

func ( m * Schema1 ) initialize ( ) error { if len ( m . FSLayers ) != len ( m . History ) { return errors . New ( " " ) } if len ( m . FSLayers ) == 0 { return errors . New ( " " ) } m . ExtractedV1Compatibility = make ( [ ] Schema1V1Compatibility , len ( m . History ) ) for i , h := range m . History { if err := json . Unmarshal ( [ ] byte ( h . V1Compatibility ) , & m . ExtractedV1Compatibility [ i ] ) ; err != nil { return errors . Wrapf ( err , " " , i ) } } return nil }

// initialize initializes ExtractedV1Compatibility and verifies invariants, so that the rest of this code can assume a minimally healthy manifest.

initialize initializes ExtractedV1Compatibility and verifies invariants so that the rest of this code can assume a minimally healthy manifest .


func (m *Schema1) ToSchema2Config(diffIDs []digest.Digest) ([]byte, error) {
	// Convert the schema 1 compat info into a schema 2 config, constructing some of the fields
	// that aren't directly comparable using info from the manifest.
	if len(m.History) == 0 {
		return nil, errors.New("image has no layers")
	}
	s1 := Schema2V1Image{}
	config := []byte(m.History[0].V1Compatibility)
	err := json.Unmarshal(config, &s1)
	if err != nil {
		return nil, errors.Wrapf(err, "error decoding configuration")
	}
	// Images created with versions prior to 1.8.3 require us to re-encode the encoded object,
	// adding some fields that aren't "omitempty".
	if s1.DockerVersion != "" && versions.LessThan(s1.DockerVersion, "1.8.3") {
		config, err = json.Marshal(&s1)
		if err != nil {
			return nil, errors.Wrapf(err, "error re-encoding compat image config %#v", s1)
		}
	}
	// Build the history.
	convertedHistory := []Schema2History{}
	for _, compat := range m.ExtractedV1Compatibility {
		hitem := Schema2History{
			Created:    compat.Created,
			CreatedBy:  strings.Join(compat.ContainerConfig.Cmd, " "),
			Author:     compat.Author,
			Comment:    compat.Comment,
			EmptyLayer: compat.ThrowAway,
		}
		convertedHistory = append([]Schema2History{hitem}, convertedHistory...)
	}
	// Build the rootfs information.  We need the decompressed sums that we've been
	// calculating to fill in the DiffIDs.  It's expected (but not enforced by us)
	// that the number of diffIDs corresponds to the number of non-EmptyLayer
	// entries in the history.
	rootFS := &Schema2RootFS{
		Type:    "layers",
		DiffIDs: diffIDs,
	}
	// And now for some raw manipulation.
	raw := make(map[string]*json.RawMessage)
	err = json.Unmarshal(config, &raw)
	if err != nil {
		return nil, errors.Wrapf(err, "error re-decoding compat image config %#v", s1)
	}
	// Drop some fields.
	delete(raw, "id")
	delete(raw, "parent")
	delete(raw, "parent_id")
	delete(raw, "layer_id")
	delete(raw, "throwaway")
	delete(raw, "Size")
	// Add the history and rootfs information.
	rootfs, err := json.Marshal(rootFS)
	if err != nil {
		return nil, errors.Errorf("error encoding rootfs information %#v: %v", rootFS, err)
	}
	rawRootfs := json.RawMessage(rootfs)
	raw["rootfs"] = &rawRootfs
	history, err := json.Marshal(convertedHistory)
	if err != nil {
		return nil, errors.Errorf("error encoding history information %#v: %v", convertedHistory, err)
	}
	rawHistory := json.RawMessage(history)
	raw["history"] = &rawHistory
	// Encode the result.
	config, err = json.Marshal(raw)
	if err != nil {
		return nil, errors.Errorf("error re-encoding compat image config %#v: %v", s1, err)
	}
	return config, nil
}

// ToSchema2Config builds a schema2-style configuration blob using the supplied diffIDs.

ToSchema2Config builds a schema2 - style configuration blob using the supplied diffIDs .


func Digest(manifest []byte) (digest.Digest, error) {
	if GuessMIMEType(manifest) == DockerV2Schema1SignedMediaType {
		sig, err := libtrust.ParsePrettySignature(manifest, "signatures")
		if err != nil {
			return "", err
		}
		manifest, err = sig.Payload()
		if err != nil {
			// Coverage: This should never happen, libtrust's Payload() can fail only if joseBase64UrlDecode() fails, on a string
			// that libtrust itself has josebase64UrlEncode()d
			return "", err
		}
	}

	return digest.FromBytes(manifest), nil
}

// Digest returns the a digest of a docker manifest, with any necessary implied transformations like stripping v1s1 signatures.

Digest returns the a digest of a docker manifest with any necessary implied transformations like stripping v1s1 signatures .


func MatchesDigest(manifest []byte, expectedDigest digest.Digest) (bool, error) {
	// This should eventually support various digest types.
	actualDigest, err := Digest(manifest)
	if err != nil {
		return false, err
	}
	return expectedDigest == actualDigest, nil
}

// MatchesDigest returns true iff the manifest matches expectedDigest.
// Error may be set if this returns false.
// Note that this is not doing ConstantTimeCompare; by the time we get here, the cryptographic signature must already have been verified,
// or we are not using a cryptographic channel and the attacker can modify the digest along with the manifest blob.

MatchesDigest returns true iff the manifest matches expectedDigest . Error may be set if this returns false . Note that this is not doing ConstantTimeCompare ; by the time we get here the cryptographic signature must already have been verified or we are not using a cryptographic channel and the attacker can modify the digest along with the manifest blob .


func NormalizedMIMEType(input string) string {
	switch input {
	// "application/json" is a valid v2s1 value per https://github.com/docker/distribution/blob/master/docs/spec/manifest-v2-1.md .
	// This works for now, when nothing else seems to return "application/json"; if that were not true, the mapping/detection might
	// need to happen within the ImageSource.
	case "application/json":
		return DockerV2Schema1SignedMediaType
	case DockerV2Schema1MediaType, DockerV2Schema1SignedMediaType,
		imgspecv1.MediaTypeImageManifest,
		DockerV2Schema2MediaType,
		DockerV2ListMediaType:
		return input
	default:
		// If it's not a recognized manifest media type, or we have failed determining the type, we'll try one last time
		// to deserialize using v2s1 as per https://github.com/docker/distribution/blob/master/manifests.go#L108
		// and https://github.com/docker/distribution/blob/master/manifest/schema1/manifest.go#L50
		//
		// Crane registries can also return "text/plain", or pretty much anything else depending on a file extension “recognized” in the tag.
		// This makes no real sense, but it happens
		// because requests for manifests are
		// redirected to a content distribution
		// network which is configured that way. See https://bugzilla.redhat.com/show_bug.cgi?id=1389442
		return DockerV2Schema1SignedMediaType
	}
}

// NormalizedMIMEType returns the effective MIME type of a manifest MIME type returned by a server,
// centralizing various workarounds.

NormalizedMIMEType returns the effective MIME type of a manifest MIME type returned by a server centralizing various workarounds .


func FromBlob(manblob []byte, mt string) (Manifest, error) {
	switch NormalizedMIMEType(mt) {
	case DockerV2Schema1MediaType, DockerV2Schema1SignedMediaType:
		return Schema1FromManifest(manblob)
	case imgspecv1.MediaTypeImageManifest:
		return OCI1FromManifest(manblob)
	case DockerV2Schema2MediaType:
		return Schema2FromManifest(manblob)
	case DockerV2ListMediaType:
		return nil, fmt.Errorf("Treating manifest lists as individual manifests is not implemented")
	default: // Note that this may not be reachable, NormalizedMIMEType has a default for unknown values.
		return nil, fmt.Errorf("Unimplemented manifest MIME type %s", mt)
	}
}

// FromBlob returns a Manifest instance for the specified manifest blob and the corresponding MIME type


func NewReference(path string) (types.ImageReference, error) {
	resolved, err := explicitfilepath.ResolvePathToFullyExplicit(path)
	if err != nil {
		return nil, err
	}
	return dirReference{path: path, resolvedPath: resolved}, nil
}

func NewReference ( path string ) ( types . ImageReference , error ) { resolved , err := explicitfilepath . ResolvePathToFullyExplicit ( path ) if err != nil { return nil , err } return dirReference { path : path , resolvedPath : resolved } , nil }

// There is no directory.ParseReference because it is rather pointless.
// Callers who need a transport-independent interface will go through
// dirTransport.ParseReference; callers who intentionally deal with directories
// can use directory.NewReference.
// NewReference returns a directory reference for a specified path.
//
// We do not expose an API supplying the resolvedPath; we could, but recomputing it
// is generally cheap enough that we prefer being confident about the properties of resolvedPath.

There is no directory . ParseReference because it is rather pointless . Callers who need a transport - independent interface will go through dirTransport . ParseReference ; callers who intentionally deal with directories can use directory . NewReference . NewReference returns a directory reference for a specified path . We do not expose an API supplying the resolvedPath ; we could but recomputing it is generally cheap enough that we prefer being confident about the properties of resolvedPath .


func (ref dirReference) layerPath(digest digest.Digest) string {
	// FIXME: Should we keep the digest identification?
	return filepath.Join(ref.path, digest.Hex())
}

// layerPath returns a path for a layer tarball within a directory using our conventions.

layerPath returns a path for a layer tarball within a directory using our conventions .


func (ref dirReference) signaturePath(index int) string {
	return filepath.Join(ref.path, fmt.Sprintf("signature-%d", index+1))
}

func ( ref dirReference ) signaturePath ( index int ) string { return filepath . Join ( ref . path , fmt . Sprintf ( " " , index + 1 ) ) }

// signaturePath returns a path for a signature within a directory using our conventions.

signaturePath returns a path for a signature within a directory using our conventions .


func New(n int, ctor func() Worker) *Pool {
	p := &Pool{
		ctor:    ctor,
		reqChan: make(chan workRequest),
	}
	p.SetSize(n)

	return p
}

func New ( n int , ctor func ( ) Worker ) * Pool { p := & Pool { ctor : ctor , reqChan : make ( chan workRequest ) , } p . SetSize ( n ) return p }

// New creates a new Pool of workers that starts with n workers. You must
// provide a constructor function that creates new Worker types and when you
// change the size of the pool the constructor will be called to create each new
// Worker.

New creates a new Pool of workers that starts with n workers . You must provide a constructor function that creates new Worker types and when you change the size of the pool the constructor will be called to create each new Worker .


func NewFunc(n int, f func(interface{}) interface{}) *Pool {
	return New(n, func() Worker {
		return &closureWorker{
			processor: f,
		}
	})
}

func NewFunc ( n int , f func ( interface { } ) interface { } ) * Pool { return New ( n , func ( ) Worker { return & closureWorker { processor : f , } } ) }

// NewFunc creates a new Pool of workers where each worker will process using
// the provided func.

NewFunc creates a new Pool of workers where each worker will process using the provided func .


func (p *Pool) ProcessTimed(
	payload interface{},
	timeout time.Duration,
) (interface{}, error) {
	atomic.AddInt64(&p.queuedJobs, 1)
	defer atomic.AddInt64(&p.queuedJobs, -1)

	tout := time.NewTimer(timeout)

	var request workRequest
	var open bool

	select {
	case request, open = <-p.reqChan:
		if !open {
			return nil, ErrPoolNotRunning
		}
	case <-tout.C:
		return nil, ErrJobTimedOut
	}

	select {
	case request.jobChan <- payload:
	case <-tout.C:
		request.interruptFunc()
		return nil, ErrJobTimedOut
	}

	select {
	case payload, open = <-request.retChan:
		if !open {
			return nil, ErrWorkerClosed
		}
	case <-tout.C:
		request.interruptFunc()
		return nil, ErrJobTimedOut
	}

	tout.Stop()
	return payload, nil
}

func ( p * Pool ) ProcessTimed ( payload interface { } , timeout time . Duration , ) ( interface { } , error ) { atomic . AddInt64 ( & p . queuedJobs , 1 ) defer atomic . AddInt64 ( & p . queuedJobs , - 1 ) tout := time . NewTimer ( timeout ) var request workRequest var open bool select { case request , open = <- p . reqChan : if ! open { return nil , ErrPoolNotRunning } case <- tout . C : return nil , ErrJobTimedOut } select { case request . jobChan <- payload : case <- tout . C : request . interruptFunc ( ) return nil , ErrJobTimedOut } select { case payload , open = <- request . retChan : if ! open { return nil , ErrWorkerClosed } case <- tout . C : request . interruptFunc ( ) return nil , ErrJobTimedOut } tout . Stop ( ) return payload , nil }

// ProcessTimed will use the Pool to process a payload and synchronously return
// the result. If the timeout occurs before the job has finished the worker will
// be interrupted and ErrJobTimedOut will be returned. ProcessTimed can be
// called safely by any goroutines.

ProcessTimed will use the Pool to process a payload and synchronously return the result . If the timeout occurs before the job has finished the worker will be interrupted and ErrJobTimedOut will be returned . ProcessTimed can be called safely by any goroutines .


func (p *Pool) SetSize(n int) {
	p.workerMut.Lock()
	defer p.workerMut.Unlock()

	lWorkers := len(p.workers)
	if lWorkers == n {
		return
	}

	// Add extra workers if N > len(workers)
	for i := lWorkers; i < n; i++ {
		p.workers = append(p.workers, newWorkerWrapper(p.reqChan, p.ctor()))
	}

	// Asynchronously stop all workers > N
	for i := n; i < lWorkers; i++ {
		p.workers[i].stop()
	}

	// Synchronously wait for all workers > N to stop
	for i := n; i < lWorkers; i++ {
		p.workers[i].join()
	}

	// Remove stopped workers from slice
	p.workers = p.workers[:n]
}

// SetSize changes the total number of workers in the Pool. This can be called
// by any goroutine at any time unless the Pool has been stopped, in which case
// a panic will occur.

SetSize changes the total number of workers in the Pool . This can be called by any goroutine at any time unless the Pool has been stopped in which case a panic will occur .


func (p *Pool) GetSize() int {
	p.workerMut.Lock()
	defer p.workerMut.Unlock()

	return len(p.workers)
}

func ( p * Pool ) GetSize ( ) int { p . workerMut . Lock ( ) defer p . workerMut . Unlock ( ) return len ( p . workers ) }

// GetSize returns the current size of the pool.

GetSize returns the current size of the pool .


func (r *Rect) TL() Point {
	return Point{int(r.x), int(r.y)}
}

func ( r * Rect ) TL ( ) Point { return Point { int ( r . x ) , int ( r . y ) } }

// Returns the Top-Left Point of the rectangle

Returns the Top - Left Point of the rectangle


func (r *Rect) BR() Point {
	return Point{int(r.x) + int(r.width), int(r.y) + int(r.height)}
}

func ( r * Rect ) BR ( ) Point { return Point { int ( r . x ) + int ( r . width ) , int ( r . y ) + int ( r . height ) } }

// Returns the Bottom-Right Point of the rectangle

Returns the Bottom - Right Point of the rectangle


func (box *Box2D) CVBox() C.CvBox2D {
	var cvBox C.CvBox2D
	cvBox.angle = C.float(box.angle)
	cvBox.center.x = C.float(box.center.X)
	cvBox.center.y = C.float(box.center.Y)
	cvBox.size.width = C.float(box.size.Width)
	cvBox.size.height = C.float(box.size.Height)
	return cvBox
}

func ( box * Box2D ) CVBox ( ) C . CvBox2D { var cvBox C . CvBox2D cvBox . angle = C . float ( box . angle ) cvBox . center . x = C . float ( box . center . X ) cvBox . center . y = C . float ( box . center . Y ) cvBox . size . width = C . float ( box . size . Width ) cvBox . size . height = C . float ( box . size . Height ) return cvBox }


func (box *Box2D) Points() []Point2D32f {
	var pts [4]C.CvPoint2D32f
	C.cvBoxPoints(
		box.CVBox(),
		(*C.CvPoint2D32f)(unsafe.Pointer(&pts[0])),
	)
	outPts := make([]Point2D32f, 4)
	for i, p := range pts {
		outPts[i].X = float32(p.x)
		outPts[i].Y = float32(p.y)
	}
	return outPts
}

func ( box * Box2D ) Points ( ) [ ] Point2D32f { var pts [ 4 ] C . CvPoint2D32f C . cvBoxPoints ( box . CVBox ( ) , ( * C . CvPoint2D32f ) ( unsafe . Pointer ( & pts [ 0 ] ) ) , ) outPts := make ( [ ] Point2D32f , 4 ) for i , p := range pts { outPts [ i ] . X = float32 ( p . x ) outPts [ i ] . Y = float32 ( p . y ) } return outPts }


func FOURCC(c1, c2, c3, c4 int8) uint32 {
	rv := C.GoOpenCV_FOURCC_(C.int(c1), C.int(c2), C.int(c3), C.int(c4))
	return uint32(rv)
}

func FOURCC ( c1 , c2 , c3 , c4 int8 ) uint32 { rv := C . GoOpenCV_FOURCC_ ( C . int ( c1 ) , C . int ( c2 ) , C . int ( c3 ) , C . int ( c4 ) ) return uint32 ( rv ) }

// Prototype for CV_FOURCC so that swig can generate wrapper without mixing up the define


func Merge(imgBlue, imgGreen, imgRed, imgAlpha, dst *IplImage) {
	C.cvMerge(
		unsafe.Pointer(imgBlue),
		unsafe.Pointer(imgGreen),
		unsafe.Pointer(imgRed),
		unsafe.Pointer(imgAlpha),
		unsafe.Pointer(dst),
	)
}

func Merge ( imgBlue , imgGreen , imgRed , imgAlpha , dst * IplImage ) { C . cvMerge ( unsafe . Pointer ( imgBlue ) , unsafe . Pointer ( imgGreen ) , unsafe . Pointer ( imgRed ) , unsafe . Pointer ( imgAlpha ) , unsafe . Pointer ( dst ) , ) }

// Merge creates one multichannel array out of several single-channel ones.

Merge creates one multichannel array out of several single - channel ones .


func Split(src, imgBlue, imgGreen, imgRed, imgAlpha *IplImage) {
	C.cvSplit(
		unsafe.Pointer(src),
		unsafe.Pointer(imgBlue),
		unsafe.Pointer(imgGreen),
		unsafe.Pointer(imgRed),
		unsafe.Pointer(imgAlpha),
	)
}

func Split ( src , imgBlue , imgGreen , imgRed , imgAlpha * IplImage ) { C . cvSplit ( unsafe . Pointer ( src ) , unsafe . Pointer ( imgBlue ) , unsafe . Pointer ( imgGreen ) , unsafe . Pointer ( imgRed ) , unsafe . Pointer ( imgAlpha ) , ) }

// Split divides a multi-channel array into several single-channel arrays.

Split divides a multi - channel array into several single - channel arrays .


func AddWeighted(src1 *IplImage, alpha float64, src2 *IplImage, beta float64, gamma float64, dst *IplImage) {
	C.cvAddWeighted(
		unsafe.Pointer(src1),
		C.double(alpha),
		unsafe.Pointer(src2),
		C.double(beta),
		C.double(gamma),
		unsafe.Pointer(dst),
	)
}

func AddWeighted ( src1 * IplImage , alpha float64 , src2 * IplImage , beta float64 , gamma float64 , dst * IplImage ) { C . cvAddWeighted ( unsafe . Pointer ( src1 ) , C . double ( alpha ) , unsafe . Pointer ( src2 ) , C . double ( beta ) , C . double ( gamma ) , unsafe . Pointer ( dst ) , ) }

// AddWeighted calculates the weighted sum of two images.

AddWeighted calculates the weighted sum of two images .


func And(src1, src2, dst *IplImage) {
	AndWithMask(src1, src2, dst, nil)
}

func And ( src1 , src2 , dst * IplImage ) { AndWithMask ( src1 , src2 , dst , nil ) }

// Calculates the per-element bit-wise conjunction of two arrays.

Calculates the per - element bit - wise conjunction of two arrays .


func AndWithMask(src1, src2, dst, mask *IplImage) {
	C.cvAnd(
		unsafe.Pointer(src1),
		unsafe.Pointer(src2),
		unsafe.Pointer(dst),
		unsafe.Pointer(mask),
	)
}

func AndWithMask ( src1 , src2 , dst , mask * IplImage ) { C . cvAnd ( unsafe . Pointer ( src1 ) , unsafe . Pointer ( src2 ) , unsafe . Pointer ( dst ) , unsafe . Pointer ( mask ) , ) }

// Calculates the per-element bit-wise conjunction of two arrays with a mask.

Calculates the per - element bit - wise conjunction of two arrays with a mask .


func AndScalar(src *IplImage, value Scalar, dst *IplImage) {
	AndScalarWithMask(src, value, dst, nil)
}

func AndScalar ( src * IplImage , value Scalar , dst * IplImage ) { AndScalarWithMask ( src , value , dst , nil ) }

// Calculates the per-element bit-wise conjunction of an array and a scalar.

Calculates the per - element bit - wise conjunction of an array and a scalar .


func AndScalarWithMask(src *IplImage, value Scalar, dst, mask *IplImage) {
	C.cvAndS(
		unsafe.Pointer(src),
		(C.CvScalar)(value),
		unsafe.Pointer(dst),
		unsafe.Pointer(mask),
	)
}

func AndScalarWithMask ( src * IplImage , value Scalar , dst , mask * IplImage ) { C . cvAndS ( unsafe . Pointer ( src ) , ( C . CvScalar ) ( value ) , unsafe . Pointer ( dst ) , unsafe . Pointer ( mask ) , ) }

// Calculates the per-element bit-wise conjunction of an array and a scalar with a mask.

Calculates the per - element bit - wise conjunction of an array and a scalar with a mask .


func Or(src1, src2, dst *IplImage) {
	OrWithMask(src1, src2, dst, nil)
}

func Or ( src1 , src2 , dst * IplImage ) { OrWithMask ( src1 , src2 , dst , nil ) }

// Calculates the per-element bit-wise disjunction of two arrays.

Calculates the per - element bit - wise disjunction of two arrays .


func OrWithMask(src1, src2, dst, mask *IplImage) {
	C.cvOr(
		unsafe.Pointer(src1),
		unsafe.Pointer(src2),
		unsafe.Pointer(dst),
		unsafe.Pointer(mask),
	)
}

func OrWithMask ( src1 , src2 , dst , mask * IplImage ) { C . cvOr ( unsafe . Pointer ( src1 ) , unsafe . Pointer ( src2 ) , unsafe . Pointer ( dst ) , unsafe . Pointer ( mask ) , ) }

// Calculates the per-element bit-wise disjunction of two arrays with a mask.

Calculates the per - element bit - wise disjunction of two arrays with a mask .


func OrScalar(src *IplImage, value Scalar, dst *IplImage) {
	OrScalarWithMask(src, value, dst, nil)
}

func OrScalar ( src * IplImage , value Scalar , dst * IplImage ) { OrScalarWithMask ( src , value , dst , nil ) }

// Calculates the per-element bit-wise disjunction of an array and a scalar.

Calculates the per - element bit - wise disjunction of an array and a scalar .


func OrScalarWithMask(src *IplImage, value Scalar, dst, mask *IplImage) {
	C.cvOrS(
		unsafe.Pointer(src),
		(C.CvScalar)(value),
		unsafe.Pointer(dst),
		unsafe.Pointer(mask),
	)
}

func OrScalarWithMask ( src * IplImage , value Scalar , dst , mask * IplImage ) { C . cvOrS ( unsafe . Pointer ( src ) , ( C . CvScalar ) ( value ) , unsafe . Pointer ( dst ) , unsafe . Pointer ( mask ) , ) }

// Calculates the per-element bit-wise disjunction of an array and a scalar with a mask.

Calculates the per - element bit - wise disjunction of an array and a scalar with a mask .


func AddWithMask(src1, src2, dst, mask *IplImage) {
	C.cvAdd(
		unsafe.Pointer(src1),
		unsafe.Pointer(src2),
		unsafe.Pointer(dst),
		unsafe.Pointer(mask),
	)
}

func AddWithMask ( src1 , src2 , dst , mask * IplImage ) { C . cvAdd ( unsafe . Pointer ( src1 ) , unsafe . Pointer ( src2 ) , unsafe . Pointer ( dst ) , unsafe . Pointer ( mask ) , ) }

// Calculates the per-element sum of two arrays with a mask.
//   dst = src1 + src2

Calculates the per - element sum of two arrays with a mask . dst = src1 + src2


func AddScalar(src *IplImage, value Scalar, dst *IplImage) {
	AddScalarWithMask(src, value, dst, nil)
}

func AddScalar ( src * IplImage , value Scalar , dst * IplImage ) { AddScalarWithMask ( src , value , dst , nil ) }

// Calculates the per-element sum of an array and a scalar.
//   dst = src + value

Calculates the per - element sum of an array and a scalar . dst = src + value


func AddScalarWithMask(src *IplImage, value Scalar, dst, mask *IplImage) {
	C.cvAddS(
		unsafe.Pointer(src),
		(C.CvScalar)(value),
		unsafe.Pointer(dst),
		unsafe.Pointer(mask),
	)
}

func AddScalarWithMask ( src * IplImage , value Scalar , dst , mask * IplImage ) { C . cvAddS ( unsafe . Pointer ( src ) , ( C . CvScalar ) ( value ) , unsafe . Pointer ( dst ) , unsafe . Pointer ( mask ) , ) }

// Calculates the per-element sum of an array and a scalar with a mask.
//   dst = src + value

Calculates the per - element sum of an array and a scalar with a mask . dst = src + value


func Subtract(src1, src2, dst *IplImage) {
	SubtractWithMask(src1, src2, dst, nil)
}

func Subtract ( src1 , src2 , dst * IplImage ) { SubtractWithMask ( src1 , src2 , dst , nil ) }

// Calculates the per-element difference between two arrays.
//   dst = src1 - src2

Calculates the per - element difference between two arrays . dst = src1 - src2


func SubtractWithMask(src1, src2, dst, mask *IplImage) {
	C.cvSub(
		unsafe.Pointer(src1),
		unsafe.Pointer(src2),
		unsafe.Pointer(dst),
		unsafe.Pointer(mask),
	)
}

func SubtractWithMask ( src1 , src2 , dst , mask * IplImage ) { C . cvSub ( unsafe . Pointer ( src1 ) , unsafe . Pointer ( src2 ) , unsafe . Pointer ( dst ) , unsafe . Pointer ( mask ) , ) }

// Calculates the per-element difference between two arrays with a mask.
//   dst = src1 - src2

Calculates the per - element difference between two arrays with a mask . dst = src1 - src2


func SubScalar(src *IplImage, value Scalar, dst *IplImage) {
	SubScalarWithMask(src, value, dst, nil)
}

func SubScalar ( src * IplImage , value Scalar , dst * IplImage ) { SubScalarWithMask ( src , value , dst , nil ) }

// Calculates the per-element difference between an array and a scalar.
//   dst = src - value

Calculates the per - element difference between an array and a scalar . dst = src - value


func SubScalarWithMask(src *IplImage, value Scalar, dst, mask *IplImage) {
	C.cvSubS(
		unsafe.Pointer(src),
		(C.CvScalar)(value),
		unsafe.Pointer(dst),
		unsafe.Pointer(mask),
	)
}

func SubScalarWithMask ( src * IplImage , value Scalar , dst , mask * IplImage ) { C . cvSubS ( unsafe . Pointer ( src ) , ( C . CvScalar ) ( value ) , unsafe . Pointer ( dst ) , unsafe . Pointer ( mask ) , ) }

// Calculates the per-element difference between an array and a scalar with a mask.
//   dst = src - value

Calculates the per - element difference between an array and a scalar with a mask . dst = src - value


func SubScalarRev(value Scalar, src, dst *IplImage) {
	SubScalarWithMaskRev(value, src, dst, nil)
}

func SubScalarRev ( value Scalar , src , dst * IplImage ) { SubScalarWithMaskRev ( value , src , dst , nil ) }

// Calculates the per-element difference between a scalar and an array.
//   dst = value - src

Calculates the per - element difference between a scalar and an array . dst = value - src


func SubScalarWithMaskRev(value Scalar, src, dst, mask *IplImage) {
	C.cvSubRS(
		unsafe.Pointer(src),
		(C.CvScalar)(value),
		unsafe.Pointer(dst),
		unsafe.Pointer(mask),
	)
}

func SubScalarWithMaskRev ( value Scalar , src , dst , mask * IplImage ) { C . cvSubRS ( unsafe . Pointer ( src ) , ( C . CvScalar ) ( value ) , unsafe . Pointer ( dst ) , unsafe . Pointer ( mask ) , ) }

// Calculates the per-element difference between a scalar and an array with a mask.
//   dst = value - src

Calculates the per - element difference between a scalar and an array with a mask . dst = value - src


func AbsDiff(src1, src2, dst *IplImage) {
	C.cvAbsDiff(
		unsafe.Pointer(src1),
		unsafe.Pointer(src2),
		unsafe.Pointer(dst),
	)
}

func AbsDiff ( src1 , src2 , dst * IplImage ) { C . cvAbsDiff ( unsafe . Pointer ( src1 ) , unsafe . Pointer ( src2 ) , unsafe . Pointer ( dst ) , ) }

// Calculates the per-element absolute difference between two arrays.

Calculates the per - element absolute difference between two arrays .


func AbsDiffScalar(src *IplImage, value Scalar, dst *IplImage) {
	C.cvAbsDiffS(
		unsafe.Pointer(src),
		unsafe.Pointer(dst),
		(C.CvScalar)(value),
	)
}

func AbsDiffScalar ( src * IplImage , value Scalar , dst * IplImage ) { C . cvAbsDiffS ( unsafe . Pointer ( src ) , unsafe . Pointer ( dst ) , ( C . CvScalar ) ( value ) , ) }

// Calculates the per-element absolute difference between an array and a scalar.

Calculates the per - element absolute difference between an array and a scalar .


func MeanStdDevWithMask(src, mask *IplImage) (Scalar, Scalar) {
	var mean, stdDev Scalar
	C.cvAvgSdv(
		unsafe.Pointer(src),
		(*C.CvScalar)(&mean),
		(*C.CvScalar)(&stdDev),
		unsafe.Pointer(mask),
	)

	return mean, stdDev
}

func MeanStdDevWithMask ( src , mask * IplImage ) ( Scalar , Scalar ) { var mean , stdDev Scalar C . cvAvgSdv ( unsafe . Pointer ( src ) , ( * C . CvScalar ) ( & mean ) , ( * C . CvScalar ) ( & stdDev ) , unsafe . Pointer ( mask ) , ) return mean , stdDev }

// MeanStdDevWithMask calculates mean and standard deviation of pixel values with mask


func CreateSeq(seq_flags, elem_size int) *Seq {
	return (*Seq)(C.cvCreateSeq(
		C.int(seq_flags),
		C.size_t(unsafe.Sizeof(Seq{})),
		C.size_t(elem_size),
		C.cvCreateMemStorage(C.int(0)),
	))
}

func CreateSeq ( seq_flags , elem_size int ) * Seq { return ( * Seq ) ( C . cvCreateSeq ( C . int ( seq_flags ) , C . size_t ( unsafe . Sizeof ( Seq { } ) ) , C . size_t ( elem_size ) , C . cvCreateMemStorage ( C . int ( 0 ) ) , ) ) }


func (seq *Seq) Push(element unsafe.Pointer) unsafe.Pointer {
	return unsafe.Pointer(C.cvSeqPush((*C.struct_CvSeq)(seq), element))
}

func ( seq * Seq ) Push ( element unsafe . Pointer ) unsafe . Pointer { return unsafe . Pointer ( C . cvSeqPush ( ( * C . struct_CvSeq ) ( seq ) , element ) ) }

// Adds an element to the sequence end.
// Returns a pointer to the element added.

Adds an element to the sequence end . Returns a pointer to the element added .


func (seq *Seq) Pop(element unsafe.Pointer) {
	C.cvSeqPop((*C.struct_CvSeq)(seq), element)
}

func ( seq * Seq ) Pop ( element unsafe . Pointer ) { C . cvSeqPop ( ( * C . struct_CvSeq ) ( seq ) , element ) }

// Removes element from the sequence end.
// Copies the element into the paramter element.

Removes element from the sequence end . Copies the element into the paramter element .


func (seq *Seq) PushFront(element unsafe.Pointer) unsafe.Pointer {
	return unsafe.Pointer((C.cvSeqPushFront((*C.struct_CvSeq)(seq), element)))
}

func ( seq * Seq ) PushFront ( element unsafe . Pointer ) unsafe . Pointer { return unsafe . Pointer ( ( C . cvSeqPushFront ( ( * C . struct_CvSeq ) ( seq ) , element ) ) ) }

// Adds an element to the sequence beginning.
// Returns a pointer to the element added.

Adds an element to the sequence beginning . Returns a pointer to the element added .


func (seq *Seq) PopFront(element unsafe.Pointer) {
	C.cvSeqPopFront((*C.struct_CvSeq)(seq), element)
}

func ( seq * Seq ) PopFront ( element unsafe . Pointer ) { C . cvSeqPopFront ( ( * C . struct_CvSeq ) ( seq ) , element ) }

// Removes element from the sequence beginning.
// Copies the element into the paramter element.

Removes element from the sequence beginning . Copies the element into the paramter element .


func (seq *Seq) GetElemAt(index int) unsafe.Pointer {
	return (unsafe.Pointer)(C.cvGetSeqElem(
		(*C.struct_CvSeq)(seq),
		C.int(index),
	))
}

func ( seq * Seq ) GetElemAt ( index int ) unsafe . Pointer { return ( unsafe . Pointer ) ( C . cvGetSeqElem ( ( * C . struct_CvSeq ) ( seq ) , C . int ( index ) , ) ) }

// Gets a pointer to the element at the index


func (seq *Seq) RemoveAt(index int) {
	C.cvSeqRemove((*C.struct_CvSeq)(seq), C.int(index))
}

func ( seq * Seq ) RemoveAt ( index int ) { C . cvSeqRemove ( ( * C . struct_CvSeq ) ( seq ) , C . int ( index ) ) }

// Removes an element from the middle of a sequence.

Removes an element from the middle of a sequence .


func Delay(delay time.Duration) Option {
	return func(c *Config) {
		c.delay = delay
	}
}

func Delay ( delay time . Duration ) Option { return func ( c * Config ) { c . delay = delay } }

// Delay set delay between retry
// default is 100ms

Delay set delay between retry default is 100ms


func BackOffDelay(n uint, config *Config) time.Duration {
	return config.delay * (1 << (n - 1))
}

func BackOffDelay ( n uint , config * Config ) time . Duration { return config . delay * ( 1 << ( n - 1 ) ) }

// BackOffDelay is a DelayType which increases delay between consecutive retries


func (e Error) Error() string {
	logWithNumber := make([]string, lenWithoutNil(e))
	for i, l := range e {
		if l != nil {
			logWithNumber[i] = fmt.Sprintf("#%d: %s", i+1, l.Error())
		}
	}

	return fmt.Sprintf("All attempts fail:\n%s", strings.Join(logWithNumber, "\n"))
}

func ( e Error ) Error ( ) string { logWithNumber := make ( [ ] string , lenWithoutNil ( e ) ) for i , l := range e { if l != nil { logWithNumber [ i ] = fmt . Sprintf ( " " , i + 1 , l . Error ( ) ) } } return fmt . Sprintf ( " \n " , strings . Join ( logWithNumber , " \n " ) ) }

// Error method return string representation of Error
// It is an implementation of error interface

Error method return string representation of Error It is an implementation of error interface


func (r *RequestBuilder) Arguments(args ...string) *RequestBuilder {
	r.args = append(r.args, args...)
	return r
}

func ( r * RequestBuilder ) Arguments ( args ... string ) * RequestBuilder { r . args = append ( r . args , args ... ) return r }

// Arguments adds the arguments to the args.

Arguments adds the arguments to the args .


func (r *RequestBuilder) BodyString(body string) *RequestBuilder {
	return r.Body(strings.NewReader(body))
}

func ( r * RequestBuilder ) BodyString ( body string ) * RequestBuilder { return r . Body ( strings . NewReader ( body ) ) }

// BodyString sets the request body to the given string.

BodyString sets the request body to the given string .


func (r *RequestBuilder) BodyBytes(body []byte) *RequestBuilder {
	return r.Body(bytes.NewReader(body))
}

func ( r * RequestBuilder ) BodyBytes ( body [ ] byte ) * RequestBuilder { return r . Body ( bytes . NewReader ( body ) ) }

// BodyBytes sets the request body to the given buffer.

BodyBytes sets the request body to the given buffer .


func (r *RequestBuilder) Body(body io.Reader) *RequestBuilder {
	r.body = body
	return r
}

func ( r * RequestBuilder ) Body ( body io . Reader ) * RequestBuilder { r . body = body return r }

// Body sets the request body to the given reader.

Body sets the request body to the given reader .


func (r *RequestBuilder) Option(key string, value interface{}) *RequestBuilder {
	var s string
	switch v := value.(type) {
	case bool:
		s = strconv.FormatBool(v)
	case string:
		s = v
	case []byte:
		s = string(v)
	default:
		// slow case.
		s = fmt.Sprint(value)
	}
	if r.opts == nil {
		r.opts = make(map[string]string, 1)
	}
	r.opts[key] = s
	return r
}

func
(
r
*
RequestBuilder
)
Option
(
key
string
,
value
interface
{
}
)
*
RequestBuilder
{
var
s
string
switch
v
:=
value
.
(
type
)
{
case
bool
:
s
=
strconv
.
FormatBool
(
v
)
case
string
:
s
=
v
case
[
]
byte
:
s
=
string
(
v
)
default
:
// slow case.
s
=
fmt
.
Sprint
(
value
)
}
if
r
.
opts
==
{
r
.
opts
=
make
(
map
[
string
]
string
,
1
)
}
r
.
opts
[
key
]
=
s
return
r
}


func (r *RequestBuilder) Header(name, value string) *RequestBuilder {
	if r.headers == nil {
		r.headers = make(map[string]string, 1)
	}
	r.headers[name] = value
	return r
}

func ( r * RequestBuilder ) Header ( name , value string ) * RequestBuilder { if r . headers == nil { r . headers = make ( map [ string ] string , 1 ) } r . headers [ name ] = value return r }


func (r *RequestBuilder) Send(ctx context.Context) (*Response, error) {
	req := NewRequest(ctx, r.shell.url, r.command, r.args...)
	req.Opts = r.opts
	req.Headers = r.headers
	req.Body = r.body
	return req.Send(&r.shell.httpcli)
}

func ( r * RequestBuilder ) Send ( ctx context . Context ) ( * Response , error ) { req := NewRequest ( ctx , r . shell . url , r . command , r . args ... ) req . Opts = r . opts req . Headers = r . headers req . Body = r . body return req . Send ( & r . shell . httpcli ) }

// Send sends the request and return the response.

Send sends the request and return the response .


func (r *RequestBuilder) Exec(ctx context.Context, res interface{}) error {
	httpRes, err := r.Send(ctx)
	if err != nil {
		return err
	}

	if res == nil {
		lateErr := httpRes.Close()
		if httpRes.Error != nil {
			return httpRes.Error
		}
		return lateErr
	}

	return httpRes.Decode(res)
}

func ( r * RequestBuilder ) Exec ( ctx context . Context , res interface { } ) error { httpRes , err := r . Send ( ctx ) if err != nil { return err } if res == nil { lateErr := httpRes . Close ( ) if httpRes . Error != nil { return httpRes . Error } return lateErr } return httpRes . Decode ( res ) }

// Exec sends the request a request and decodes the response.

Exec sends the request a request and decodes the response .


func (s *PubSubSubscription) Next() (*Message, error) {
	if s.resp.Error != nil {
		return nil, s.resp.Error
	}

	d := json.NewDecoder(s.resp.Output)

	var r struct {
		From     []byte   `json:"from,omitempty"`
		Data     []byte   `json:"data,omitempty"`
		Seqno    []byte   `json:"seqno,omitempty"`
		TopicIDs []string `json:"topicIDs,omitempty"`
	}

	err := d.Decode(&r)
	if err != nil {
		return nil, err
	}

	from, err := peer.IDFromBytes(r.From)
	if err != nil {
		return nil, err
	}
	return &Message{
		From:     from,
		Data:     r.Data,
		Seqno:    r.Seqno,
		TopicIDs: r.TopicIDs,
	}, nil
}

func ( s * PubSubSubscription ) Next ( ) ( * Message , error ) { if s . resp . Error != nil { return nil , s . resp . Error } d := json . NewDecoder ( s . resp . Output ) var r struct { From [ ] byte `json:"from,omitempty"` Data [ ] byte `json:"data,omitempty"` Seqno [ ] byte `json:"seqno,omitempty"` TopicIDs [ ] string `json:"topicIDs,omitempty"` } err := d . Decode ( & r ) if err != nil { return nil , err } from , err := peer . IDFromBytes ( r . From ) if err != nil { return nil , err } return & Message { From : from , Data : r . Data , Seqno : r . Seqno , TopicIDs : r . TopicIDs , } , nil }

// Next waits for the next record and returns that.

Next waits for the next record and returns that .


func (s *PubSubSubscription) Cancel() error {
	if s.resp.Output == nil {
		return nil
	}

	return s.resp.Output.Close()
}

func ( s * PubSubSubscription ) Cancel ( ) error { if s . resp . Output == nil { return nil } return s . resp . Output . Close ( ) }

// Cancel cancels the given subscription.


func (s *Shell) FileList(path string) (*UnixLsObject, error) {
	var out lsOutput
	if err := s.Request("file/ls", path).Exec(context.Background(), &out); err != nil {
		return nil, err
	}

	for _, object := range out.Objects {
		return object, nil
	}

	return nil, fmt.Errorf("no object in results")
}

func ( s * Shell ) FileList ( path string ) ( * UnixLsObject , error ) { var out lsOutput if err := s . Request ( " " , path ) . Exec ( context . Background ( ) , & out ) ; err != nil { return nil , err } for _ , object := range out . Objects { return object , nil } return nil , fmt . Errorf ( " " ) }

// FileList entries at the given path using the UnixFS commands


func (s *Shell) Cat(path string) (io.ReadCloser, error) {
	resp, err := s.Request("cat", path).Send(context.Background())
	if err != nil {
		return nil, err
	}
	if resp.Error != nil {
		return nil, resp.Error
	}

	return resp.Output, nil
}

func ( s * Shell ) Cat ( path string ) ( io . ReadCloser , error ) { resp , err := s . Request ( " " , path ) . Send ( context . Background ( ) ) if err != nil { return nil , err } if resp . Error != nil { return nil , resp . Error } return resp . Output , nil }

// Cat the content at the given path. Callers need to drain and close the returned reader after usage.

Cat the content at the given path . Callers need to drain and close the returned reader after usage .


func (s *Shell) List(path string) ([]*LsLink, error) {
	var out struct{ Objects []LsObject }
	err := s.Request("ls", path).Exec(context.Background(), &out)
	if err != nil {
		return nil, err
	}
	if len(out.Objects) != 1 {
		return nil, errors.New("bad response from server")
	}
	return out.Objects[0].Links, nil
}

func ( s * Shell ) List ( path string ) ( [ ] * LsLink , error ) { var out struct { Objects [ ] LsObject } err := s . Request ( " " , path ) . Exec ( context . Background ( ) , & out ) if err != nil { return nil , err } if len ( out . Objects ) != 1 { return nil , errors . New ( " " ) } return out . Objects [ 0 ] . Links , nil }


func (s *Shell) Pin(path string) error {
	return s.Request("pin/add", path).
		Option("recursive", true).
		Exec(context.Background(), nil)
}

func ( s * Shell ) Pin ( path string ) error { return s . Request ( " " , path ) . Option ( " " , true ) . Exec ( context . Background ( ) , nil ) }


func (s *Shell) Pins() (map[string]PinInfo, error) {
	var raw struct{ Keys map[string]PinInfo }
	return raw.Keys, s.Request("pin/ls").Exec(context.Background(), &raw)
}

func ( s * Shell ) Pins ( ) ( map [ string ] PinInfo , error ) { var raw struct { Keys map [ string ] PinInfo } return raw . Keys , s . Request ( " " ) . Exec ( context . Background ( ) , & raw ) }

// Pins returns a map of the pin hashes to their info (currently just the
// pin type, one of DirectPin, RecursivePin, or IndirectPin. A map is returned
// instead of a slice because it is easier to do existence lookup by map key
// than unordered array searching. The map is likely to be more useful to a
// client than a flat list.

Pins returns a map of the pin hashes to their info ( currently just the pin type one of DirectPin RecursivePin or IndirectPin . A map is returned instead of a slice because it is easier to do existence lookup by map key than unordered array searching . The map is likely to be more useful to a client than a flat list .


func (s *Shell) Version() (string, string, error) {
	ver := struct {
		Version string
		Commit  string
	}{}

	if err := s.Request("version").Exec(context.Background(), &ver); err != nil {
		return "", "", err
	}
	return ver.Version, ver.Commit, nil
}

func ( s * Shell ) Version ( ) ( string , string , error ) { ver := struct { Version string Commit string } { } if err := s . Request ( " " ) . Exec ( context . Background ( ) , & ver ) ; err != nil { return " " , " " , err } return ver . Version , ver . Commit , nil }


func (s *Shell) SwarmPeers(ctx context.Context) (*SwarmConnInfos, error) {
	v := &SwarmConnInfos{}
	err := s.Request("swarm/peers").Exec(ctx, &v)
	return v, err
}

func ( s * Shell ) SwarmPeers ( ctx context . Context ) ( * SwarmConnInfos , error ) { v := & SwarmConnInfos { } err := s . Request ( " " ) . Exec ( ctx , & v ) return v , err }


func (s *Shell) SwarmConnect(ctx context.Context, addr ...string) error {
	var conn *swarmConnection
	err := s.Request("swarm/connect").
		Arguments(addr...).
		Exec(ctx, &conn)
	return err
}

func ( s * Shell ) SwarmConnect ( ctx context . Context , addr ... string ) error { var conn * swarmConnection err := s . Request ( " " ) . Arguments ( addr ... ) . Exec ( ctx , & conn ) return err }

// SwarmConnect opens a swarm connection to a specific address.

SwarmConnect opens a swarm connection to a specific address .


func DagPutOptions(opts ...DagPutOption) (*DagPutSettings, error) {
	options := &DagPutSettings{
		InputEnc: "json",
		Kind:     "cbor",
		Pin:      "false",
		Hash:     "sha2-256",
	}

	for _, opt := range opts {
		err := opt(options)
		if err != nil {
			return nil, err
		}
	}
	return options, nil
}

func DagPutOptions ( opts ... DagPutOption ) ( * DagPutSettings , error ) { options := & DagPutSettings { InputEnc : " " , Kind : " " , Pin : " " , Hash : " " , } for _ , opt := range opts { err := opt ( options ) if err != nil { return nil , err } } return options , nil }

// DagPutOptions applies the given options to a DagPutSettings instance.

DagPutOptions applies the given options to a DagPutSettings instance .


func (dagOpts) Pin(pin string) DagPutOption {
	return func(opts *DagPutSettings) error {
		opts.Pin = pin
		return nil
	}
}

func ( dagOpts ) Pin ( pin string ) DagPutOption { return func ( opts * DagPutSettings ) error { opts . Pin = pin return nil } }

// Pin is an option for Dag.Put which specifies whether to pin the added
// dags. Default is "false".

Pin is an option for Dag . Put which specifies whether to pin the added dags . Default is false .


func (dagOpts) Kind(kind string) DagPutOption {
	return func(opts *DagPutSettings) error {
		opts.Kind = kind
		return nil
	}
}

func ( dagOpts ) Kind ( kind string ) DagPutOption { return func ( opts * DagPutSettings ) error { opts . Kind = kind return nil } }

// Kind is an option for Dag.Put which specifies the format that the dag
// will be added as. Default is "cbor".

Kind is an option for Dag . Put which specifies the format that the dag will be added as . Default is cbor .


func (dagOpts) Hash(hash string) DagPutOption {
	return func(opts *DagPutSettings) error {
		opts.Hash = hash
		return nil
	}
}

func ( dagOpts ) Hash ( hash string ) DagPutOption { return func ( opts * DagPutSettings ) error { opts . Hash = hash return nil } }

// Hash is an option for Dag.Put which specifies the hash function to use

Hash is an option for Dag . Put which specifies the hash function to use


func (s *Shell) AddDir(dir string) (string, error) {
	stat, err := os.Lstat(dir)
	if err != nil {
		return "", err
	}

	sf, err := files.NewSerialFile(dir, false, stat)
	if err != nil {
		return "", err
	}
	slf := files.NewSliceDirectory([]files.DirEntry{files.FileEntry(filepath.Base(dir), sf)})
	reader := files.NewMultiFileReader(slf, true)

	resp, err := s.Request("add").
		Option("recursive", true).
		Body(reader).
		Send(context.Background())
	if err != nil {
		return "", nil
	}

	defer resp.Close()

	if resp.Error != nil {
		return "", resp.Error
	}

	dec := json.NewDecoder(resp.Output)
	var final string
	for {
		var out object
		err = dec.Decode(&out)
		if err != nil {
			if err == io.EOF {
				break
			}
			return "", err
		}
		final = out.Hash
	}

	if final == "" {
		return "", errors.New("no results received")
	}

	return final, nil
}

func ( s * Shell ) AddDir ( dir string ) ( string , error ) { stat , err := os . Lstat ( dir ) if err != nil { return " " , err } sf , err := files . NewSerialFile ( dir , false , stat ) if err != nil { return " " , err } slf := files . NewSliceDirectory ( [ ] files . DirEntry { files . FileEntry ( filepath . Base ( dir ) , sf ) } ) reader := files . NewMultiFileReader ( slf , true ) resp , err := s . Request ( " " ) . Option ( " " , true ) . Body ( reader ) . Send ( context . Background ( ) ) if err != nil { return " " , nil } defer resp . Close ( ) if resp . Error != nil { return " " , resp . Error } dec := json . NewDecoder ( resp . Output ) var final string for { var out object err = dec . Decode ( & out ) if err != nil { if err == io . EOF { break } return " " , err } final = out . Hash } if final == " " { return " " , errors . New ( " " ) } return final , nil }

// AddDir adds a directory recursively with all of the files under it


func (s *Shell) Publish(node string, value string) error {
	var pubResp PublishResponse
	req := s.Request("name/publish")
	if node != "" {
		req.Arguments(node)
	}
	req.Arguments(value)

	return req.Exec(context.Background(), &pubResp)
}

func ( s * Shell ) Publish ( node string , value string ) error { var pubResp PublishResponse req := s . Request ( " " ) if node != " " { req . Arguments ( node ) } req . Arguments ( value ) return req . Exec ( context . Background ( ) , & pubResp ) }

// Publish updates a mutable name to point to a given value


func (s *Shell) PublishWithDetails(contentHash, key string, lifetime, ttl time.Duration, resolve bool) (*PublishResponse, error) {
	var pubResp PublishResponse
	req := s.Request("name/publish", contentHash).Option("resolve", resolve)
	if key != "" {
		req.Option("key", key)
	}
	if lifetime != 0 {
		req.Option("lifetime", lifetime)
	}
	if ttl.Seconds() > 0 {
		req.Option("ttl", ttl)
	}
	err := req.Exec(context.Background(), &pubResp)
	if err != nil {
		return nil, err
	}
	return &pubResp, nil
}

func ( s * Shell ) PublishWithDetails ( contentHash , key string , lifetime , ttl time . Duration , resolve bool ) ( * PublishResponse , error ) { var pubResp PublishResponse req := s . Request ( " " , contentHash ) . Option ( " " , resolve ) if key != " " { req . Option ( " " , key ) } if lifetime != 0 { req . Option ( " " , lifetime ) } if ttl . Seconds ( ) > 0 { req . Option ( " " , ttl ) } err := req . Exec ( context . Background ( ) , & pubResp ) if err != nil { return nil , err } return & pubResp , nil }

// PublishWithDetails is used for fine grained control over record publishing


func (pv PlanValue) ResolveValue(bindVars map[string]*querypb.BindVariable) (Value, error) {
	switch {
	case pv.Key != "":
		bv, err := pv.lookupValue(bindVars)
		if err != nil {
			return NULL, err
		}
		return MakeTrusted(bv.Type, bv.Value), nil
	case !pv.Value.IsNull():
		return pv.Value, nil
	case pv.ListKey != "" || pv.Values != nil:
		// This code is unreachable because the parser does not allow
		// multi-value constructs where a single value is expected.
		return NULL, errors.New("a list was supplied where a single value was expected")
	}
	return NULL, nil
}

// ResolveValue resolves a PlanValue as a single value based on the supplied bindvars.

ResolveValue resolves a PlanValue as a single value based on the supplied bindvars .


func (pq *ParsedQuery) GenerateQuery(bindVariables map[string]*querypb.BindVariable, extras map[string]Encodable) ([]byte, error) {
	if len(pq.bindLocations) == 0 {
		return []byte(pq.Query), nil
	}
	buf := bytes.NewBuffer(make([]byte, 0, len(pq.Query)))
	current := 0
	for _, loc := range pq.bindLocations {
		buf.WriteString(pq.Query[current:loc.offset])
		name := pq.Query[loc.offset : loc.offset+loc.length]
		if encodable, ok := extras[name[1:]]; ok {
			encodable.EncodeSQL(buf)
		} else {
			supplied, _, err := FetchBindVar(name, bindVariables)
			if err != nil {
				return nil, err
			}
			EncodeValue(buf, supplied)
		}
		current = loc.offset + loc.length
	}
	buf.WriteString(pq.Query[current:])
	return buf.Bytes(), nil
}

func ( pq * ParsedQuery ) GenerateQuery ( bindVariables map [ string ] * querypb . BindVariable , extras map [ string ] Encodable ) ( [ ] byte , error ) { if len ( pq . bindLocations ) == 0 { return [ ] byte ( pq . Query ) , nil } buf := bytes . NewBuffer ( make ( [ ] byte , 0 , len ( pq . Query ) ) ) current := 0 for _ , loc := range pq . bindLocations { buf . WriteString ( pq . Query [ current : loc . offset ] ) name := pq . Query [ loc . offset : loc . offset + loc . length ] if encodable , ok := extras [ name [ 1 : ] ] ; ok { encodable . EncodeSQL ( buf ) } else { supplied , _ , err := FetchBindVar ( name , bindVariables ) if err != nil { return nil , err } EncodeValue ( buf , supplied ) } current = loc . offset + loc . length } buf . WriteString ( pq . Query [ current : ] ) return buf . Bytes ( ) , nil }

// GenerateQuery generates a query by substituting the specified
// bindVariables. The extras parameter specifies special parameters
// that can perform custom encoding.

GenerateQuery generates a query by substituting the specified bindVariables . The extras parameter specifies special parameters that can perform custom encoding .


func EncodeValue(buf *bytes.Buffer, value *querypb.BindVariable) {
	if value.Type != querypb.Type_TUPLE {
		// Since we already check for TUPLE, we don't expect an error.
		v, _ := sqltypes.BindVariableToValue(value)
		v.EncodeSQL(buf)
		return
	}

	// It's a TUPLE.
	buf.WriteByte('(')
	for i, bv := range value.Values {
		if i != 0 {
			buf.WriteString(", ")
		}
		sqltypes.ProtoToValue(bv).EncodeSQL(buf)
	}
	buf.WriteByte(')')
}

// EncodeValue encodes one bind variable value into the query.

EncodeValue encodes one bind variable value into the query .


func (tkn *Tokenizer) Lex(lval *yySymType) int {
	typ, val := tkn.Scan()
	for typ == COMMENT {
		if tkn.AllowComments {
			break
		}
		typ, val = tkn.Scan()
	}
	lval.bytes = val
	tkn.lastToken = val
	return typ
}

func ( tkn * Tokenizer ) Lex ( lval * yySymType ) int { typ , val := tkn . Scan ( ) for typ == COMMENT { if tkn . AllowComments { break } typ , val = tkn . Scan ( ) } lval . bytes = val tkn . lastToken = val return typ }

// Lex returns the next token form the Tokenizer.
// This function is used by go yacc.

Lex returns the next token form the Tokenizer . This function is used by go yacc .


func (tkn *Tokenizer) skipStatement() {
	ch := tkn.lastChar
	for ch != ';' && ch != eofChar {
		tkn.next()
		ch = tkn.lastChar
	}
}

func ( tkn * Tokenizer ) skipStatement ( ) { ch := tkn . lastChar for ch != ';' && ch != eofChar { tkn . next ( ) ch = tkn . lastChar } }

// skipStatement scans until the EOF, or end of statement is encountered.

skipStatement scans until the EOF or end of statement is encountered .


func (tkn *Tokenizer) reset() {
	tkn.ParseTree = nil
	tkn.partialDDL = nil
	tkn.specialComment = nil
	tkn.posVarIndex = 0
	tkn.nesting = 0
	tkn.ForceEOF = false
}

func ( tkn * Tokenizer ) reset ( ) { tkn . ParseTree = nil tkn . partialDDL = nil tkn . specialComment = nil tkn . posVarIndex = 0 tkn . nesting = 0 tkn . ForceEOF = false }


func Preview(sql string) int {
	trimmed := StripLeadingComments(sql)

	firstWord := trimmed
	if end := strings.IndexFunc(trimmed, unicode.IsSpace); end != -1 {
		firstWord = trimmed[:end]
	}
	firstWord = strings.TrimLeftFunc(firstWord, func(r rune) bool { return !unicode.IsLetter(r) })
	// Comparison is done in order of priority.
	loweredFirstWord := strings.ToLower(firstWord)
	switch loweredFirstWord {
	case "select":
		return StmtSelect
	case "stream":
		return StmtStream
	case "insert":
		return StmtInsert
	case "replace":
		return StmtReplace
	case "update":
		return StmtUpdate
	case "delete":
		return StmtDelete
	}
	// For the following statements it is not sufficient to rely
	// on loweredFirstWord. This is because they are not statements
	// in the grammar and we are relying on Preview to parse them.
	// For instance, we don't want: "BEGIN JUNK" to be parsed
	// as StmtBegin.
	trimmedNoComments, _ := SplitMarginComments(trimmed)
	switch strings.ToLower(trimmedNoComments) {
	case "begin", "start transaction":
		return StmtBegin
	case "commit":
		return StmtCommit
	case "rollback":
		return StmtRollback
	}
	switch loweredFirstWord {
	case "create", "alter", "rename", "drop", "truncate":
		return StmtDDL
	case "set":
		return StmtSet
	case "show":
		return StmtShow
	case "use":
		return StmtUse
	case "analyze", "describe", "desc", "explain", "repair", "optimize":
		return StmtOther
	}
	if strings.Index(trimmed, "/*!") == 0 {
		return StmtComment
	}
	return StmtUnknown
}

// Preview analyzes the beginning of the query using a simpler and faster
// textual comparison to identify the statement type.

Preview analyzes the beginning of the query using a simpler and faster textual comparison to identify the statement type .


func NewPlanValue(node Expr) (sqltypes.PlanValue, error) {
	switch node := node.(type) {
	case *SQLVal:
		switch node.Type {
		case ValArg:
			return sqltypes.PlanValue{Key: string(node.Val[1:])}, nil
		case IntVal:
			n, err := sqltypes.NewIntegral(string(node.Val))
			if err != nil {
				return sqltypes.PlanValue{}, fmt.Errorf("%v", err)
			}
			return sqltypes.PlanValue{Value: n}, nil
		case StrVal:
			return sqltypes.PlanValue{Value: sqltypes.MakeTrusted(sqltypes.VarBinary, node.Val)}, nil
		case HexVal:
			v, err := node.HexDecode()
			if err != nil {
				return sqltypes.PlanValue{}, fmt.Errorf("%v", err)
			}
			return sqltypes.PlanValue{Value: sqltypes.MakeTrusted(sqltypes.VarBinary, v)}, nil
		}
	case ListArg:
		return sqltypes.PlanValue{ListKey: string(node[2:])}, nil
	case ValTuple:
		pv := sqltypes.PlanValue{
			Values: make([]sqltypes.PlanValue, 0, len(node)),
		}
		for _, val := range node {
			innerpv, err := NewPlanValue(val)
			if err != nil {
				return sqltypes.PlanValue{}, err
			}
			if innerpv.ListKey != "" || innerpv.Values != nil {
				return sqltypes.PlanValue{}, errors.New("unsupported: nested lists")
			}
			pv.Values = append(pv.Values, innerpv)
		}
		return pv, nil
	case *NullVal:
		return sqltypes.PlanValue{}, nil
	}
	return sqltypes.PlanValue{}, fmt.Errorf("expression is too complex '%v'", String(node))
}

func NewPlanValue ( node Expr ) ( sqltypes . PlanValue , error ) { switch node := node . ( type ) { case * SQLVal : switch node . Type { case ValArg : return sqltypes . PlanValue { Key : string ( node . Val [ 1 : ] ) } , nil case IntVal : n , err := sqltypes . NewIntegral ( string ( node . Val ) ) if err != nil { return sqltypes . PlanValue { } , fmt . Errorf ( " " , err ) } return sqltypes . PlanValue { Value : n } , nil case StrVal : return sqltypes . PlanValue { Value : sqltypes . MakeTrusted ( sqltypes . VarBinary , node . Val ) } , nil case HexVal : v , err := node . HexDecode ( ) if err != nil { return sqltypes . PlanValue { } , fmt . Errorf ( " " , err ) } return sqltypes . PlanValue { Value : sqltypes . MakeTrusted ( sqltypes . VarBinary , v ) } , nil } case ListArg : return sqltypes . PlanValue { ListKey : string ( node [ 2 : ] ) } , nil case ValTuple : pv := sqltypes . PlanValue { Values : make ( [ ] sqltypes . PlanValue , 0 , len ( node ) ) , } for _ , val := range node { innerpv , err := NewPlanValue ( val ) if err != nil { return sqltypes . PlanValue { } , err } if innerpv . ListKey != " " || innerpv . Values != nil { return sqltypes . PlanValue { } , errors . New ( " " ) } pv . Values = append ( pv . Values , innerpv ) } return pv , nil case * NullVal : return sqltypes . PlanValue { } , nil } return sqltypes . PlanValue { } , fmt . Errorf ( " " , String ( node ) ) }

// NewPlanValue builds a sqltypes.PlanValue from an Expr.

NewPlanValue builds a sqltypes . PlanValue from an Expr .


func StringIn(str string, values ...string) bool {
	for _, val := range values {
		if str == val {
			return true
		}
	}
	return false
}

func StringIn ( str string , values ... string ) bool { for _ , val := range values { if str == val { return true } } return false }

// StringIn is a convenience function that returns
// true if str matches any of the values.

StringIn is a convenience function that returns true if str matches any of the values .


func NewTrackedBuffer(nodeFormatter NodeFormatter) *TrackedBuffer {
	return &TrackedBuffer{
		Buffer:        new(bytes.Buffer),
		nodeFormatter: nodeFormatter,
	}
}

func NewTrackedBuffer ( nodeFormatter NodeFormatter ) * TrackedBuffer { return & TrackedBuffer { Buffer : new ( bytes . Buffer ) , nodeFormatter : nodeFormatter , } }

// NewTrackedBuffer creates a new TrackedBuffer.

NewTrackedBuffer creates a new TrackedBuffer .


func NewStringArena(size int) *StringArena {
	sa := &StringArena{buf: make([]byte, 0, size)}
	pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&sa.buf))
	pstring := (*reflect.StringHeader)(unsafe.Pointer(&sa.str))
	pstring.Data = pbytes.Data
	pstring.Len = pbytes.Cap
	return sa
}

func NewStringArena ( size int ) * StringArena { sa := & StringArena { buf : make ( [ ] byte , 0 , size ) } pbytes := ( * reflect . SliceHeader ) ( unsafe . Pointer ( & sa . buf ) ) pstring := ( * reflect . StringHeader ) ( unsafe . Pointer ( & sa . str ) ) pstring . Data = pbytes . Data pstring . Len = pbytes . Cap return sa }

// NewStringArena creates an arena of the specified size.

NewStringArena creates an arena of the specified size .


func (sa *StringArena) NewString(b []byte) string {
	if len(b) == 0 {
		return ""
	}
	if len(sa.buf)+len(b) > cap(sa.buf) {
		return string(b)
	}
	start := len(sa.buf)
	sa.buf = append(sa.buf, b...)
	return sa.str[start : start+len(b)]
}

func ( sa * StringArena ) NewString ( b [ ] byte ) string { if len ( b ) == 0 { return " " } if len ( sa . buf ) + len ( b ) > cap ( sa . buf ) { return string ( b ) } start := len ( sa . buf ) sa . buf = append ( sa . buf , b ... ) return sa . str [ start : start + len ( b ) ] }

// NewString copies a byte slice into the arena and returns it as a string.
// If the arena is full, it returns a traditional go string.

NewString copies a byte slice into the arena and returns it as a string . If the arena is full it returns a traditional go string .


func (sa *StringArena) SpaceLeft() int {
	return cap(sa.buf) - len(sa.buf)
}

func ( sa * StringArena ) SpaceLeft ( ) int { return cap ( sa . buf ) - len ( sa . buf ) }

// SpaceLeft returns the amount of space left in the arena.

SpaceLeft returns the amount of space left in the arena .


func ParseStrictDDL(sql string) (Statement, error) {
	tokenizer := NewStringTokenizer(sql)
	if yyParse(tokenizer) != 0 {
		return nil, tokenizer.LastError
	}
	return tokenizer.ParseTree, nil
}

func ParseStrictDDL ( sql string ) ( Statement , error ) { tokenizer := NewStringTokenizer ( sql ) if yyParse ( tokenizer ) != 0 { return nil , tokenizer . LastError } return tokenizer . ParseTree , nil }

// ParseStrictDDL is the same as Parse except it errors on
// partially parsed DDL statements.

ParseStrictDDL is the same as Parse except it errors on partially parsed DDL statements .


func ParseNext(tokenizer *Tokenizer) (Statement, error) {
	if tokenizer.lastChar == ';' {
		tokenizer.next()
		tokenizer.skipBlank()
	}
	if tokenizer.lastChar == eofChar {
		return nil, io.EOF
	}

	tokenizer.reset()
	tokenizer.multi = true
	if yyParse(tokenizer) != 0 {
		if tokenizer.partialDDL != nil {
			tokenizer.ParseTree = tokenizer.partialDDL
			return tokenizer.ParseTree, nil
		}
		return nil, tokenizer.LastError
	}
	return tokenizer.ParseTree, nil
}

func ParseNext ( tokenizer * Tokenizer ) ( Statement , error ) { if tokenizer . lastChar == ';' { tokenizer . next ( ) tokenizer . skipBlank ( ) } if tokenizer . lastChar == eofChar { return nil , io . EOF } tokenizer . reset ( ) tokenizer . multi = true if yyParse ( tokenizer ) != 0 { if tokenizer . partialDDL != nil { tokenizer . ParseTree = tokenizer . partialDDL return tokenizer . ParseTree , nil } return nil , tokenizer . LastError } return tokenizer . ParseTree , nil }

// ParseNext parses a single SQL statement from the tokenizer
// returning a Statement which is the AST representation of the query.
// The tokenizer will always read up to the end of the statement, allowing for
// the next call to ParseNext to parse any subsequent SQL statements. When
// there are no more statements to parse, a error of io.EOF is returned.

ParseNext parses a single SQL statement from the tokenizer returning a Statement which is the AST representation of the query . The tokenizer will always read up to the end of the statement allowing for the next call to ParseNext to parse any subsequent SQL statements . When there are no more statements to parse a error of io . EOF is returned .


func Append(buf *bytes.Buffer, node SQLNode) {
	tbuf := &TrackedBuffer{
		Buffer: buf,
	}
	node.Format(tbuf)
}

func Append ( buf * bytes . Buffer , node SQLNode ) { tbuf := & TrackedBuffer { Buffer : buf , } node . Format ( tbuf ) }

// Append appends the SQLNode to the buffer.

Append appends the SQLNode to the buffer .


func ExprFromValue(value sqltypes.Value) (Expr, error) {
	// The type checks here follow the rules defined in sqltypes/types.go.
	switch {
	case value.Type() == sqltypes.Null:
		return &NullVal{}, nil
	case value.IsIntegral():
		return NewIntVal(value.ToBytes()), nil
	case value.IsFloat() || value.Type() == sqltypes.Decimal:
		return NewFloatVal(value.ToBytes()), nil
	case value.IsQuoted():
		return NewStrVal(value.ToBytes()), nil
	default:
		// We cannot support sqltypes.Expression, or any other invalid type.
		return nil, fmt.Errorf("cannot convert value %v to AST", value)
	}
}

// ExprFromValue converts the given Value into an Expr or returns an error.

ExprFromValue converts the given Value into an Expr or returns an error .


func Backtick(in string) string {
	var buf bytes.Buffer
	buf.WriteByte('`')
	for _, c := range in {
		buf.WriteRune(c)
		if c == '`' {
			buf.WriteByte('`')
		}
	}
	buf.WriteByte('`')
	return buf.String()
}

func Backtick ( in string ) string { var buf bytes . Buffer buf . WriteByte ( '`' ) for _ , c := range in { buf . WriteRune ( c ) if c == '`' { buf . WriteByte ( '`' ) } } buf . WriteByte ( '`' ) return buf . String ( ) }

// Backtick produces a backticked literal given an input string.

Backtick produces a backticked literal given an input string .


func NewValue(typ querypb.Type, val []byte) (v Value, err error) {
	switch {
	case IsSigned(typ):
		if _, err := strconv.ParseInt(string(val), 0, 64); err != nil {
			return NULL, err
		}
		return MakeTrusted(typ, val), nil
	case IsUnsigned(typ):
		if _, err := strconv.ParseUint(string(val), 0, 64); err != nil {
			return NULL, err
		}
		return MakeTrusted(typ, val), nil
	case IsFloat(typ) || typ == Decimal:
		if _, err := strconv.ParseFloat(string(val), 64); err != nil {
			return NULL, err
		}
		return MakeTrusted(typ, val), nil
	case IsQuoted(typ) || typ == Null:
		return MakeTrusted(typ, val), nil
	}
	// All other types are unsafe or invalid.
	return NULL, fmt.Errorf("invalid type specified for MakeValue: %v", typ)
}

// NewValue builds a Value using typ and val. If the value and typ
// don't match, it returns an error.

NewValue builds a Value using typ and val . If the value and typ don t match it returns an error .


func (v Value) String() string {
	if v.typ == Null {
		return "NULL"
	}
	if v.IsQuoted() {
		return fmt.Sprintf("%v(%q)", v.typ, v.val)
	}
	return fmt.Sprintf("%v(%s)", v.typ, v.val)
}

func ( v Value ) String ( ) string { if v . typ == Null { return " " } if v . IsQuoted ( ) { return fmt . Sprintf ( " " , v . typ , v . val ) } return fmt . Sprintf ( " " , v . typ , v . val ) }

// String returns a printable version of the value.

String returns a printable version of the value .


func (v Value) EncodeSQL(b BinWriter) {
	switch {
	case v.typ == Null:
		b.Write(nullstr)
	case v.IsQuoted():
		encodeBytesSQL(v.val, b)
	default:
		b.Write(v.val)
	}
}

func ( v Value ) EncodeSQL ( b BinWriter ) { switch { case v . typ == Null : b . Write ( nullstr ) case v . IsQuoted ( ) : encodeBytesSQL ( v . val , b ) default : b . Write ( v . val ) } }

// EncodeSQL encodes the value into an SQL statement. Can be binary.

EncodeSQL encodes the value into an SQL statement . Can be binary .


func (iv InsertValues) EncodeSQL(buf *bytes.Buffer) {
	for i, rows := range iv {
		if i != 0 {
			buf.WriteString(", ")
		}
		buf.WriteByte('(')
		for j, bv := range rows {
			if j != 0 {
				buf.WriteString(", ")
			}
			bv.EncodeSQL(buf)
		}
		buf.WriteByte(')')
	}
}

func ( iv InsertValues ) EncodeSQL ( buf * bytes . Buffer ) { for i , rows := range iv { if i != 0 { buf . WriteString ( " " ) } buf . WriteByte ( '(' ) for j , bv := range rows { if j != 0 { buf . WriteString ( " " ) } bv . EncodeSQL ( buf ) } buf . WriteByte ( ')' ) } }

// EncodeSQL performs the SQL encoding for InsertValues.

EncodeSQL performs the SQL encoding for InsertValues .


func (tpl *TupleEqualityList) EncodeSQL(buf *bytes.Buffer) {
	if len(tpl.Columns) == 1 {
		tpl.encodeAsIn(buf)
		return
	}
	tpl.encodeAsEquality(buf)
}

func ( tpl * TupleEqualityList ) EncodeSQL ( buf * bytes . Buffer ) { if len ( tpl . Columns ) == 1 { tpl . encodeAsIn ( buf ) return } tpl . encodeAsEquality ( buf ) }

// EncodeSQL generates the where clause constraints for the tuple
// equality.

EncodeSQL generates the where clause constraints for the tuple equality .


func (nz *normalizer) WalkStatement(node SQLNode) (bool, error) {
	switch node := node.(type) {
	case *Select:
		_ = Walk(nz.WalkSelect, node)
		// Don't continue
		return false, nil
	case *SQLVal:
		nz.convertSQLVal(node)
	case *ComparisonExpr:
		nz.convertComparison(node)
	}
	return true, nil
}

func
(
nz
*
normalizer
)
WalkStatement
(
node
SQLNode
)
(
bool
,
error
)
{
switch
node
:=
node
.
(
type
)
{
case
*
Select
:
_
=
Walk
(
nz
.
WalkSelect
,
node
)
// Don't continue
return
false
,
case
*
SQLVal
:
nz
.
convertSQLVal
(
node
)
case
*
ComparisonExpr
:
nz
.
convertComparison
(
node
)
}
return
true
,
}

// WalkStatement is the top level walk function.
// If it encounters a Select, it switches to a mode
// where variables are deduped.

WalkStatement is the top level walk function . If it encounters a Select it switches to a mode where variables are deduped .


func (nz *normalizer) WalkSelect(node SQLNode) (bool, error) {
	switch node := node.(type) {
	case *SQLVal:
		nz.convertSQLValDedup(node)
	case *ComparisonExpr:
		nz.convertComparison(node)
	}
	return true, nil
}

func ( nz * normalizer ) WalkSelect ( node SQLNode ) ( bool , error ) { switch node := node . ( type ) { case * SQLVal : nz . convertSQLValDedup ( node ) case * ComparisonExpr : nz . convertComparison ( node ) } return true , nil }

// WalkSelect normalizes the AST in Select mode.

WalkSelect normalizes the AST in Select mode .


func BindVariablesEqual(x, y map[string]*querypb.BindVariable) bool {
	return reflect.DeepEqual(&querypb.BoundQuery{BindVariables: x}, &querypb.BoundQuery{BindVariables: y})
}

func BindVariablesEqual ( x , y map [ string ] * querypb . BindVariable ) bool { return reflect . DeepEqual ( & querypb . BoundQuery { BindVariables : x } , & querypb . BoundQuery { BindVariables : y } ) }

// BindVariablesEqual compares two maps of bind variables.

BindVariablesEqual compares two maps of bind variables .