Imported Upstream version 4.8.1
[platform/upstream/gcc48.git] / libgo / go / syscall / env_windows.go
1 // Copyright 2010 The Go Authors.  All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Windows environment variables.
6
7 package syscall
8
9 import (
10         "unicode/utf16"
11         "unsafe"
12 )
13
14 func Getenv(key string) (value string, found bool) {
15         keyp, err := UTF16PtrFromString(key)
16         if err != nil {
17                 return "", false
18         }
19         b := make([]uint16, 100)
20         n, e := GetEnvironmentVariable(keyp, &b[0], uint32(len(b)))
21         if n == 0 && e == ERROR_ENVVAR_NOT_FOUND {
22                 return "", false
23         }
24         if n > uint32(len(b)) {
25                 b = make([]uint16, n)
26                 n, e = GetEnvironmentVariable(keyp, &b[0], uint32(len(b)))
27                 if n > uint32(len(b)) {
28                         n = 0
29                 }
30         }
31         if n == 0 {
32                 return "", false
33         }
34         return string(utf16.Decode(b[0:n])), true
35 }
36
37 func Setenv(key, value string) error {
38         var v *uint16
39         var err error
40         if len(value) > 0 {
41                 v, err = UTF16PtrFromString(value)
42                 if err != nil {
43                         return err
44                 }
45         }
46         keyp, err := UTF16PtrFromString(key)
47         if err != nil {
48                 return err
49         }
50         e := SetEnvironmentVariable(keyp, v)
51         if e != nil {
52                 return e
53         }
54         return nil
55 }
56
57 func Clearenv() {
58         for _, s := range Environ() {
59                 // Environment variables can begin with =
60                 // so start looking for the separator = at j=1.
61                 // http://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx
62                 for j := 1; j < len(s); j++ {
63                         if s[j] == '=' {
64                                 Setenv(s[0:j], "")
65                                 break
66                         }
67                 }
68         }
69 }
70
71 func Environ() []string {
72         s, e := GetEnvironmentStrings()
73         if e != nil {
74                 return nil
75         }
76         defer FreeEnvironmentStrings(s)
77         r := make([]string, 0, 50) // Empty with room to grow.
78         for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(s)); true; i++ {
79                 if p[i] == 0 {
80                         // empty string marks the end
81                         if i <= from {
82                                 break
83                         }
84                         r = append(r, string(utf16.Decode(p[from:i])))
85                         from = i + 1
86                 }
87         }
88         return r
89 }