func newMetric(ctx context.Context, opts metricOptions) (*metric, error) {
	dir_buf := make([]byte, 0, len(opts.dir)+1+len(opts.name)+5)
	dir_buf = append(dir_buf, opts.dir...)
	if len(dir_buf) > 0 && dir_buf[len(dir_buf)-1] != '/' {
		dir_buf = append(dir_buf, '/')
	}
	dir_buf = metricToDir(dir_buf, opts.name)
	dir := string(dir_buf)
	dh, err := os.Open(dir)
	if os.IsNotExist(err) && !opts.ro {
		if err := os.MkdirAll(dir, 0755); err != nil {
			return nil, Error.Wrap(err)
		}
		dh, err = os.Open(dir)
	}
	if err != nil {
		return nil, Error.Wrap(err)
	}
	defer dh.Close()
	names, err := dh.Readdirnames(-1)
	if err != nil {
		return nil, Error.Wrap(err)
	}
	var fb filenameBuf
	interned := make(map[int]string)
	first, last := 0, 0
	first_set := false
	for _, name := range names {
		if !strings.HasSuffix(name, ".data") {
			continue
		}
		val, err := strconv.ParseInt(name[:len(name)-5], 10, 0)
		if err != nil {
			continue
		}
		iv := int(val)
		interned[iv] = fb.metricFilenameAt(dir, iv)
		if iv > last {
			last = iv
		}
		if iv < first || !first_set {
			first = iv
			first_set = true
		}
	}
	if !first_set {
		path := fb.metricFilenameAt(dir, 1)
		f, err := opts.fch.acquireFile(ctx, path, false)
		if err != nil {
			return nil, err
		}
		opts.fch.releaseFile(path, f)
		first, last = 1, 1
	}
	return &metric{
		opts:  opts,
		dir:   dir,
		first: first,
		last:  last,
		fb:       fb,
		interned: interned,
	}, nil
}
newMetric constructs a metric for some path. only one metric instance should
be in use at a time for a given directory.
package files
import (
	"context"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
	"github.com/vivint/rothko/external"
)
type metricOptions struct {
	fch  *fileCache
	dir  string
	name string
	max  int
	ro   bool  
}
type filenameBuf []byte
func (fb *filenameBuf) metricFilenameAt(dir string, index int) string {
	out := []byte(*fb)[:0]
	if initial := len(dir) + 12; cap(out) < initial {
		out = make([]byte, 0, initial)
	}
	out = append(out, dir...)
	if len(out) > 0 && out[len(out)-1] != '/' {
		out = append(out, '/')
	}
	out = strconv.AppendInt(out, int64(index), 10)
	out = append(out, ".data"...)
	*fb = filenameBuf(out)
	return string(out)
}
type metric struct {
	opts  metricOptions
	dir   string
	first int
	last  int
	fb       filenameBuf
	interned map[int]string  
}