| Abhay Kumar | a2ae599 | 2025-11-10 14:02:24 +0000 | [diff] [blame^] | 1 | package common |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io" |
| 6 | "os" |
| 7 | "unsafe" |
| 8 | ) |
| 9 | |
| 10 | func LoadBucket(buf []byte) *InBucket { |
| 11 | return (*InBucket)(unsafe.Pointer(&buf[0])) |
| 12 | } |
| 13 | |
| 14 | func LoadPage(buf []byte) *Page { |
| 15 | return (*Page)(unsafe.Pointer(&buf[0])) |
| 16 | } |
| 17 | |
| 18 | func LoadPageMeta(buf []byte) *Meta { |
| 19 | return (*Meta)(unsafe.Pointer(&buf[PageHeaderSize])) |
| 20 | } |
| 21 | |
| 22 | func CopyFile(srcPath, dstPath string) error { |
| 23 | // Ensure source file exists. |
| 24 | _, err := os.Stat(srcPath) |
| 25 | if os.IsNotExist(err) { |
| 26 | return fmt.Errorf("source file %q not found", srcPath) |
| 27 | } else if err != nil { |
| 28 | return err |
| 29 | } |
| 30 | |
| 31 | // Ensure output file not exist. |
| 32 | _, err = os.Stat(dstPath) |
| 33 | if err == nil { |
| 34 | return fmt.Errorf("output file %q already exists", dstPath) |
| 35 | } else if !os.IsNotExist(err) { |
| 36 | return err |
| 37 | } |
| 38 | |
| 39 | srcDB, err := os.Open(srcPath) |
| 40 | if err != nil { |
| 41 | return fmt.Errorf("failed to open source file %q: %w", srcPath, err) |
| 42 | } |
| 43 | defer srcDB.Close() |
| 44 | dstDB, err := os.Create(dstPath) |
| 45 | if err != nil { |
| 46 | return fmt.Errorf("failed to create output file %q: %w", dstPath, err) |
| 47 | } |
| 48 | defer dstDB.Close() |
| 49 | written, err := io.Copy(dstDB, srcDB) |
| 50 | if err != nil { |
| 51 | return fmt.Errorf("failed to copy database file from %q to %q: %w", srcPath, dstPath, err) |
| 52 | } |
| 53 | |
| 54 | srcFi, err := srcDB.Stat() |
| 55 | if err != nil { |
| 56 | return fmt.Errorf("failed to get source file info %q: %w", srcPath, err) |
| 57 | } |
| 58 | initialSize := srcFi.Size() |
| 59 | if initialSize != written { |
| 60 | return fmt.Errorf("the byte copied (%q: %d) isn't equal to the initial db size (%q: %d)", dstPath, written, srcPath, initialSize) |
| 61 | } |
| 62 | |
| 63 | return nil |
| 64 | } |