github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/syndtr/goleveldb/leveldb/storage/file_storage_windows.go (about)

     1  // Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com>
     2  // All rights reserved.
     3  //
     4  // Use of this source code is governed by a BSD-style license that can be
     5  // found in the LICENSE file.
     6  
     7  package storage
     8  
     9  import (
    10  	"syscall"
    11  	"unsafe"
    12  )
    13  
    14  var (
    15  	modkernel32 = syscall.NewLazyDLL("kernel32.dll")
    16  
    17  	procMoveFileExW = modkernel32.NewProc("MoveFileExW")
    18  )
    19  
    20  const (
    21  	_MOVEFILE_REPLACE_EXISTING = 1
    22  )
    23  
    24  type windowsFileLock struct {
    25  	fd syscall.Handle
    26  }
    27  
    28  func (fl *windowsFileLock) release() error {
    29  	return syscall.Close(fl.fd)
    30  }
    31  
    32  func newFileLock(path string, readOnly bool) (fl fileLock, err error) {
    33  	pathp, err := syscall.UTF16PtrFromString(path)
    34  	if err != nil {
    35  		return
    36  	}
    37  	var access, shareMode uint32
    38  	if readOnly {
    39  		access = syscall.GENERIC_READ
    40  		shareMode = syscall.FILE_SHARE_READ
    41  	} else {
    42  		access = syscall.GENERIC_READ | syscall.GENERIC_WRITE
    43  	}
    44  	fd, err := syscall.CreateFile(pathp, access, shareMode, nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0)
    45  	if err == syscall.ERROR_FILE_NOT_FOUND {
    46  		fd, err = syscall.CreateFile(pathp, access, shareMode, nil, syscall.OPEN_ALWAYS, syscall.FILE_ATTRIBUTE_NORMAL, 0)
    47  	}
    48  	if err != nil {
    49  		return
    50  	}
    51  	fl = &windowsFileLock{fd: fd}
    52  	return
    53  }
    54  
    55  func moveFileEx(from *uint16, to *uint16, flags uint32) error {
    56  	r1, _, e1 := syscall.Syscall(procMoveFileExW.Addr(), 3, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), uintptr(flags))
    57  	if r1 == 0 {
    58  		if e1 != 0 {
    59  			return error(e1)
    60  		}
    61  		return syscall.EINVAL
    62  	}
    63  	return nil
    64  }
    65  
    66  func rename(oldpath, newpath string) error {
    67  	from, err := syscall.UTF16PtrFromString(oldpath)
    68  	if err != nil {
    69  		return err
    70  	}
    71  	to, err := syscall.UTF16PtrFromString(newpath)
    72  	if err != nil {
    73  		return err
    74  	}
    75  	return moveFileEx(from, to, _MOVEFILE_REPLACE_EXISTING)
    76  }
    77  
    78  func syncDir(name string) error { return nil }