mirror of
https://github.com/rwinkhart/sys.git
synced 2026-09-05 16:47:27 -04:00
windows: implement the environment functions by wrapping syscall
Make windows implementation similar to unix. Updates golang/go#10803 (0intro will close the issue) Change-Id: I6f6a7b1c84f54b1ec92f0346a9998df34235c71a Reviewed-on: https://go-review.googlesource.com/10077 Reviewed-by: Rob Pike <r@golang.org>
This commit is contained in:
+5
-60
@@ -6,75 +6,20 @@
|
|||||||
|
|
||||||
package windows
|
package windows
|
||||||
|
|
||||||
import (
|
import "syscall"
|
||||||
"unicode/utf16"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Getenv(key string) (value string, found bool) {
|
func Getenv(key string) (value string, found bool) {
|
||||||
keyp, err := UTF16PtrFromString(key)
|
return syscall.Getenv(key)
|
||||||
if err != nil {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
n := uint32(100)
|
|
||||||
for {
|
|
||||||
b := make([]uint16, n)
|
|
||||||
n, err = GetEnvironmentVariable(keyp, &b[0], uint32(len(b)))
|
|
||||||
if n == 0 && err == ERROR_ENVVAR_NOT_FOUND {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
if n <= uint32(len(b)) {
|
|
||||||
return string(utf16.Decode(b[:n])), true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Setenv(key, value string) error {
|
func Setenv(key, value string) error {
|
||||||
v, err := UTF16PtrFromString(value)
|
return syscall.Setenv(key, value)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
keyp, err := UTF16PtrFromString(key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
e := SetEnvironmentVariable(keyp, v)
|
|
||||||
if e != nil {
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Clearenv() {
|
func Clearenv() {
|
||||||
for _, s := range Environ() {
|
syscall.Clearenv()
|
||||||
// Environment variables can begin with =
|
|
||||||
// so start looking for the separator = at j=1.
|
|
||||||
// http://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx
|
|
||||||
for j := 1; j < len(s); j++ {
|
|
||||||
if s[j] == '=' {
|
|
||||||
Setenv(s[0:j], "")
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Environ() []string {
|
func Environ() []string {
|
||||||
s, e := GetEnvironmentStrings()
|
return syscall.Environ()
|
||||||
if e != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
defer FreeEnvironmentStrings(s)
|
|
||||||
r := make([]string, 0, 50) // Empty with room to grow.
|
|
||||||
for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(s)); true; i++ {
|
|
||||||
if p[i] == 0 {
|
|
||||||
// empty string marks the end
|
|
||||||
if i <= from {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
r = append(r, string(utf16.Decode(p[from:i])))
|
|
||||||
from = i + 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return r
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user