From 978aa1f0c8786cf36d976b0e759bb9e37bb63e0c Mon Sep 17 00:00:00 2001
From: Matt Joiner <anacrolix@gmail.com>
Date: Sun, 29 Sep 2013 14:20:18 +1000
Subject: [PATCH] Don't rely on *os.File finalizer for close

---
 client.go | 34 ++++++++++++++++++++--------------
 1 file changed, 20 insertions(+), 14 deletions(-)

diff --git a/client.go b/client.go
index 51e518fe..a787fd9f 100644
--- a/client.go
+++ b/client.go
@@ -156,26 +156,32 @@ func mmapTorrentData(metaInfo *metainfo.MetaInfo, location string) (mms MMapSpan
 		if err != nil {
 			return
 		}
-		var fi os.FileInfo
-		fi, err = file.Stat()
-		if err != nil {
-			return
-		}
-		if fi.Size() < miFile.Length {
-			err = file.Truncate(miFile.Length)
+		func() {
+			defer file.Close()
+			var fi os.FileInfo
+			fi, err = file.Stat()
 			if err != nil {
 				return
 			}
-		}
-		var mMap gommap.MMap
-		mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
+			if fi.Size() < miFile.Length {
+				err = file.Truncate(miFile.Length)
+				if err != nil {
+					return
+				}
+			}
+			var mMap gommap.MMap
+			mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
+			if err != nil {
+				return
+			}
+			if int64(len(mMap)) != miFile.Length {
+				panic("mmap has wrong length")
+			}
+			mms = append(mms, MMap{mMap})
+		}()
 		if err != nil {
 			return
 		}
-		if int64(len(mMap)) != miFile.Length {
-			panic("mmap has wrong length")
-		}
-		mms = append(mms, MMap{mMap})
 	}
 	return
 }
-- 
2.51.0