1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
23 maxBlockSize = 1 << 26
24 concurrentWriters = 4 // max goroutines writing to Keep during sync()
25 writeAheadBlocks = 1 // max background jobs flushing to Keep before blocking writes
28 // A CollectionFileSystem is a FileSystem that can be serialized as a
29 // manifest and stored as a collection.
30 type CollectionFileSystem interface {
33 // Flush all file data to Keep and return a snapshot of the
34 // filesystem suitable for saving as (Collection)ManifestText.
35 // Prefix (normally ".") is a top level directory, effectively
36 // prepended to all paths in the returned manifest.
37 MarshalManifest(prefix string) (string, error)
39 // Total data bytes in all files.
43 type collectionFileSystem struct {
48 // FileSystem returns a CollectionFileSystem for the collection.
49 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
51 if c.ModifiedAt == nil {
54 modTime = *c.ModifiedAt
56 fs := &collectionFileSystem{
58 fileSystem: fileSystem{
59 fsBackend: keepBackend{apiClient: client, keepClient: kc},
67 mode: os.ModeDir | 0755,
70 inodes: make(map[string]inode),
73 root.SetParent(root, ".")
74 if err := root.loadManifest(c.ManifestText); err != nil {
77 backdateTree(root, modTime)
82 func backdateTree(n inode, modTime time.Time) {
83 switch n := n.(type) {
85 n.fileinfo.modTime = modTime
87 n.fileinfo.modTime = modTime
88 for _, n := range n.inodes {
89 backdateTree(n, modTime)
94 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
95 if name == "" || name == "." || name == ".." {
96 return nil, ErrInvalidArgument
104 mode: perm | os.ModeDir,
107 inodes: make(map[string]inode),
115 mode: perm & ^os.ModeDir,
122 func (fs *collectionFileSystem) Sync() error {
126 txt, err := fs.MarshalManifest(".")
128 return fmt.Errorf("sync failed: %s", err)
134 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
135 "collection": map[string]string{
136 "manifest_text": coll.ManifestText,
138 "select": []string{"uuid"},
141 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
146 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
147 fs.fileSystem.root.Lock()
148 defer fs.fileSystem.root.Unlock()
149 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix, newThrottle(concurrentWriters))
152 func (fs *collectionFileSystem) Size() int64 {
153 return fs.fileSystem.root.(*dirnode).TreeSize()
156 // filenodePtr is an offset into a file that is (usually) efficient to
157 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
159 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
160 // corresponds to file offset filenodePtr.off. Otherwise, it is
161 // necessary to reexamine len(filenode.segments[0]) etc. to find the
162 // correct segment and offset.
163 type filenodePtr struct {
170 // seek returns a ptr that is consistent with both startPtr.off and
171 // the current state of fn. The caller must already hold fn.RLock() or
174 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
179 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
181 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
182 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
185 // meaningless anyway
187 } else if ptr.off >= fn.fileinfo.size {
188 ptr.segmentIdx = len(fn.segments)
190 ptr.repacked = fn.repacked
192 } else if ptr.repacked == fn.repacked {
193 // segmentIdx and segmentOff accurately reflect
194 // ptr.off, but might have fallen off the end of a
196 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
203 ptr.repacked = fn.repacked
205 if ptr.off >= fn.fileinfo.size {
206 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
209 // Recompute segmentIdx and segmentOff. We have already
210 // established fn.fileinfo.size > ptr.off >= 0, so we don't
211 // have to deal with edge cases here.
213 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
214 // This would panic (index out of range) if
215 // fn.fileinfo.size were larger than
216 // sum(fn.segments[i].Len()) -- but that can't happen
217 // because we have ensured fn.fileinfo.size is always
219 segLen := int64(fn.segments[ptr.segmentIdx].Len())
220 if off+segLen > ptr.off {
221 ptr.segmentOff = int(ptr.off - off)
229 // filenode implements inode.
230 type filenode struct {
235 // number of times `segments` has changed in a
236 // way that might invalidate a filenodePtr
238 memsize int64 // bytes in memSegments
244 // caller must have lock
245 func (fn *filenode) appendSegment(e segment) {
246 fn.segments = append(fn.segments, e)
247 fn.fileinfo.size += int64(e.Len())
250 func (fn *filenode) SetParent(p inode, name string) {
254 fn.fileinfo.name = name
257 func (fn *filenode) Parent() inode {
263 func (fn *filenode) FS() FileSystem {
267 // Read reads file data from a single segment, starting at startPtr,
268 // into p. startPtr is assumed not to be up-to-date. Caller must have
270 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
271 ptr = fn.seek(startPtr)
273 err = ErrNegativeOffset
276 if ptr.segmentIdx >= len(fn.segments) {
280 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
284 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
287 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
295 func (fn *filenode) Size() int64 {
298 return fn.fileinfo.Size()
301 func (fn *filenode) FileInfo() os.FileInfo {
307 func (fn *filenode) Truncate(size int64) error {
310 return fn.truncate(size)
313 func (fn *filenode) truncate(size int64) error {
314 if size == fn.fileinfo.size {
318 if size < fn.fileinfo.size {
319 ptr := fn.seek(filenodePtr{off: size})
320 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
321 if seg, ok := fn.segments[i].(*memSegment); ok {
322 fn.memsize -= int64(seg.Len())
325 if ptr.segmentOff == 0 {
326 fn.segments = fn.segments[:ptr.segmentIdx]
328 fn.segments = fn.segments[:ptr.segmentIdx+1]
329 switch seg := fn.segments[ptr.segmentIdx].(type) {
331 seg.Truncate(ptr.segmentOff)
332 fn.memsize += int64(seg.Len())
334 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
337 fn.fileinfo.size = size
340 for size > fn.fileinfo.size {
341 grow := size - fn.fileinfo.size
344 if len(fn.segments) == 0 {
346 fn.segments = append(fn.segments, seg)
347 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
349 fn.segments = append(fn.segments, seg)
351 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
354 seg.Truncate(seg.Len() + int(grow))
355 fn.fileinfo.size += grow
361 // Write writes data from p to the file, starting at startPtr,
362 // extending the file size if necessary. Caller must have Lock.
363 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
364 if startPtr.off > fn.fileinfo.size {
365 if err = fn.truncate(startPtr.off); err != nil {
366 return 0, startPtr, err
369 ptr = fn.seek(startPtr)
371 err = ErrNegativeOffset
374 for len(p) > 0 && err == nil {
376 if len(cando) > maxBlockSize {
377 cando = cando[:maxBlockSize]
379 // Rearrange/grow fn.segments (and shrink cando if
380 // needed) such that cando can be copied to
381 // fn.segments[ptr.segmentIdx] at offset
383 cur := ptr.segmentIdx
384 prev := ptr.segmentIdx - 1
386 if cur < len(fn.segments) {
387 _, curWritable = fn.segments[cur].(*memSegment)
389 var prevAppendable bool
390 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
391 _, prevAppendable = fn.segments[prev].(*memSegment)
393 if ptr.segmentOff > 0 && !curWritable {
394 // Split a non-writable block.
395 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
396 // Truncate cur, and insert a new
399 fn.segments = append(fn.segments, nil)
400 copy(fn.segments[cur+1:], fn.segments[cur:])
402 // Split cur into two copies, truncate
403 // the one on the left, shift the one
404 // on the right, and insert a new
405 // segment between them.
406 fn.segments = append(fn.segments, nil, nil)
407 copy(fn.segments[cur+2:], fn.segments[cur:])
408 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
413 seg.Truncate(len(cando))
414 fn.memsize += int64(len(cando))
415 fn.segments[cur] = seg
416 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
421 } else if curWritable {
422 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
427 // Shrink cando if needed to fit in
429 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
430 cando = cando[:cangrow]
434 if cur == len(fn.segments) {
435 // ptr is at EOF, filesize is changing.
436 fn.fileinfo.size += int64(len(cando))
437 } else if el := fn.segments[cur].Len(); el <= len(cando) {
438 // cando is long enough that we won't
439 // need cur any more. shrink cando to
440 // be exactly as long as cur
441 // (otherwise we'd accidentally shift
442 // the effective position of all
443 // segments after cur).
445 copy(fn.segments[cur:], fn.segments[cur+1:])
446 fn.segments = fn.segments[:len(fn.segments)-1]
448 // shrink cur by the same #bytes we're growing prev
449 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
455 ptr.segmentOff = fn.segments[prev].Len()
456 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
457 fn.memsize += int64(len(cando))
461 // Insert a segment between prev and
462 // cur, and advance prev/cur.
463 fn.segments = append(fn.segments, nil)
464 if cur < len(fn.segments) {
465 copy(fn.segments[cur+1:], fn.segments[cur:])
469 // appending a new segment does
470 // not invalidate any ptrs
473 seg.Truncate(len(cando))
474 fn.memsize += int64(len(cando))
475 fn.segments[cur] = seg
481 // Finally we can copy bytes from cando to the current segment.
482 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
486 ptr.off += int64(len(cando))
487 ptr.segmentOff += len(cando)
488 if ptr.segmentOff >= maxBlockSize {
489 fn.pruneMemSegments()
491 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
496 fn.fileinfo.modTime = time.Now()
501 // Write some data out to disk to reduce memory use. Caller must have
503 func (fn *filenode) pruneMemSegments() {
504 // TODO: share code with (*dirnode)sync()
505 // TODO: pack/flush small blocks too, when fragmented
506 if fn.throttle == nil {
507 // TODO: share a throttle with filesystem
508 fn.throttle = newThrottle(writeAheadBlocks)
510 for idx, seg := range fn.segments {
511 seg, ok := seg.(*memSegment)
512 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
515 // Setting seg.flushing guarantees seg.buf will not be
516 // modified in place: WriteAt and Truncate will
517 // allocate a new buf instead, if necessary.
518 idx, buf := idx, seg.buf
519 done := make(chan struct{})
521 // If lots of background writes are already in
522 // progress, block here until one finishes, rather
523 // than pile up an unlimited number of buffered writes
524 // and network flush operations.
525 fn.throttle.Acquire()
528 locator, _, err := fn.FS().PutB(buf)
529 fn.throttle.Release()
532 if curbuf := seg.buf[:1]; &curbuf[0] != &buf[0] {
533 // A new seg.buf has been allocated.
538 // TODO: stall (or return errors from)
539 // subsequent writes until flushing
540 // starts to succeed.
543 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
544 // Segment has been dropped/moved/resized.
547 fn.memsize -= int64(len(buf))
548 fn.segments[idx] = storedSegment{
559 // Block until all pending pruneMemSegments work is finished. Caller
560 // must NOT have lock.
561 func (fn *filenode) waitPrune() {
562 var pending []<-chan struct{}
564 for _, seg := range fn.segments {
565 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
566 pending = append(pending, seg.flushing)
570 for _, p := range pending {
575 type dirnode struct {
576 fs *collectionFileSystem
580 func (dn *dirnode) FS() FileSystem {
584 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
585 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
586 gn := &getternode{Getter: func() ([]byte, error) {
589 coll.ManifestText, err = dn.fs.MarshalManifest(".")
593 data, err := json.Marshal(&coll)
595 data = append(data, '\n')
599 gn.SetParent(dn, name)
602 return dn.treenode.Child(name, replace)
605 type fnSegmentRef struct {
610 // commitBlock concatenates the data from the given filenode segments
611 // (which must be *memSegments), writes the data out to Keep as a
612 // single block, and replaces the filenodes' *memSegments with
613 // storedSegments that reference the relevant portions of the new
616 // Caller must have write lock.
617 func (dn *dirnode) commitBlock(ctx context.Context, throttle *throttle, refs []fnSegmentRef) error {
622 defer throttle.Release()
623 if err := ctx.Err(); err != nil {
626 block := make([]byte, 0, maxBlockSize)
627 for _, ref := range refs {
628 block = append(block, ref.fn.segments[ref.idx].(*memSegment).buf...)
630 locator, _, err := dn.fs.PutB(block)
635 for _, ref := range refs {
636 data := ref.fn.segments[ref.idx].(*memSegment).buf
637 ref.fn.segments[ref.idx] = storedSegment{
645 ref.fn.memsize -= int64(len(data))
650 // sync flushes in-memory data and remote block references (for the
651 // children with the given names, which must be children of dn) to
652 // local persistent storage. Caller must have write lock on dn and the
654 func (dn *dirnode) sync(ctx context.Context, throttle *throttle, names []string) error {
655 cg := newContextGroup(ctx)
658 goCommit := func(refs []fnSegmentRef) {
660 return dn.commitBlock(cg.Context(), throttle, refs)
664 var pending []fnSegmentRef
665 var pendingLen int = 0
666 localLocator := map[string]string{}
667 for _, name := range names {
668 fn, ok := dn.inodes[name].(*filenode)
672 for idx, seg := range fn.segments {
673 switch seg := seg.(type) {
675 loc, ok := localLocator[seg.locator]
678 loc, err = dn.fs.LocalLocator(seg.locator)
682 localLocator[seg.locator] = loc
685 fn.segments[idx] = seg
687 if seg.Len() > maxBlockSize/2 {
688 goCommit([]fnSegmentRef{{fn, idx}})
691 if pendingLen+seg.Len() > maxBlockSize {
696 pending = append(pending, fnSegmentRef{fn, idx})
697 pendingLen += seg.Len()
699 panic(fmt.Sprintf("can't sync segment type %T", seg))
707 // caller must have write lock.
708 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string, throttle *throttle) (string, error) {
709 cg := newContextGroup(ctx)
712 if len(dn.inodes) == 0 {
716 // Express the existence of an empty directory by
717 // adding an empty file named `\056`, which (unlike
718 // the more obvious spelling `.`) is accepted by the
719 // API's manifest validator.
720 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
723 names := make([]string, 0, len(dn.inodes))
724 for name := range dn.inodes {
725 names = append(names, name)
729 // Wait for children to finish any pending write operations
730 // before locking them.
731 for _, name := range names {
732 node := dn.inodes[name]
733 if fn, ok := node.(*filenode); ok {
738 var dirnames []string
739 var filenames []string
740 for _, name := range names {
741 node := dn.inodes[name]
744 switch node := node.(type) {
746 dirnames = append(dirnames, name)
748 filenames = append(filenames, name)
750 panic(fmt.Sprintf("can't marshal inode type %T", node))
754 subdirs := make([]string, len(dirnames))
756 for i, name := range dirnames {
759 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name, throttle)
767 type filepart struct {
773 var fileparts []filepart
775 if err := dn.sync(cg.Context(), throttle, names); err != nil {
778 for _, name := range filenames {
779 node := dn.inodes[name].(*filenode)
780 if len(node.segments) == 0 {
781 fileparts = append(fileparts, filepart{name: name})
784 for _, seg := range node.segments {
785 switch seg := seg.(type) {
787 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
788 streamLen -= int64(seg.size)
790 blocks = append(blocks, seg.locator)
794 offset: streamLen + int64(seg.offset),
795 length: int64(seg.length),
797 if prev := len(fileparts) - 1; prev >= 0 &&
798 fileparts[prev].name == name &&
799 fileparts[prev].offset+fileparts[prev].length == next.offset {
800 fileparts[prev].length += next.length
802 fileparts = append(fileparts, next)
804 streamLen += int64(seg.size)
806 // This can't happen: we
807 // haven't unlocked since
809 panic(fmt.Sprintf("can't marshal segment type %T", seg))
813 var filetokens []string
814 for _, s := range fileparts {
815 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
817 if len(filetokens) == 0 {
819 } else if len(blocks) == 0 {
820 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
822 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
826 return rootdir + strings.Join(subdirs, ""), err
829 func (dn *dirnode) loadManifest(txt string) error {
831 streams := strings.Split(txt, "\n")
832 if streams[len(streams)-1] != "" {
833 return fmt.Errorf("line %d: no trailing newline", len(streams))
835 streams = streams[:len(streams)-1]
836 segments := []storedSegment{}
837 for i, stream := range streams {
839 var anyFileTokens bool
842 segments = segments[:0]
843 for i, token := range strings.Split(stream, " ") {
845 dirname = manifestUnescape(token)
848 if !strings.Contains(token, ":") {
850 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
852 toks := strings.SplitN(token, "+", 3)
854 return fmt.Errorf("line %d: bad locator %q", lineno, token)
856 length, err := strconv.ParseInt(toks[1], 10, 32)
857 if err != nil || length < 0 {
858 return fmt.Errorf("line %d: bad locator %q", lineno, token)
860 segments = append(segments, storedSegment{
867 } else if len(segments) == 0 {
868 return fmt.Errorf("line %d: bad locator %q", lineno, token)
871 toks := strings.SplitN(token, ":", 3)
873 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
877 offset, err := strconv.ParseInt(toks[0], 10, 64)
878 if err != nil || offset < 0 {
879 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
881 length, err := strconv.ParseInt(toks[1], 10, 64)
882 if err != nil || length < 0 {
883 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
885 name := dirname + "/" + manifestUnescape(toks[2])
886 fnode, err := dn.createFileAndParents(name)
887 if fnode == nil && err == nil && length == 0 {
888 // Special case: an empty file used as
889 // a marker to preserve an otherwise
890 // empty directory in a manifest.
893 if err != nil || (fnode == nil && length != 0) {
894 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
896 // Map the stream offset/range coordinates to
897 // block/offset/range coordinates and add
898 // corresponding storedSegments to the filenode
900 // Can't continue where we left off.
901 // TODO: binary search instead of
902 // rewinding all the way (but this
903 // situation might be rare anyway)
906 for next := int64(0); segIdx < len(segments); segIdx++ {
907 seg := segments[segIdx]
908 next = pos + int64(seg.Len())
909 if next <= offset || seg.Len() == 0 {
913 if pos >= offset+length {
918 blkOff = int(offset - pos)
920 blkLen := seg.Len() - blkOff
921 if pos+int64(blkOff+blkLen) > offset+length {
922 blkLen = int(offset + length - pos - int64(blkOff))
924 fnode.appendSegment(storedSegment{
926 locator: seg.locator,
931 if next > offset+length {
937 if segIdx == len(segments) && pos < offset+length {
938 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
942 return fmt.Errorf("line %d: no file segments", lineno)
943 } else if len(segments) == 0 {
944 return fmt.Errorf("line %d: no locators", lineno)
945 } else if dirname == "" {
946 return fmt.Errorf("line %d: no stream name", lineno)
952 // only safe to call from loadManifest -- no locking.
954 // If path is a "parent directory exists" marker (the last path
955 // component is "."), the returned values are both nil.
956 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
958 names := strings.Split(path, "/")
959 basename := names[len(names)-1]
960 for _, name := range names[:len(names)-1] {
966 // can't be sure parent will be a *dirnode
967 return nil, ErrInvalidArgument
972 node, err = node.Child(name, func(child inode) (inode, error) {
974 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
978 child.SetParent(node, name)
980 } else if !child.IsDir() {
981 return child, ErrFileExists
992 } else if !permittedName(basename) {
993 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
996 _, err = node.Child(basename, func(child inode) (inode, error) {
997 switch child := child.(type) {
999 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
1003 child.SetParent(node, basename)
1004 fn = child.(*filenode)
1010 return child, ErrIsDirectory
1012 return child, ErrInvalidArgument
1018 func (dn *dirnode) TreeSize() (bytes int64) {
1021 for _, i := range dn.inodes {
1022 switch i := i.(type) {
1026 bytes += i.TreeSize()
1032 type segment interface {
1035 // Return a new segment with a subsection of the data from this
1036 // one. length<0 means length=Len()-off.
1037 Slice(off int, length int) segment
1040 type memSegment struct {
1042 // If flushing is not nil, then a) buf is being shared by a
1043 // pruneMemSegments goroutine, and must be copied on write;
1044 // and b) the flushing channel will close when the goroutine
1045 // finishes, whether it succeeds or not.
1046 flushing <-chan struct{}
1049 func (me *memSegment) Len() int {
1053 func (me *memSegment) Slice(off, length int) segment {
1055 length = len(me.buf) - off
1057 buf := make([]byte, length)
1058 copy(buf, me.buf[off:])
1059 return &memSegment{buf: buf}
1062 func (me *memSegment) Truncate(n int) {
1063 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1066 newsize = newsize << 2
1068 newbuf := make([]byte, n, newsize)
1069 copy(newbuf, me.buf)
1070 me.buf, me.flushing = newbuf, nil
1072 // reclaim existing capacity, and zero reclaimed part
1073 oldlen := len(me.buf)
1075 for i := oldlen; i < n; i++ {
1081 func (me *memSegment) WriteAt(p []byte, off int) {
1082 if off+len(p) > len(me.buf) {
1083 panic("overflowed segment")
1085 if me.flushing != nil {
1086 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1088 copy(me.buf[off:], p)
1091 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1092 if off > int64(me.Len()) {
1096 n = copy(p, me.buf[int(off):])
1103 type storedSegment struct {
1106 size int // size of stored block (also encoded in locator)
1107 offset int // position of segment within the stored block
1108 length int // bytes in this segment (offset + length <= size)
1111 func (se storedSegment) Len() int {
1115 func (se storedSegment) Slice(n, size int) segment {
1118 if size >= 0 && se.length > size {
1124 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1125 if off > int64(se.length) {
1128 maxlen := se.length - int(off)
1129 if len(p) > maxlen {
1131 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1137 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1140 func canonicalName(name string) string {
1141 name = path.Clean("/" + name)
1142 if name == "/" || name == "./" {
1144 } else if strings.HasPrefix(name, "/") {
1150 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1152 func manifestUnescapeFunc(seq string) string {
1156 i, err := strconv.ParseUint(seq[1:], 8, 8)
1158 // Invalid escape sequence: can't unescape.
1161 return string([]byte{byte(i)})
1164 func manifestUnescape(s string) string {
1165 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1168 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1170 func manifestEscapeFunc(seq string) string {
1171 return fmt.Sprintf("\\%03o", byte(seq[0]))
1174 func manifestEscape(s string) string {
1175 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)