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, fs.UpdateBody(coll), map[string]interface{}{"select": []string{"uuid"}})
136 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
141 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
142 fs.fileSystem.root.Lock()
143 defer fs.fileSystem.root.Unlock()
144 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix, newThrottle(concurrentWriters))
147 func (fs *collectionFileSystem) Size() int64 {
148 return fs.fileSystem.root.(*dirnode).TreeSize()
151 // filenodePtr is an offset into a file that is (usually) efficient to
152 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
154 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
155 // corresponds to file offset filenodePtr.off. Otherwise, it is
156 // necessary to reexamine len(filenode.segments[0]) etc. to find the
157 // correct segment and offset.
158 type filenodePtr struct {
165 // seek returns a ptr that is consistent with both startPtr.off and
166 // the current state of fn. The caller must already hold fn.RLock() or
169 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
174 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
176 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
177 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
180 // meaningless anyway
182 } else if ptr.off >= fn.fileinfo.size {
183 ptr.segmentIdx = len(fn.segments)
185 ptr.repacked = fn.repacked
187 } else if ptr.repacked == fn.repacked {
188 // segmentIdx and segmentOff accurately reflect
189 // ptr.off, but might have fallen off the end of a
191 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
198 ptr.repacked = fn.repacked
200 if ptr.off >= fn.fileinfo.size {
201 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
204 // Recompute segmentIdx and segmentOff. We have already
205 // established fn.fileinfo.size > ptr.off >= 0, so we don't
206 // have to deal with edge cases here.
208 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
209 // This would panic (index out of range) if
210 // fn.fileinfo.size were larger than
211 // sum(fn.segments[i].Len()) -- but that can't happen
212 // because we have ensured fn.fileinfo.size is always
214 segLen := int64(fn.segments[ptr.segmentIdx].Len())
215 if off+segLen > ptr.off {
216 ptr.segmentOff = int(ptr.off - off)
224 // filenode implements inode.
225 type filenode struct {
230 // number of times `segments` has changed in a
231 // way that might invalidate a filenodePtr
233 memsize int64 // bytes in memSegments
239 // caller must have lock
240 func (fn *filenode) appendSegment(e segment) {
241 fn.segments = append(fn.segments, e)
242 fn.fileinfo.size += int64(e.Len())
245 func (fn *filenode) SetParent(p inode, name string) {
249 fn.fileinfo.name = name
252 func (fn *filenode) Parent() inode {
258 func (fn *filenode) FS() FileSystem {
262 // Read reads file data from a single segment, starting at startPtr,
263 // into p. startPtr is assumed not to be up-to-date. Caller must have
265 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
266 ptr = fn.seek(startPtr)
268 err = ErrNegativeOffset
271 if ptr.segmentIdx >= len(fn.segments) {
275 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
279 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
282 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
290 func (fn *filenode) Size() int64 {
293 return fn.fileinfo.Size()
296 func (fn *filenode) FileInfo() os.FileInfo {
302 func (fn *filenode) Truncate(size int64) error {
305 return fn.truncate(size)
308 func (fn *filenode) truncate(size int64) error {
309 if size == fn.fileinfo.size {
313 if size < fn.fileinfo.size {
314 ptr := fn.seek(filenodePtr{off: size})
315 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
316 if seg, ok := fn.segments[i].(*memSegment); ok {
317 fn.memsize -= int64(seg.Len())
320 if ptr.segmentOff == 0 {
321 fn.segments = fn.segments[:ptr.segmentIdx]
323 fn.segments = fn.segments[:ptr.segmentIdx+1]
324 switch seg := fn.segments[ptr.segmentIdx].(type) {
326 seg.Truncate(ptr.segmentOff)
327 fn.memsize += int64(seg.Len())
329 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
332 fn.fileinfo.size = size
335 for size > fn.fileinfo.size {
336 grow := size - fn.fileinfo.size
339 if len(fn.segments) == 0 {
341 fn.segments = append(fn.segments, seg)
342 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
344 fn.segments = append(fn.segments, seg)
346 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
349 seg.Truncate(seg.Len() + int(grow))
350 fn.fileinfo.size += grow
356 // Write writes data from p to the file, starting at startPtr,
357 // extending the file size if necessary. Caller must have Lock.
358 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
359 if startPtr.off > fn.fileinfo.size {
360 if err = fn.truncate(startPtr.off); err != nil {
361 return 0, startPtr, err
364 ptr = fn.seek(startPtr)
366 err = ErrNegativeOffset
369 for len(p) > 0 && err == nil {
371 if len(cando) > maxBlockSize {
372 cando = cando[:maxBlockSize]
374 // Rearrange/grow fn.segments (and shrink cando if
375 // needed) such that cando can be copied to
376 // fn.segments[ptr.segmentIdx] at offset
378 cur := ptr.segmentIdx
379 prev := ptr.segmentIdx - 1
381 if cur < len(fn.segments) {
382 _, curWritable = fn.segments[cur].(*memSegment)
384 var prevAppendable bool
385 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
386 _, prevAppendable = fn.segments[prev].(*memSegment)
388 if ptr.segmentOff > 0 && !curWritable {
389 // Split a non-writable block.
390 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
391 // Truncate cur, and insert a new
394 fn.segments = append(fn.segments, nil)
395 copy(fn.segments[cur+1:], fn.segments[cur:])
397 // Split cur into two copies, truncate
398 // the one on the left, shift the one
399 // on the right, and insert a new
400 // segment between them.
401 fn.segments = append(fn.segments, nil, nil)
402 copy(fn.segments[cur+2:], fn.segments[cur:])
403 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
408 seg.Truncate(len(cando))
409 fn.memsize += int64(len(cando))
410 fn.segments[cur] = seg
411 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
416 } else if curWritable {
417 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
422 // Shrink cando if needed to fit in
424 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
425 cando = cando[:cangrow]
429 if cur == len(fn.segments) {
430 // ptr is at EOF, filesize is changing.
431 fn.fileinfo.size += int64(len(cando))
432 } else if el := fn.segments[cur].Len(); el <= len(cando) {
433 // cando is long enough that we won't
434 // need cur any more. shrink cando to
435 // be exactly as long as cur
436 // (otherwise we'd accidentally shift
437 // the effective position of all
438 // segments after cur).
440 copy(fn.segments[cur:], fn.segments[cur+1:])
441 fn.segments = fn.segments[:len(fn.segments)-1]
443 // shrink cur by the same #bytes we're growing prev
444 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
450 ptr.segmentOff = fn.segments[prev].Len()
451 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
452 fn.memsize += int64(len(cando))
456 // Insert a segment between prev and
457 // cur, and advance prev/cur.
458 fn.segments = append(fn.segments, nil)
459 if cur < len(fn.segments) {
460 copy(fn.segments[cur+1:], fn.segments[cur:])
464 // appending a new segment does
465 // not invalidate any ptrs
468 seg.Truncate(len(cando))
469 fn.memsize += int64(len(cando))
470 fn.segments[cur] = seg
476 // Finally we can copy bytes from cando to the current segment.
477 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
481 ptr.off += int64(len(cando))
482 ptr.segmentOff += len(cando)
483 if ptr.segmentOff >= maxBlockSize {
484 fn.pruneMemSegments()
486 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
491 fn.fileinfo.modTime = time.Now()
496 // Write some data out to disk to reduce memory use. Caller must have
498 func (fn *filenode) pruneMemSegments() {
499 // TODO: share code with (*dirnode)sync()
500 // TODO: pack/flush small blocks too, when fragmented
501 if fn.throttle == nil {
502 // TODO: share a throttle with filesystem
503 fn.throttle = newThrottle(writeAheadBlocks)
505 for idx, seg := range fn.segments {
506 seg, ok := seg.(*memSegment)
507 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
510 // Setting seg.flushing guarantees seg.buf will not be
511 // modified in place: WriteAt and Truncate will
512 // allocate a new buf instead, if necessary.
513 idx, buf := idx, seg.buf
514 done := make(chan struct{})
516 // If lots of background writes are already in
517 // progress, block here until one finishes, rather
518 // than pile up an unlimited number of buffered writes
519 // and network flush operations.
520 fn.throttle.Acquire()
523 locator, _, err := fn.FS().PutB(buf)
524 fn.throttle.Release()
527 if curbuf := seg.buf[:1]; &curbuf[0] != &buf[0] {
528 // A new seg.buf has been allocated.
533 // TODO: stall (or return errors from)
534 // subsequent writes until flushing
535 // starts to succeed.
538 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
539 // Segment has been dropped/moved/resized.
542 fn.memsize -= int64(len(buf))
543 fn.segments[idx] = storedSegment{
554 // Block until all pending pruneMemSegments work is finished. Caller
555 // must NOT have lock.
556 func (fn *filenode) waitPrune() {
557 var pending []<-chan struct{}
559 for _, seg := range fn.segments {
560 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
561 pending = append(pending, seg.flushing)
565 for _, p := range pending {
570 type dirnode struct {
571 fs *collectionFileSystem
575 func (dn *dirnode) FS() FileSystem {
579 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
580 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
581 gn := &getternode{Getter: func() ([]byte, error) {
584 coll.ManifestText, err = dn.fs.MarshalManifest(".")
588 data, err := json.Marshal(&coll)
590 data = append(data, '\n')
594 gn.SetParent(dn, name)
597 return dn.treenode.Child(name, replace)
600 type fnSegmentRef struct {
605 // commitBlock concatenates the data from the given filenode segments
606 // (which must be *memSegments), writes the data out to Keep as a
607 // single block, and replaces the filenodes' *memSegments with
608 // storedSegments that reference the relevant portions of the new
611 // Caller must have write lock.
612 func (dn *dirnode) commitBlock(ctx context.Context, throttle *throttle, refs []fnSegmentRef) error {
617 defer throttle.Release()
618 if err := ctx.Err(); err != nil {
621 block := make([]byte, 0, maxBlockSize)
622 for _, ref := range refs {
623 block = append(block, ref.fn.segments[ref.idx].(*memSegment).buf...)
625 locator, _, err := dn.fs.PutB(block)
630 for _, ref := range refs {
631 data := ref.fn.segments[ref.idx].(*memSegment).buf
632 ref.fn.segments[ref.idx] = storedSegment{
640 ref.fn.memsize -= int64(len(data))
645 // sync flushes in-memory data and remote block references (for the
646 // children with the given names, which must be children of dn) to
647 // local persistent storage. Caller must have write lock on dn and the
649 func (dn *dirnode) sync(ctx context.Context, throttle *throttle, names []string) error {
650 cg := newContextGroup(ctx)
653 goCommit := func(refs []fnSegmentRef) {
655 return dn.commitBlock(cg.Context(), throttle, refs)
659 var pending []fnSegmentRef
660 var pendingLen int = 0
661 localLocator := map[string]string{}
662 for _, name := range names {
663 fn, ok := dn.inodes[name].(*filenode)
667 for idx, seg := range fn.segments {
668 switch seg := seg.(type) {
670 loc, ok := localLocator[seg.locator]
673 loc, err = dn.fs.LocalLocator(seg.locator)
677 localLocator[seg.locator] = loc
680 fn.segments[idx] = seg
682 if seg.Len() > maxBlockSize/2 {
683 goCommit([]fnSegmentRef{{fn, idx}})
686 if pendingLen+seg.Len() > maxBlockSize {
691 pending = append(pending, fnSegmentRef{fn, idx})
692 pendingLen += seg.Len()
694 panic(fmt.Sprintf("can't sync segment type %T", seg))
702 // caller must have write lock.
703 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string, throttle *throttle) (string, error) {
704 cg := newContextGroup(ctx)
707 if len(dn.inodes) == 0 {
711 // Express the existence of an empty directory by
712 // adding an empty file named `\056`, which (unlike
713 // the more obvious spelling `.`) is accepted by the
714 // API's manifest validator.
715 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
718 names := make([]string, 0, len(dn.inodes))
719 for name := range dn.inodes {
720 names = append(names, name)
724 // Wait for children to finish any pending write operations
725 // before locking them.
726 for _, name := range names {
727 node := dn.inodes[name]
728 if fn, ok := node.(*filenode); ok {
733 var dirnames []string
734 var filenames []string
735 for _, name := range names {
736 node := dn.inodes[name]
739 switch node := node.(type) {
741 dirnames = append(dirnames, name)
743 filenames = append(filenames, name)
745 panic(fmt.Sprintf("can't marshal inode type %T", node))
749 subdirs := make([]string, len(dirnames))
751 for i, name := range dirnames {
754 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name, throttle)
762 type filepart struct {
768 var fileparts []filepart
770 if err := dn.sync(cg.Context(), throttle, names); err != nil {
773 for _, name := range filenames {
774 node := dn.inodes[name].(*filenode)
775 if len(node.segments) == 0 {
776 fileparts = append(fileparts, filepart{name: name})
779 for _, seg := range node.segments {
780 switch seg := seg.(type) {
782 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
783 streamLen -= int64(seg.size)
785 blocks = append(blocks, seg.locator)
789 offset: streamLen + int64(seg.offset),
790 length: int64(seg.length),
792 if prev := len(fileparts) - 1; prev >= 0 &&
793 fileparts[prev].name == name &&
794 fileparts[prev].offset+fileparts[prev].length == next.offset {
795 fileparts[prev].length += next.length
797 fileparts = append(fileparts, next)
799 streamLen += int64(seg.size)
801 // This can't happen: we
802 // haven't unlocked since
804 panic(fmt.Sprintf("can't marshal segment type %T", seg))
808 var filetokens []string
809 for _, s := range fileparts {
810 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
812 if len(filetokens) == 0 {
814 } else if len(blocks) == 0 {
815 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
817 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
821 return rootdir + strings.Join(subdirs, ""), err
824 func (dn *dirnode) loadManifest(txt string) error {
826 streams := strings.Split(txt, "\n")
827 if streams[len(streams)-1] != "" {
828 return fmt.Errorf("line %d: no trailing newline", len(streams))
830 streams = streams[:len(streams)-1]
831 segments := []storedSegment{}
832 for i, stream := range streams {
834 var anyFileTokens bool
837 segments = segments[:0]
838 for i, token := range strings.Split(stream, " ") {
840 dirname = manifestUnescape(token)
843 if !strings.Contains(token, ":") {
845 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
847 toks := strings.SplitN(token, "+", 3)
849 return fmt.Errorf("line %d: bad locator %q", lineno, token)
851 length, err := strconv.ParseInt(toks[1], 10, 32)
852 if err != nil || length < 0 {
853 return fmt.Errorf("line %d: bad locator %q", lineno, token)
855 segments = append(segments, storedSegment{
862 } else if len(segments) == 0 {
863 return fmt.Errorf("line %d: bad locator %q", lineno, token)
866 toks := strings.SplitN(token, ":", 3)
868 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
872 offset, err := strconv.ParseInt(toks[0], 10, 64)
873 if err != nil || offset < 0 {
874 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
876 length, err := strconv.ParseInt(toks[1], 10, 64)
877 if err != nil || length < 0 {
878 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
880 name := dirname + "/" + manifestUnescape(toks[2])
881 fnode, err := dn.createFileAndParents(name)
882 if fnode == nil && err == nil && length == 0 {
883 // Special case: an empty file used as
884 // a marker to preserve an otherwise
885 // empty directory in a manifest.
888 if err != nil || (fnode == nil && length != 0) {
889 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
891 // Map the stream offset/range coordinates to
892 // block/offset/range coordinates and add
893 // corresponding storedSegments to the filenode
895 // Can't continue where we left off.
896 // TODO: binary search instead of
897 // rewinding all the way (but this
898 // situation might be rare anyway)
901 for next := int64(0); segIdx < len(segments); segIdx++ {
902 seg := segments[segIdx]
903 next = pos + int64(seg.Len())
904 if next <= offset || seg.Len() == 0 {
908 if pos >= offset+length {
913 blkOff = int(offset - pos)
915 blkLen := seg.Len() - blkOff
916 if pos+int64(blkOff+blkLen) > offset+length {
917 blkLen = int(offset + length - pos - int64(blkOff))
919 fnode.appendSegment(storedSegment{
921 locator: seg.locator,
926 if next > offset+length {
932 if segIdx == len(segments) && pos < offset+length {
933 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
937 return fmt.Errorf("line %d: no file segments", lineno)
938 } else if len(segments) == 0 {
939 return fmt.Errorf("line %d: no locators", lineno)
940 } else if dirname == "" {
941 return fmt.Errorf("line %d: no stream name", lineno)
947 // only safe to call from loadManifest -- no locking.
949 // If path is a "parent directory exists" marker (the last path
950 // component is "."), the returned values are both nil.
951 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
953 names := strings.Split(path, "/")
954 basename := names[len(names)-1]
955 for _, name := range names[:len(names)-1] {
961 // can't be sure parent will be a *dirnode
962 return nil, ErrInvalidArgument
967 node, err = node.Child(name, func(child inode) (inode, error) {
969 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
973 child.SetParent(node, name)
975 } else if !child.IsDir() {
976 return child, ErrFileExists
987 } else if !permittedName(basename) {
988 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
991 _, err = node.Child(basename, func(child inode) (inode, error) {
992 switch child := child.(type) {
994 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
998 child.SetParent(node, basename)
999 fn = child.(*filenode)
1005 return child, ErrIsDirectory
1007 return child, ErrInvalidArgument
1013 func (dn *dirnode) TreeSize() (bytes int64) {
1016 for _, i := range dn.inodes {
1017 switch i := i.(type) {
1021 bytes += i.TreeSize()
1027 type segment interface {
1030 // Return a new segment with a subsection of the data from this
1031 // one. length<0 means length=Len()-off.
1032 Slice(off int, length int) segment
1035 type memSegment struct {
1037 // If flushing is not nil, then a) buf is being shared by a
1038 // pruneMemSegments goroutine, and must be copied on write;
1039 // and b) the flushing channel will close when the goroutine
1040 // finishes, whether it succeeds or not.
1041 flushing <-chan struct{}
1044 func (me *memSegment) Len() int {
1048 func (me *memSegment) Slice(off, length int) segment {
1050 length = len(me.buf) - off
1052 buf := make([]byte, length)
1053 copy(buf, me.buf[off:])
1054 return &memSegment{buf: buf}
1057 func (me *memSegment) Truncate(n int) {
1058 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1061 newsize = newsize << 2
1063 newbuf := make([]byte, n, newsize)
1064 copy(newbuf, me.buf)
1065 me.buf, me.flushing = newbuf, nil
1067 // reclaim existing capacity, and zero reclaimed part
1068 oldlen := len(me.buf)
1070 for i := oldlen; i < n; i++ {
1076 func (me *memSegment) WriteAt(p []byte, off int) {
1077 if off+len(p) > len(me.buf) {
1078 panic("overflowed segment")
1080 if me.flushing != nil {
1081 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1083 copy(me.buf[off:], p)
1086 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1087 if off > int64(me.Len()) {
1091 n = copy(p, me.buf[int(off):])
1098 type storedSegment struct {
1101 size int // size of stored block (also encoded in locator)
1102 offset int // position of segment within the stored block
1103 length int // bytes in this segment (offset + length <= size)
1106 func (se storedSegment) Len() int {
1110 func (se storedSegment) Slice(n, size int) segment {
1113 if size >= 0 && se.length > size {
1119 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1120 if off > int64(se.length) {
1123 maxlen := se.length - int(off)
1124 if len(p) > maxlen {
1126 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1132 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1135 func canonicalName(name string) string {
1136 name = path.Clean("/" + name)
1137 if name == "/" || name == "./" {
1139 } else if strings.HasPrefix(name, "/") {
1145 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1147 func manifestUnescapeFunc(seq string) string {
1151 i, err := strconv.ParseUint(seq[1:], 8, 8)
1153 // Invalid escape sequence: can't unescape.
1156 return string([]byte{byte(i)})
1159 func manifestUnescape(s string) string {
1160 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1163 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1165 func manifestEscapeFunc(seq string) string {
1166 return fmt.Sprintf("\\%03o", byte(seq[0]))
1169 func manifestEscape(s string) string {
1170 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)