// CreateSegment creates a new segment k in dir.
328333
func CreateSegment(dir string, k int) (*Segment, error) {
	f, err := os.OpenFile(SegmentName(dir, k), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		return nil, err
	}
	return &Segment{File: f, i: k, dir: dir}, nil
}
1103950
func persistBasicSegment(
	s Segment, file File, pos int64, options *StoreOptions) (rv SegmentLoc, err error) {

	seg, ok := s.(*segment)
	if !ok {
		return rv, fmt.Errorf("wrong segment type")
	}

	kvsBuf, err := Uint64SliceToByteSlice(seg.kvs)
	if err != nil {
		return rv, err
	}

	kvsPos := pageAlignCeil(pos)
	bufPos := pageAlignCeil(kvsPos + int64(len(kvsBuf)))

	ioCh := make(chan ioResult)

	go func() {
		kvsWritten, err := file.WriteAt(kvsBuf, kvsPos)
		ioCh <- ioResult{kind: "kvs", want: len(kvsBuf), got: kvsWritten, err: err}
	}()

	go func() {
		bufWritten, err := file.WriteAt(seg.buf, bufPos)
		ioCh <- ioResult{kind: "buf", want: len(seg.buf), got: bufWritten, err: err}
	}()

	resMap := map[string]ioResult{}
	for len(resMap) < 2 {
		res := <-ioCh
		if res.err != nil {
			return rv, res.err
		}
		if res.want != res.got {
			return rv, fmt.Errorf("store: persistSegment error writing,"+
				" res: %+v, err: %v", res, res.err)
		}
		resMap[res.kind] = res
	}

	close(ioCh)

	return SegmentLoc{
		Kind:       seg.Kind(),
		KvsOffset:  uint64(kvsPos),
		KvsBytes:   uint64(resMap["kvs"].got),
		BufOffset:  uint64(bufPos),
		BufBytes:   uint64(resMap["buf"].got),
		TotOpsSet:  seg.totOperationSet,
		TotOpsDel:  seg.totOperationDel,
		TotKeyByte: seg.totKeyByte,
		TotValByte: seg.totValByte,
	}, nil
}
1017324
func (p *SeriesPartition) createSegment() (*SeriesSegment, error) {
	// Close writer for active segment, if one exists.
	if segment := p.activeSegment(); segment != nil {
		if err := segment.CloseForWrite(); err != nil {
			return nil, err
		}
	}

	// Generate a new sequential segment identifier.
	var id uint16
	if len(p.segments) > 0 {
		id = p.segments[len(p.segments)-1].ID() + 1
	}
	filename := fmt.Sprintf("%04x", id)

	// Generate new empty segment.
	segment, err := CreateSeriesSegment(id, filepath.Join(p.path, filename))
	if err != nil {
		return nil, err
	}
	p.segments = append(p.segments, segment)

	// Allow segment to write.
	if err := segment.InitForWrite(); err != nil {
		return nil, err
	}
	p.tracker.SetSegments(uint64(len(p.segments)))
	p.tracker.SetDiskSize(p.diskSize()) // Disk size will change with new segment.
	return segment, nil
}
1268537
func (s *CmafPackage) SetSegmentPrefix(v string) *CmafPackage {
	s.SegmentPrefix = &v
	return s
}
1212570
func loadBasicSegment(sloc *SegmentLoc) (Segment, error) {
	var kvs []uint64
	var buf []byte
	var err error

	if sloc.KvsBytes > 0 {
		if sloc.KvsBytes > uint64(len(sloc.mref.buf)) {
			return nil, fmt.Errorf("store: load basic segment KvsOffset/KvsBytes too big,"+
				" len(mref.buf): %d, sloc: %+v", len(sloc.mref.buf), sloc)
		}

		kvsBytes := sloc.mref.buf[0:sloc.KvsBytes]
		kvs, err = ByteSliceToUint64Slice(kvsBytes)
		if err != nil {
			return nil, err
		}
	}

	if sloc.BufBytes > 0 {
		bufStart := sloc.BufOffset - sloc.KvsOffset
		if bufStart+sloc.BufBytes > uint64(len(sloc.mref.buf)) {
			return nil, fmt.Errorf("store: load basic segment BufOffset/BufBytes too big,"+
				" len(mref.buf): %d, sloc: %+v", len(sloc.mref.buf), sloc)
		}

		buf = sloc.mref.buf[bufStart : bufStart+sloc.BufBytes]
	}

	return &segment{
		kvs:             kvs,
		buf:             buf,
		totOperationSet: sloc.TotOpsSet,
		totOperationDel: sloc.TotOpsDel,
		totKeyByte:      sloc.TotKeyByte,
		totValByte:      sloc.TotValByte,
	}, nil
}
512499
func (b *Factory) CreateElement(recorded, local, remote map[string]interface{}) (apply.Element, error) {
	// Create an Item from the 3 values.  Use empty name for field
	visitor := &ElementBuildingVisitor{b.Resources}

	gvk, err := getCommonGroupVersionKind(recorded, local, remote)
	if err != nil {
		return nil, err
	}

	// Get the openapi object metadata
	s := visitor.resources.LookupResource(gvk)
	oapiKind, err := getKind(s)
	if err != nil {
		return nil, err
	}

	data := apply.NewRawElementData(recorded, local, remote)
	fieldName := ""
	item, err := visitor.getItem(oapiKind, fieldName, data)
	if err != nil {
		return nil, err
	}

	// Collate each field of the item into a combined Element
	return item.CreateElement(visitor)
}
536561
func (l *Client) GetSegment(id string) (Segment, error) {
	res := ApiResp{}
	data := Segment{}

	// make the request
	err := l.Get(parseLyticsURL(segmentEndpoint, map[string]string{"id": id}), nil, nil, &res, &data)
	if err != nil {
		return data, err
	}

	return data, nil
}
1045193
func NewSegment(name, traceID, spanID string, conn net.Conn) *Segment {
	return &Segment{
		Mutex:      &sync.Mutex{},
		Name:       name,
		TraceID:    traceID,
		ID:         spanID,
		StartTime:  now(),
		InProgress: true,
		conn:       conn,
	}
}
1362936
func (s *Segment) SetSegmentNumber(v int64) *Segment {
	s.SegmentNumber = &v
	return s
}
495040
func (w *Writer) CreatePart(
	contentId string,
	header textproto.MIMEHeader,
) (io.Writer, error) {

	var mediaType = DefaultMediaType

	if header == nil {
		header = make(textproto.MIMEHeader)
		header.Set("Content-Type", mediaType)
	} else if header.Get("Content-Type") != "" {
		mediaType = header.Get("Content-Type")
	}

	if contentId != "" {
		cid, err := formatContentId(contentId)
		if err != nil {
			return nil, err
		}
		header.Set("Content-ID", cid)
	}

	if w.firstPart == false {
		w.SetType(mediaType)
		w.rootMediaType = w.mediaType
		w.firstPart = true
	}
	return w.w.CreatePart(header)
}
754887
func (w *WAL) nextSegment() error {
	// Only flush the current page if it actually holds data.
	if w.page.alloc > 0 {
		if err := w.flushPage(true); err != nil {
			return err
		}
	}
	next, err := CreateSegment(w.dir, w.segment.Index()+1)
	if err != nil {
		return errors.Wrap(err, "create new segment file")
	}
	prev := w.segment
	if err := w.setSegment(next); err != nil {
		return err
	}

	// Don't block further writes by fsyncing the last segment.
	w.actorc <- func() {
		if err := w.fsync(prev); err != nil {
			level.Error(w.logger).Log("msg", "sync previous segment", "err", err)
		}
		if err := prev.Close(); err != nil {
			level.Error(w.logger).Log("msg", "close previous segment", "err", err)
		}
	}
	return nil
}
901675
func ContextSegment(ctx context.Context) *Segment {
	if s := ctx.Value(segKey); s != nil {
		return s.(*Segment)
	}
	return nil
}
923051
func versionSegments(segments string) []int {
	segments = strings.Trim(segments, "v")
	segments = strings.Split(segments, "-")[0]
	s := strings.Split(segments, ".")
	segmentSlice := make([]int, len(s))
	for i, v := range s {
		segmentSlice[i], _ = strconv.Atoi(v)
	}
	return segmentSlice
}
163517
func (s *M2tsSettings) SetSegmentationStyle(v string) *M2tsSettings {
	s.SegmentationStyle = &v
	return s
}
939750
func removeSegments(segments []Segment, toRemove []Segment) []Segment {
	rv := make([]Segment, 0, len(segments)-len(toRemove))
OUTER:
	for _, segment := range segments {
		for _, r := range toRemove {
			if segment == r {
				continue OUTER
			}
		}
		rv = append(rv, segment)
	}
	return rv
}
313990
func CreateSeriesSegment(id uint16, path string) (*SeriesSegment, error) {
	// Generate segment in temp location.
	f, err := os.Create(path + ".initializing")
	if err != nil {
		return nil, err
	}
	defer f.Close()

	// Write header to file and close.
	hdr := NewSeriesSegmentHeader()
	if _, err := hdr.WriteTo(f); err != nil {
		return nil, err
	} else if err := f.Truncate(int64(SeriesSegmentSize(id))); err != nil {
		return nil, err
	} else if err := f.Close(); err != nil {
		return nil, err
	}

	// Swap with target path.
	if err := os.Rename(f.Name(), path); err != nil {
		return nil, err
	}

	// Open segment at new location.
	segment := NewSeriesSegment(id, path)
	if err := segment.Open(); err != nil {
		return nil, err
	}
	return segment, nil
}
645651
func (w *SegmentWAL) createSegmentFile(name string) (*os.File, error) {
	f, err := os.Create(name)
	if err != nil {
		return nil, err
	}
	if err = fileutil.Preallocate(f, w.segmentSize, true); err != nil {
		return nil, err
	}
	// Write header metadata for new file.
	metab := make([]byte, 8)
	binary.BigEndian.PutUint32(metab[:4], WALMagic)
	metab[4] = WALFormatDefault

	if _, err := f.Write(metab); err != nil {
		return nil, err
	}
	return f, err
}