github.com/vchain-us/vcn@v0.9.11-0.20210921212052-a2484d23c0b3/pkg/bundle/descriptor.go (about)

     1  /*
     2   * Copyright (c) 2018-2020 vChain, Inc. All Rights Reserved.
     3   * This software is released under GPL3.
     4   * The full license information can be found under:
     5   * https://www.gnu.org/licenses/gpl-3.0.en.html
     6   *
     7   */
     8  
     9  package bundle
    10  
    11  import (
    12  	"io"
    13  	"sort"
    14  
    15  	// See https://github.com/opencontainers/go-digest#usage
    16  	_ "crypto/sha256"
    17  	_ "crypto/sha512"
    18  
    19  	digest "github.com/opencontainers/go-digest"
    20  )
    21  
    22  // Descriptor describes the disposition of targeted content.
    23  type Descriptor struct {
    24  	// Digest is the digest of the targeted content.
    25  	Digest digest.Digest `json:"digest"`
    26  
    27  	// Size specifies the size in bytes of the targeted content.
    28  	Size uint64 `json:"size"`
    29  
    30  	// Paths specifies the relative locations of the targeted content.
    31  	Paths []string `json:"paths"`
    32  }
    33  
    34  func (d *Descriptor) sortUnique() {
    35  	tmp := make(map[string]bool, len(d.Paths))
    36  	for _, p := range d.Paths {
    37  		tmp[p] = true
    38  	}
    39  	d.Paths = make([]string, len(tmp))
    40  	i := 0
    41  	for p := range tmp {
    42  		d.Paths[i] = p
    43  		i++
    44  	}
    45  	sort.Strings(d.Paths)
    46  }
    47  
    48  // NewDescriptor returns a new *Descriptor for the provided path and src.
    49  func NewDescriptor(path string, src io.Reader) (*Descriptor, error) {
    50  	digester := digest.SHA256.Digester()
    51  	size, err := io.Copy(digester.Hash(), src)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  
    56  	return &Descriptor{
    57  		Paths:  []string{path},
    58  		Digest: digester.Digest(),
    59  		Size:   uint64(size),
    60  	}, nil
    61  }