From 11405bf65b1b68ffbbb49fe82ef314f424212651 Mon Sep 17 00:00:00 2001 From: whr819987540 <819987540@qq.com> Date: Thu, 4 May 2023 16:38:04 +0800 Subject: [PATCH] =?UTF-8?q?BuildFromMemory=E4=BB=8E=E5=86=85=E5=AD=98?= =?UTF-8?q?=E4=B8=AD=E7=9B=B4=E6=8E=A5=E7=94=9F=E6=88=90.torrent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- metainfo/info.go | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/metainfo/info.go b/metainfo/info.go index 3dd168dc..5f7e5b2e 100644 --- a/metainfo/info.go +++ b/metainfo/info.go @@ -94,6 +94,39 @@ func (info *Info) BuildFromFilePath(root string) (err error) { return } +// 根据导入的模型确定name +// 需要设置info.Length为byte数组的长度, 也是整个文件(内存)的长度 +func (info *Info) BuildFromMemory(byteData []byte, name string) (err error) { + // length + length := info.Length + if length == 0 { + info.Length = int64(len(byteData)) + length = info.Length + } + + // name + info.Name = name + + // files + // regard the memory block as single file + info.Files = append(info.Files, FileInfo{ + Path: []string{name}, + Length: length, + }) + + // piece length + if info.PieceLength == 0 { + info.PieceLength = ChoosePieceLength(info.TotalLength()) + } + + // pieces + err = info.GeneratePiecesFromMemory(byteData) + if err != nil { + err = fmt.Errorf("error generating pieces: %s", err) + } + return +} + // Concatenates all the files in the torrent into w. open is a function that // gets at the contents of the given file. func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error { @@ -127,6 +160,14 @@ func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) return } +func (info *Info) GeneratePiecesFromMemory(byteData []byte) (err error) { + if info.PieceLength == 0 { + return errors.New("piece length must be non-zero") + } + info.Pieces, err = GeneratePiecesFromMemory(byteData, info.PieceLength,int(info.TotalLength()),nil) + return +} + func (info *Info) TotalLength() (ret int64) { if info.IsDir() { for _, fi := range info.Files {