<commit_before>// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package mime

import (
	"syscall"
	"unsafe"
)

func initMime() {
	var root syscall.Handle
	rootpathp, _ := syscall.UTF16PtrFromString(`\`)
	if syscall.RegOpenKeyEx(syscall.HKEY_CLASSES_ROOT, rootpathp,
		0, syscall.KEY_READ, &root) != nil {
		return
	}
	defer syscall.RegCloseKey(root)
	var count uint32
	if syscall.RegQueryInfoKey(root, nil, nil, nil, &count, nil, nil, nil, nil, nil, nil, nil) != nil {
		return
	}
	var buf [1 << 10]uint16
	for i := uint32(0); i < count; i++ {
		n := uint32(len(buf))
		if syscall.RegEnumKeyEx(root, i, &buf[0], &n, nil, nil, nil, nil) != nil {
			continue
		}
		ext := syscall.UTF16ToString(buf[:])
		if len(ext) < 2 || ext[0] != '.' { // looking for extensions only
			continue
		}
		var h syscall.Handle
		extpathp, _ := syscall.UTF16PtrFromString(`\` + ext)
		if syscall.RegOpenKeyEx(
			syscall.HKEY_CLASSES_ROOT, extpathp,
			0, syscall.KEY_READ, &h) != nil {
			continue
		}
		var typ uint32
		n = uint32(len(buf) * 2) // api expects array of bytes, not uint16
		contenttypep, _ := syscall.UTF16PtrFromString("Content Type")
		if syscall.RegQueryValueEx(
			h, contenttypep,
			nil, &typ, (*byte)(unsafe.Pointer(&buf[0])), &n) != nil {
			syscall.RegCloseKey(h)
			continue
		}
		syscall.RegCloseKey(h)
		if typ != syscall.REG_SZ { // null terminated strings only
			continue
		}
		mimeType := syscall.UTF16ToString(buf[:])
		setExtensionType(ext, mimeType)
	}
}

func initMimeForTests() map[string]string {
	return map[string]string{
		".bmp": "image/bmp",
		".png": "image/png",
	}
}
<commit_msg>mime: use .wav instead of .bmp during windows tests<commit_after>// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package mime

import (
	"syscall"
	"unsafe"
)

func initMime() {
	var root syscall.Handle
	rootpathp, _ := syscall.UTF16PtrFromString(`\`)
	if syscall.RegOpenKeyEx(syscall.HKEY_CLASSES_ROOT, rootpathp,
		0, syscall.KEY_READ, &root) != nil {
		return
	}
	defer syscall.RegCloseKey(root)
	var count uint32
	if syscall.RegQueryInfoKey(root, nil, nil, nil, &count, nil, nil, nil, nil, nil, nil, nil) != nil {
		return
	}
	var buf [1 << 10]uint16
	for i := uint32(0); i < count; i++ {
		n := uint32(len(buf))
		if syscall.RegEnumKeyEx(root, i, &buf[0], &n, nil, nil, nil, nil) != nil {
			continue
		}
		ext := syscall.UTF16ToString(buf[:])
		if len(ext) < 2 || ext[0] != '.' { // looking for extensions only
			continue
		}
		var h syscall.Handle
		extpathp, _ := syscall.UTF16PtrFromString(`\` + ext)
		if syscall.RegOpenKeyEx(
			syscall.HKEY_CLASSES_ROOT, extpathp,
			0, syscall.KEY_READ, &h) != nil {
			continue
		}
		var typ uint32
		n = uint32(len(buf) * 2) // api expects array of bytes, not uint16
		contenttypep, _ := syscall.UTF16PtrFromString("Content Type")
		if syscall.RegQueryValueEx(
			h, contenttypep,
			nil, &typ, (*byte)(unsafe.Pointer(&buf[0])), &n) != nil {
			syscall.RegCloseKey(h)
			continue
		}
		syscall.RegCloseKey(h)
		if typ != syscall.REG_SZ { // null terminated strings only
			continue
		}
		mimeType := syscall.UTF16ToString(buf[:])
		setExtensionType(ext, mimeType)
	}
}

func initMimeForTests() map[string]string {
	return map[string]string{
		".wav": "audio/wav",
		".png": "image/png",
	}
}
<|endoftext|>


<commit_before>// Copyright 2011 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Plan 9 environment variables.

package syscall

import "errors"

func Getenv(key string) (value string, found bool) {
	if len(key) == 0 {
		return "", EINVAL
	}
	f, e := Open("/env/" + key)
	if e != nil {
		return "", ENOENV
	}
	defer f.Close()

	l, _ := f.Seek(0, 2)
	f.Seek(0, 0)
	buf := make([]byte, l)
	n, e := f.Read(buf)
	if e != nil {
		return "", ENOENV
	}

	if n > 0 && buf[n-1] == 0 {
		buf = buf[:n-1]
	}
	return string(buf), nil
}

func Setenv(key, value string) error {
	if len(key) == 0 {
		return EINVAL
	}

	f, e := Create("/env/" + key)
	if e != nil {
		return e
	}
	defer f.Close()

	_, e = f.Write([]byte(value))
	return nil
}

func Clearenv() {
	RawSyscall(SYS_RFORK, RFCENVG, 0, 0)
}

func Environ() []string {
	env := make([]string, 0, 100)

	f, e := Open("/env")
	if e != nil {
		panic(e)
	}
	defer f.Close()

	names, e := f.Readdirnames(-1)
	if e != nil {
		panic(e)
	}

	for _, k := range names {
		if v, ok := Getenv(k); ok {
			env = append(env, k+"="+v)
		}
	}
	return env[0:len(env)]
}
<commit_msg>syscall: fix env routines for Plan 9<commit_after>// Copyright 2011 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Plan 9 environment variables.

package syscall

import "errors"

func Getenv(key string) (value string, found bool) {
	if len(key) == 0 {
		return "", false
	}
	f, e := Open("/env/"+key, O_RDONLY)
	if e != nil {
		return "", false
	}
	defer Close(f)

	l, _ := Seek(f, 0, 2)
	Seek(f, 0, 0)
	buf := make([]byte, l)
	n, e := Read(f, buf)
	if e != nil {
		return "", false
	}

	if n > 0 && buf[n-1] == 0 {
		buf = buf[:n-1]
	}
	return string(buf), true
}

func Setenv(key, value string) error {
	if len(key) == 0 {
		return errors.New("bad arg in system call")
	}

	f, e := Create("/env/"+key, O_RDWR, 0666)
	if e != nil {
		return e
	}
	defer Close(f)

	_, e = Write(f, []byte(value))
	return nil
}

func Clearenv() {
	RawSyscall(SYS_RFORK, RFCENVG, 0, 0)
}

func Environ() []string {
	env := make([]string, 0, 100)

	f, e := Open("/env", O_RDONLY)
	if e != nil {
		panic(e)
	}
	defer Close(f)

	names, e := readdirnames(f)
	if e != nil {
		panic(e)
	}

	for _, k := range names {
		if v, ok := Getenv(k); ok {
			env = append(env, k+"="+v)
		}
	}
	return env[0:len(env)]
}
<|endoftext|>


<commit_before>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package template implements data-driven templates for generating textual output.

To generate HTML output, see package html/template, which has the same interface
as this package but automatically secures HTML output against certain attacks.

Templates are executed by applying them to a data structure. Annotations in the
template refer to elements of the data structure (typically a field of a struct
or a key in a map) to control execution and derive values to be displayed.
Execution of the template walks the structure and sets the cursor, represented
by a period '.' and called "dot", to the value at the current location in the
structure as execution proceeds.

The input text for a template is UTF-8-encoded text in any format.
"Actions"--data evaluations or control structures--are delimited by
"{{" and "}}"; all text outside actions is copied to the output unchanged.
Actions may not span newlines, although comments can.

Once constructed, a template may be executed safely in parallel.

Here is a trivial example that prints "17 items are made of wool".

	type Inventory struct {
		Material string
		Count    uint
	}
	sweaters := Inventory{"wool", 17}
	tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
	if err != nil { panic(err) }
	err = tmpl.Execute(os.Stdout, sweaters)
	if err != nil { panic(err) }

More intricate examples appear below.

Actions

Here is the list of actions. "Arguments" and "pipelines" are evaluations of
data, defined in detail below.

*/
//	{{/* a comment */}}
//		A comment; discarded. May contain newlines.
//		Comments do not nest.
/*

	{{pipeline}}
		The default textual representation of the value of the pipeline
		is copied to the output.

	{{if pipeline}} T1 {{end}}
		If the value of the pipeline is empty, no output is generated;
		otherwise, T1 is executed.  The empty values are false, 0, any
		nil pointer or interface value, and any array, slice, map, or
		string of length zero.
		Dot is unaffected.

	{{if pipeline}} T1 {{else}} T0 {{end}}
		If the value of the pipeline is empty, T0 is executed;
		otherwise, T1 is executed.  Dot is unaffected.

	{{range pipeline}} T1 {{end}}
		The value of the pipeline must be an array, slice, or map. If
		the value of the pipeline has length zero, nothing is output;
		otherwise, dot is set to the successive elements of the array,
		slice, or map and T1 is executed. If the value is a map and the
		keys are of basic type with a defined order ("comparable"), the
		elements will be visited in sorted key order.

	{{range pipeline}} T1 {{else}} T0 {{end}}
		The value of the pipeline must be an array, slice, or map. If
		the value of the pipeline has length zero, dot is unaffected and
		T0 is executed; otherwise, dot is set to the successive elements
		of the array, slice, or map and T1 is executed.

	{{template "name"}}
		The template with the specified name is executed with nil data.

	{{template "name" pipeline}}
		The template with the specified name is executed with dot set
		to the value of the pipeline.

	{{with pipeline}} T1 {{end}}
		If the value of the pipeline is empty, no output is generated;
		otherwise, dot is set to the value of the pipeline and T1 is
		executed.

	{{with pipeline}} T1 {{else}} T0 {{end}}
		If the value of the pipeline is empty, dot is unaffected and T0
		is executed; otherwise, dot is set to the value of the pipeline
		and T1 is executed.

Arguments

An argument is a simple value, denoted by one of the following.

	- A boolean, string, character, integer, floating-point, imaginary
	  or complex constant in Go syntax. These behave like Go's untyped
	  constants, although raw strings may not span newlines.
	- The keyword nil, representing an untyped Go nil.
	- The character '.' (period):
		.
	  The result is the value of dot.
	- A variable name, which is a (possibly empty) alphanumeric string
	  preceded by a dollar sign, such as
		$piOver2
	  or
		$
	  The result is the value of the variable.
	  Variables are described below.
	- The name of a field of the data, which must be a struct, preceded
	  by a period, such as
		.Field
	  The result is the value of the field. Field invocations may be
	  chained:
	    .Field1.Field2
	  Fields can also be evaluated on variables, including chaining:
	    $x.Field1.Field2
	- The name of a key of the data, which must be a map, preceded
	  by a period, such as
		.Key
	  The result is the map element value indexed by the key.
	  Key invocations may be chained and combined with fields to any
	  depth:
	    .Field1.Key1.Field2.Key2
	  Although the key must be an alphanumeric identifier, unlike with
	  field names they do not need to start with an upper case letter.
	  Keys can also be evaluated on variables, including chaining:
	    $x.key1.key2
	- The name of a niladic method of the data, preceded by a period,
	  such as
		.Method
	  The result is the value of invoking the method with dot as the
	  receiver, dot.Method(). Such a method must have one return value (of
	  any type) or two return values, the second of which is an error.
	  If it has two and the returned error is non-nil, execution terminates
	  and an error is returned to the caller as the value of Execute.
	  Method invocations may be chained and combined with fields and keys
	  to any depth:
	    .Field1.Key1.Method1.Field2.Key2.Method2
	  Methods can also be evaluated on variables, including chaining:
	    $x.Method1.Field
	- The name of a niladic function, such as
		fun
	  The result is the value of invoking the function, fun(). The return
	  types and values behave as in methods. Functions and function
	  names are described below.
	- A parenthesized instance of one the above, for grouping. The result
	  may be accessed by a field or map key invocation.
		print (.F1 arg1) (.F2 arg2)
		(.StructValuedMethod "arg").Field

Arguments may evaluate to any type; if they are pointers the implementation
automatically indirects to the base type when required.
If an evaluation yields a function value, such as a function-valued
field of a struct, the function is not invoked automatically, but it
can be used as a truth value for an if action and the like. To invoke
it, use the call function, defined below.

A pipeline is a possibly chained sequence of "commands". A command is a simple
value (argument) or a function or method call, possibly with multiple arguments:

	Argument
		The result is the value of evaluating the argument.
	.Method [Argument...]
		The method can be alone or the last element of a chain but,
		unlike methods in the middle of a chain, it can take arguments.
		The result is the value of calling the method with the
		arguments:
			dot.Method(Argument1, etc.)
	functionName [Argument...]
		The result is the value of calling the function associated
		with the name:
			function(Argument1, etc.)
		Functions and function names are described below.

Pipelines

A pipeline may be "chained" by separating a sequence of commands with pipeline
characters '|'. In a chained pipeline, the result of the each command is
passed as the last argument of the following command. The output of the final
command in the pipeline is the value of the pipeline.

The output of a command will be either one value or two values, the second of
which has type error. If that second value is present and evaluates to
non-nil, execution terminates and the error is returned to the caller of
Execute.

Variables

A pipeline inside an action may initialize a variable to capture the result.
The initialization has syntax

	$variable := pipeline

where $variable is the name of the variable. An action that declares a
variable produces no output.

If a "range" action initializes a variable, the variable is set to the
successive elements of the iteration.  Also, a "range" may declare two
variables, separated by a comma:

	range $index, $element := pipeline

in which case $index and $element are set to the successive values of the
array/slice index or map key and element, respectively.  Note that if there is
only one variable, it is assigned the element; this is opposite to the
convention in Go range clauses.

A variable's scope extends to the "end" action of the control structure ("if",
"with", or "range") in which it is declared, or to the end of the template if
there is no such control structure.  A template invocation does not inherit
variables from the point of its invocation.

When execution begins, $ is set to the data argument passed to Execute, that is,
to the starting value of dot.

Examples

Here are some example one-line templates demonstrating pipelines and variables.
All produce the quoted word "output":

	{{"\"output\""}}
		A string constant.
	{{`"output"`}}
		A raw string constant.
	{{printf "%q" "output"}}
		A function call.
	{{"output" | printf "%q"}}
		A function call whose final argument comes from the previous
		command.
	{{printf "%q" (print "out" "put")}}
		A parenthesized argument.
	{{"put" | printf "%s%s" "out" | printf "%q"}}
		A more elaborate call.
	{{"output" | printf "%s" | printf "%q"}}
		A longer chain.
	{{with "output"}}{{printf "%q" .}}{{end}}
		A with action using dot.
	{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
		A with action that creates and uses a variable.
	{{with $x := "output"}}{{printf "%q" $x}}{{end}}
		A with action that uses the variable in another action.
	{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
		The same, but pipelined.

Functions

During execution functions are found in two function maps: first in the
template, then in the global function map. By default, no functions are defined
in the template but the Funcs method can be used to add them.

Predefined global functions are named as follows.

	and
		Returns the boolean AND of its arguments by returning the
		first empty argument or the last argument, that is,
		"and x y" behaves as "if x then y else x". All the
		arguments are evaluated.
	call
		Returns the result of calling the first argument, which
		must be a function, with the remaining arguments as parameters.
		Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
		Y is a func-valued field, map entry, or the like.
		The first argument must be the result of an evaluation
		that yields a value of function type (as distinct from
		a predefined function such as print). The function must
		return either one or two result values, the second of which
		is of type error. If the arguments don't match the function
		or the returned error value is non-nil, execution stops.
	html
		Returns the escaped HTML equivalent of the textual
		representation of its arguments.
	index
		Returns the result of indexing its first argument by the
		following arguments. Thus "index x 1 2 3" is, in Go syntax,
		x[1][2][3]. Each indexed item must be a map, slice, or array.
	js
		Returns the escaped JavaScript equivalent of the textual
		representation of its arguments.
	len
		Returns the integer length of its argument.
	not
		Returns the boolean negation of its single argument.
	or
		Returns the boolean OR of its arguments by returning the
		first non-empty argument or the last argument, that is,
		"or x y" behaves as "if x then x else y". All the
		arguments are evaluated.
	print
		An alias for fmt.Sprint
	printf
		An alias for fmt.Sprintf
	println
		An alias for fmt.Sprintln
	urlquery
		Returns the escaped value of the textual representation of
		its arguments in a form suitable for embedding in a URL query.

The boolean functions take any zero value to be false and a non-zero value to
be true.

Associated templates

Each template is named by a string specified when it is created. Also, each
template is associated with zero or more other templates that it may invoke by
name; such associations are transitive and form a name space of templates.

A template may use a template invocation to instantiate another associated
template; see the explanation of the "template" action above. The name must be
that of a template associated with the template that contains the invocation.

Nested template definitions

When parsing a template, another template may be defined and associated with the
template being parsed. Template definitions must appear at the top level of the
template, much like global variables in a Go program.

The syntax of such definitions is to surround each template declaration with a
"define" and "end" action.

The define action names the template being created by providing a string
constant. Here is a simple example:

	`{{define "T1"}}ONE{{end}}
	{{define "T2"}}TWO{{end}}
	{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
	{{template "T3"}}`

This defines two templates, T1 and T2, and a third T3 that invokes the other two
when it is executed. Finally it invokes T3. If executed this template will
produce the text

	ONE TWO

By construction, a template may reside in only one association. If it's
necessary to have a template addressable from multiple associations, the
template definition must be parsed multiple times to create distinct *Template
values, or must be copied with the Clone or AddParseTree method.

Parse may be called multiple times to assemble the various associated templates;
see the ParseFiles and ParseGlob functions and methods for simple ways to parse
related templates stored in files.

A template may be executed directly or through ExecuteTemplate, which executes
an associated template identified by name. To invoke our example above, we
might write,

	err := tmpl.Execute(os.Stdout, "no data needed")
	if err != nil {
		log.Fatalf("execution failed: %s", err)
	}

or to invoke a particular template explicitly by name,

	err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")
	if err != nil {
		log.Fatalf("execution failed: %s", err)
	}

*/
package template
<commit_msg>text/template: Document that range can be used on chan types.<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package template implements data-driven templates for generating textual output.

To generate HTML output, see package html/template, which has the same interface
as this package but automatically secures HTML output against certain attacks.

Templates are executed by applying them to a data structure. Annotations in the
template refer to elements of the data structure (typically a field of a struct
or a key in a map) to control execution and derive values to be displayed.
Execution of the template walks the structure and sets the cursor, represented
by a period '.' and called "dot", to the value at the current location in the
structure as execution proceeds.

The input text for a template is UTF-8-encoded text in any format.
"Actions"--data evaluations or control structures--are delimited by
"{{" and "}}"; all text outside actions is copied to the output unchanged.
Actions may not span newlines, although comments can.

Once constructed, a template may be executed safely in parallel.

Here is a trivial example that prints "17 items are made of wool".

	type Inventory struct {
		Material string
		Count    uint
	}
	sweaters := Inventory{"wool", 17}
	tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
	if err != nil { panic(err) }
	err = tmpl.Execute(os.Stdout, sweaters)
	if err != nil { panic(err) }

More intricate examples appear below.

Actions

Here is the list of actions. "Arguments" and "pipelines" are evaluations of
data, defined in detail below.

*/
//	{{/* a comment */}}
//		A comment; discarded. May contain newlines.
//		Comments do not nest.
/*

	{{pipeline}}
		The default textual representation of the value of the pipeline
		is copied to the output.

	{{if pipeline}} T1 {{end}}
		If the value of the pipeline is empty, no output is generated;
		otherwise, T1 is executed.  The empty values are false, 0, any
		nil pointer or interface value, and any array, slice, map, or
		string of length zero.
		Dot is unaffected.

	{{if pipeline}} T1 {{else}} T0 {{end}}
		If the value of the pipeline is empty, T0 is executed;
		otherwise, T1 is executed.  Dot is unaffected.

	{{range pipeline}} T1 {{end}}
		The value of the pipeline must be an array, slice, map, or channel.
		If the value of the pipeline has length zero, nothing is output;
		otherwise, dot is set to the successive elements of the array,
		slice, or map and T1 is executed. If the value is a map and the
		keys are of basic type with a defined order ("comparable"), the
		elements will be visited in sorted key order.

	{{range pipeline}} T1 {{else}} T0 {{end}}
		The value of the pipeline must be an array, slice, map, or channel.
		If the value of the pipeline has length zero, dot is unaffected and
		T0 is executed; otherwise, dot is set to the successive elements
		of the array, slice, or map and T1 is executed.

	{{template "name"}}
		The template with the specified name is executed with nil data.

	{{template "name" pipeline}}
		The template with the specified name is executed with dot set
		to the value of the pipeline.

	{{with pipeline}} T1 {{end}}
		If the value of the pipeline is empty, no output is generated;
		otherwise, dot is set to the value of the pipeline and T1 is
		executed.

	{{with pipeline}} T1 {{else}} T0 {{end}}
		If the value of the pipeline is empty, dot is unaffected and T0
		is executed; otherwise, dot is set to the value of the pipeline
		and T1 is executed.

Arguments

An argument is a simple value, denoted by one of the following.

	- A boolean, string, character, integer, floating-point, imaginary
	  or complex constant in Go syntax. These behave like Go's untyped
	  constants, although raw strings may not span newlines.
	- The keyword nil, representing an untyped Go nil.
	- The character '.' (period):
		.
	  The result is the value of dot.
	- A variable name, which is a (possibly empty) alphanumeric string
	  preceded by a dollar sign, such as
		$piOver2
	  or
		$
	  The result is the value of the variable.
	  Variables are described below.
	- The name of a field of the data, which must be a struct, preceded
	  by a period, such as
		.Field
	  The result is the value of the field. Field invocations may be
	  chained:
	    .Field1.Field2
	  Fields can also be evaluated on variables, including chaining:
	    $x.Field1.Field2
	- The name of a key of the data, which must be a map, preceded
	  by a period, such as
		.Key
	  The result is the map element value indexed by the key.
	  Key invocations may be chained and combined with fields to any
	  depth:
	    .Field1.Key1.Field2.Key2
	  Although the key must be an alphanumeric identifier, unlike with
	  field names they do not need to start with an upper case letter.
	  Keys can also be evaluated on variables, including chaining:
	    $x.key1.key2
	- The name of a niladic method of the data, preceded by a period,
	  such as
		.Method
	  The result is the value of invoking the method with dot as the
	  receiver, dot.Method(). Such a method must have one return value (of
	  any type) or two return values, the second of which is an error.
	  If it has two and the returned error is non-nil, execution terminates
	  and an error is returned to the caller as the value of Execute.
	  Method invocations may be chained and combined with fields and keys
	  to any depth:
	    .Field1.Key1.Method1.Field2.Key2.Method2
	  Methods can also be evaluated on variables, including chaining:
	    $x.Method1.Field
	- The name of a niladic function, such as
		fun
	  The result is the value of invoking the function, fun(). The return
	  types and values behave as in methods. Functions and function
	  names are described below.
	- A parenthesized instance of one the above, for grouping. The result
	  may be accessed by a field or map key invocation.
		print (.F1 arg1) (.F2 arg2)
		(.StructValuedMethod "arg").Field

Arguments may evaluate to any type; if they are pointers the implementation
automatically indirects to the base type when required.
If an evaluation yields a function value, such as a function-valued
field of a struct, the function is not invoked automatically, but it
can be used as a truth value for an if action and the like. To invoke
it, use the call function, defined below.

A pipeline is a possibly chained sequence of "commands". A command is a simple
value (argument) or a function or method call, possibly with multiple arguments:

	Argument
		The result is the value of evaluating the argument.
	.Method [Argument...]
		The method can be alone or the last element of a chain but,
		unlike methods in the middle of a chain, it can take arguments.
		The result is the value of calling the method with the
		arguments:
			dot.Method(Argument1, etc.)
	functionName [Argument...]
		The result is the value of calling the function associated
		with the name:
			function(Argument1, etc.)
		Functions and function names are described below.

Pipelines

A pipeline may be "chained" by separating a sequence of commands with pipeline
characters '|'. In a chained pipeline, the result of the each command is
passed as the last argument of the following command. The output of the final
command in the pipeline is the value of the pipeline.

The output of a command will be either one value or two values, the second of
which has type error. If that second value is present and evaluates to
non-nil, execution terminates and the error is returned to the caller of
Execute.

Variables

A pipeline inside an action may initialize a variable to capture the result.
The initialization has syntax

	$variable := pipeline

where $variable is the name of the variable. An action that declares a
variable produces no output.

If a "range" action initializes a variable, the variable is set to the
successive elements of the iteration.  Also, a "range" may declare two
variables, separated by a comma:

	range $index, $element := pipeline

in which case $index and $element are set to the successive values of the
array/slice index or map key and element, respectively.  Note that if there is
only one variable, it is assigned the element; this is opposite to the
convention in Go range clauses.

A variable's scope extends to the "end" action of the control structure ("if",
"with", or "range") in which it is declared, or to the end of the template if
there is no such control structure.  A template invocation does not inherit
variables from the point of its invocation.

When execution begins, $ is set to the data argument passed to Execute, that is,
to the starting value of dot.

Examples

Here are some example one-line templates demonstrating pipelines and variables.
All produce the quoted word "output":

	{{"\"output\""}}
		A string constant.
	{{`"output"`}}
		A raw string constant.
	{{printf "%q" "output"}}
		A function call.
	{{"output" | printf "%q"}}
		A function call whose final argument comes from the previous
		command.
	{{printf "%q" (print "out" "put")}}
		A parenthesized argument.
	{{"put" | printf "%s%s" "out" | printf "%q"}}
		A more elaborate call.
	{{"output" | printf "%s" | printf "%q"}}
		A longer chain.
	{{with "output"}}{{printf "%q" .}}{{end}}
		A with action using dot.
	{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
		A with action that creates and uses a variable.
	{{with $x := "output"}}{{printf "%q" $x}}{{end}}
		A with action that uses the variable in another action.
	{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
		The same, but pipelined.

Functions

During execution functions are found in two function maps: first in the
template, then in the global function map. By default, no functions are defined
in the template but the Funcs method can be used to add them.

Predefined global functions are named as follows.

	and
		Returns the boolean AND of its arguments by returning the
		first empty argument or the last argument, that is,
		"and x y" behaves as "if x then y else x". All the
		arguments are evaluated.
	call
		Returns the result of calling the first argument, which
		must be a function, with the remaining arguments as parameters.
		Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
		Y is a func-valued field, map entry, or the like.
		The first argument must be the result of an evaluation
		that yields a value of function type (as distinct from
		a predefined function such as print). The function must
		return either one or two result values, the second of which
		is of type error. If the arguments don't match the function
		or the returned error value is non-nil, execution stops.
	html
		Returns the escaped HTML equivalent of the textual
		representation of its arguments.
	index
		Returns the result of indexing its first argument by the
		following arguments. Thus "index x 1 2 3" is, in Go syntax,
		x[1][2][3]. Each indexed item must be a map, slice, or array.
	js
		Returns the escaped JavaScript equivalent of the textual
		representation of its arguments.
	len
		Returns the integer length of its argument.
	not
		Returns the boolean negation of its single argument.
	or
		Returns the boolean OR of its arguments by returning the
		first non-empty argument or the last argument, that is,
		"or x y" behaves as "if x then x else y". All the
		arguments are evaluated.
	print
		An alias for fmt.Sprint
	printf
		An alias for fmt.Sprintf
	println
		An alias for fmt.Sprintln
	urlquery
		Returns the escaped value of the textual representation of
		its arguments in a form suitable for embedding in a URL query.

The boolean functions take any zero value to be false and a non-zero value to
be true.

Associated templates

Each template is named by a string specified when it is created. Also, each
template is associated with zero or more other templates that it may invoke by
name; such associations are transitive and form a name space of templates.

A template may use a template invocation to instantiate another associated
template; see the explanation of the "template" action above. The name must be
that of a template associated with the template that contains the invocation.

Nested template definitions

When parsing a template, another template may be defined and associated with the
template being parsed. Template definitions must appear at the top level of the
template, much like global variables in a Go program.

The syntax of such definitions is to surround each template declaration with a
"define" and "end" action.

The define action names the template being created by providing a string
constant. Here is a simple example:

	`{{define "T1"}}ONE{{end}}
	{{define "T2"}}TWO{{end}}
	{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
	{{template "T3"}}`

This defines two templates, T1 and T2, and a third T3 that invokes the other two
when it is executed. Finally it invokes T3. If executed this template will
produce the text

	ONE TWO

By construction, a template may reside in only one association. If it's
necessary to have a template addressable from multiple associations, the
template definition must be parsed multiple times to create distinct *Template
values, or must be copied with the Clone or AddParseTree method.

Parse may be called multiple times to assemble the various associated templates;
see the ParseFiles and ParseGlob functions and methods for simple ways to parse
related templates stored in files.

A template may be executed directly or through ExecuteTemplate, which executes
an associated template identified by name. To invoke our example above, we
might write,

	err := tmpl.Execute(os.Stdout, "no data needed")
	if err != nil {
		log.Fatalf("execution failed: %s", err)
	}

or to invoke a particular template explicitly by name,

	err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")
	if err != nil {
		log.Fatalf("execution failed: %s", err)
	}

*/
package template
<|endoftext|>


<commit_before>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package utf8 implements functions and constants to support text encoded in
// UTF-8. It includes functions to translate between runes and UTF-8 byte sequences.
package utf8

// The conditions RuneError==unicode.ReplacementChar and
// MaxRune==unicode.MaxRune are verified in the tests.
// Defining them locally avoids this package depending on package unicode.

// Numbers fundamental to the encoding.
const (
	RuneError = '\uFFFD'     // the "error" Rune or "Unicode replacement character"
	RuneSelf  = 0x80         // characters below Runeself are represented as themselves in a single byte.
	MaxRune   = '\U0010FFFF' // Maximum valid Unicode code point.
	UTFMax    = 4            // maximum number of bytes of a UTF-8 encoded Unicode character.
)

// Code points in the surrogate range are not valid for UTF-8.
const (
	surrogateMin = 0xD800
	surrogateMax = 0xDFFF
)

const (
	t1 = 0x00 // 0000 0000
	tx = 0x80 // 1000 0000
	t2 = 0xC0 // 1100 0000
	t3 = 0xE0 // 1110 0000
	t4 = 0xF0 // 1111 0000
	t5 = 0xF8 // 1111 1000

	maskx = 0x3F // 0011 1111
	mask2 = 0x1F // 0001 1111
	mask3 = 0x0F // 0000 1111
	mask4 = 0x07 // 0000 0111

	rune1Max = 1<<7 - 1
	rune2Max = 1<<11 - 1
	rune3Max = 1<<16 - 1
)

func decodeRuneInternal(p []byte) (r rune, size int, short bool) {
	n := len(p)
	if n < 1 {
		return RuneError, 0, true
	}
	c0 := p[0]

	// 1-byte, 7-bit sequence?
	if c0 < tx {
		return rune(c0), 1, false
	}

	// unexpected continuation byte?
	if c0 < t2 {
		return RuneError, 1, false
	}

	// need first continuation byte
	if n < 2 {
		return RuneError, 1, true
	}
	c1 := p[1]
	if c1 < tx || t2 <= c1 {
		return RuneError, 1, false
	}

	// 2-byte, 11-bit sequence?
	if c0 < t3 {
		r = rune(c0&mask2)<<6 | rune(c1&maskx)
		if r <= rune1Max {
			return RuneError, 1, false
		}
		return r, 2, false
	}

	// need second continuation byte
	if n < 3 {
		return RuneError, 1, true
	}
	c2 := p[2]
	if c2 < tx || t2 <= c2 {
		return RuneError, 1, false
	}

	// 3-byte, 16-bit sequence?
	if c0 < t4 {
		r = rune(c0&mask3)<<12 | rune(c1&maskx)<<6 | rune(c2&maskx)
		if r <= rune2Max {
			return RuneError, 1, false
		}
		if surrogateMin <= r && r <= surrogateMax {
			return RuneError, 1, false
		}
		return r, 3, false
	}

	// need third continuation byte
	if n < 4 {
		return RuneError, 1, true
	}
	c3 := p[3]
	if c3 < tx || t2 <= c3 {
		return RuneError, 1, false
	}

	// 4-byte, 21-bit sequence?
	if c0 < t5 {
		r = rune(c0&mask4)<<18 | rune(c1&maskx)<<12 | rune(c2&maskx)<<6 | rune(c3&maskx)
		if r <= rune3Max || MaxRune < r {
			return RuneError, 1, false
		}
		return r, 4, false
	}

	// error
	return RuneError, 1, false
}

func decodeRuneInStringInternal(s string) (r rune, size int, short bool) {
	n := len(s)
	if n < 1 {
		return RuneError, 0, true
	}
	c0 := s[0]

	// 1-byte, 7-bit sequence?
	if c0 < tx {
		return rune(c0), 1, false
	}

	// unexpected continuation byte?
	if c0 < t2 {
		return RuneError, 1, false
	}

	// need first continuation byte
	if n < 2 {
		return RuneError, 1, true
	}
	c1 := s[1]
	if c1 < tx || t2 <= c1 {
		return RuneError, 1, false
	}

	// 2-byte, 11-bit sequence?
	if c0 < t3 {
		r = rune(c0&mask2)<<6 | rune(c1&maskx)
		if r <= rune1Max {
			return RuneError, 1, false
		}
		return r, 2, false
	}

	// need second continuation byte
	if n < 3 {
		return RuneError, 1, true
	}
	c2 := s[2]
	if c2 < tx || t2 <= c2 {
		return RuneError, 1, false
	}

	// 3-byte, 16-bit sequence?
	if c0 < t4 {
		r = rune(c0&mask3)<<12 | rune(c1&maskx)<<6 | rune(c2&maskx)
		if r <= rune2Max {
			return RuneError, 1, false
		}
		if surrogateMin <= r && r <= surrogateMax {
			return RuneError, 1, false
		}
		return r, 3, false
	}

	// need third continuation byte
	if n < 4 {
		return RuneError, 1, true
	}
	c3 := s[3]
	if c3 < tx || t2 <= c3 {
		return RuneError, 1, false
	}

	// 4-byte, 21-bit sequence?
	if c0 < t5 {
		r = rune(c0&mask4)<<18 | rune(c1&maskx)<<12 | rune(c2&maskx)<<6 | rune(c3&maskx)
		if r <= rune3Max || MaxRune < r {
			return RuneError, 1, false
		}
		return r, 4, false
	}

	// error
	return RuneError, 1, false
}

// FullRune reports whether the bytes in p begin with a full UTF-8 encoding of a rune.
// An invalid encoding is considered a full Rune since it will convert as a width-1 error rune.
func FullRune(p []byte) bool {
	_, _, short := decodeRuneInternal(p)
	return !short
}

// FullRuneInString is like FullRune but its input is a string.
func FullRuneInString(s string) bool {
	_, _, short := decodeRuneInStringInternal(s)
	return !short
}

// DecodeRune unpacks the first UTF-8 encoding in p and returns the rune and its width in bytes.
// If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.
// An encoding is invalid if it is incorrect UTF-8, encodes a rune that is
// out of range, or is not the shortest possible UTF-8 encoding for the
// value. No other validation is performed.
func DecodeRune(p []byte) (r rune, size int) {
	r, size, _ = decodeRuneInternal(p)
	return
}

// DecodeRuneInString is like DecodeRune but its input is a string.
// If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.
// An encoding is invalid if it is incorrect UTF-8, encodes a rune that is
// out of range, or is not the shortest possible UTF-8 encoding for the
// value. No other validation is performed.
func DecodeRuneInString(s string) (r rune, size int) {
	r, size, _ = decodeRuneInStringInternal(s)
	return
}

// DecodeLastRune unpacks the last UTF-8 encoding in p and returns the rune and its width in bytes.
// If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.
// An encoding is invalid if it is incorrect UTF-8, encodes a rune that is
// out of range, or is not the shortest possible UTF-8 encoding for the
// value. No other validation is performed.
func DecodeLastRune(p []byte) (r rune, size int) {
	end := len(p)
	if end == 0 {
		return RuneError, 0
	}
	start := end - 1
	r = rune(p[start])
	if r < RuneSelf {
		return r, 1
	}
	// guard against O(n^2) behavior when traversing
	// backwards through strings with long sequences of
	// invalid UTF-8.
	lim := end - UTFMax
	if lim < 0 {
		lim = 0
	}
	for start--; start >= lim; start-- {
		if RuneStart(p[start]) {
			break
		}
	}
	if start < 0 {
		start = 0
	}
	r, size = DecodeRune(p[start:end])
	if start+size != end {
		return RuneError, 1
	}
	return r, size
}

// DecodeLastRuneInString is like DecodeLastRune but its input is a string.
// If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.
// An encoding is invalid if it is incorrect UTF-8, encodes a rune that is
// out of range, or is not the shortest possible UTF-8 encoding for the
// value. No other validation is performed.
func DecodeLastRuneInString(s string) (r rune, size int) {
	end := len(s)
	if end == 0 {
		return RuneError, 0
	}
	start := end - 1
	r = rune(s[start])
	if r < RuneSelf {
		return r, 1
	}
	// guard against O(n^2) behavior when traversing
	// backwards through strings with long sequences of
	// invalid UTF-8.
	lim := end - UTFMax
	if lim < 0 {
		lim = 0
	}
	for start--; start >= lim; start-- {
		if RuneStart(s[start]) {
			break
		}
	}
	if start < 0 {
		start = 0
	}
	r, size = DecodeRuneInString(s[start:end])
	if start+size != end {
		return RuneError, 1
	}
	return r, size
}

// RuneLen returns the number of bytes required to encode the rune.
// It returns -1 if the rune is not a valid value to encode in UTF-8.
func RuneLen(r rune) int {
	switch {
	case r < 0:
		return -1
	case r <= rune1Max:
		return 1
	case r <= rune2Max:
		return 2
	case surrogateMin <= r && r <= surrogateMax:
		return -1
	case r <= rune3Max:
		return 3
	case r <= MaxRune:
		return 4
	}
	return -1
}

// EncodeRune writes into p (which must be large enough) the UTF-8 encoding of the rune.
// It returns the number of bytes written.
func EncodeRune(p []byte, r rune) int {
	// Negative values are erroneous.  Making it unsigned addresses the problem.
	if uint32(r) <= rune1Max {
		p[0] = byte(r)
		return 1
	}

	if uint32(r) <= rune2Max {
		p[0] = t2 | byte(r>>6)
		p[1] = tx | byte(r)&maskx
		return 2
	}

	if uint32(r) > MaxRune {
		r = RuneError
	}

	if surrogateMin <= r && r <= surrogateMax {
		r = RuneError
	}

	if uint32(r) <= rune3Max {
		p[0] = t3 | byte(r>>12)
		p[1] = tx | byte(r>>6)&maskx
		p[2] = tx | byte(r)&maskx
		return 3
	}

	p[0] = t4 | byte(r>>18)
	p[1] = tx | byte(r>>12)&maskx
	p[2] = tx | byte(r>>6)&maskx
	p[3] = tx | byte(r)&maskx
	return 4
}

// RuneCount returns the number of runes in p.  Erroneous and short
// encodings are treated as single runes of width 1 byte.
func RuneCount(p []byte) int {
	i := 0
	var n int
	for n = 0; i < len(p); n++ {
		if p[i] < RuneSelf {
			i++
		} else {
			_, size := DecodeRune(p[i:])
			i += size
		}
	}
	return n
}

// RuneCountInString is like RuneCount but its input is a string.
func RuneCountInString(s string) (n int) {
	for _ = range s {
		n++
	}
	return
}

// RuneStart reports whether the byte could be the first byte of
// an encoded rune.  Second and subsequent bytes always have the top
// two bits set to 10.
func RuneStart(b byte) bool { return b&0xC0 != 0x80 }

// Valid reports whether p consists entirely of valid UTF-8-encoded runes.
func Valid(p []byte) bool {
	i := 0
	for i < len(p) {
		if p[i] < RuneSelf {
			i++
		} else {
			_, size := DecodeRune(p[i:])
			if size == 1 {
				// All valid runes of size 1 (those
				// below RuneSelf) were handled above.
				// This must be a RuneError.
				return false
			}
			i += size
		}
	}
	return true
}

// ValidString reports whether s consists entirely of valid UTF-8-encoded runes.
func ValidString(s string) bool {
	for i, r := range s {
		if r == RuneError {
			// The RuneError value can be an error
			// sentinel value (if it's size 1) or the same
			// value encoded properly. Decode it to see if
			// it's the 1 byte sentinel value.
			_, size := DecodeRuneInString(s[i:])
			if size == 1 {
				return false
			}
		}
	}
	return true
}

// ValidRune reports whether r can be legally encoded as UTF-8.
// Code points that are out of range or a surrogate half are illegal.
func ValidRune(r rune) bool {
	switch {
	case r < 0:
		return false
	case surrogateMin <= r && r <= surrogateMax:
		return false
	case r > MaxRune:
		return false
	}
	return true
}
<commit_msg>unicode/utf8: minor code simplification<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package utf8 implements functions and constants to support text encoded in
// UTF-8. It includes functions to translate between runes and UTF-8 byte sequences.
package utf8

// The conditions RuneError==unicode.ReplacementChar and
// MaxRune==unicode.MaxRune are verified in the tests.
// Defining them locally avoids this package depending on package unicode.

// Numbers fundamental to the encoding.
const (
	RuneError = '\uFFFD'     // the "error" Rune or "Unicode replacement character"
	RuneSelf  = 0x80         // characters below Runeself are represented as themselves in a single byte.
	MaxRune   = '\U0010FFFF' // Maximum valid Unicode code point.
	UTFMax    = 4            // maximum number of bytes of a UTF-8 encoded Unicode character.
)

// Code points in the surrogate range are not valid for UTF-8.
const (
	surrogateMin = 0xD800
	surrogateMax = 0xDFFF
)

const (
	t1 = 0x00 // 0000 0000
	tx = 0x80 // 1000 0000
	t2 = 0xC0 // 1100 0000
	t3 = 0xE0 // 1110 0000
	t4 = 0xF0 // 1111 0000
	t5 = 0xF8 // 1111 1000

	maskx = 0x3F // 0011 1111
	mask2 = 0x1F // 0001 1111
	mask3 = 0x0F // 0000 1111
	mask4 = 0x07 // 0000 0111

	rune1Max = 1<<7 - 1
	rune2Max = 1<<11 - 1
	rune3Max = 1<<16 - 1
)

func decodeRuneInternal(p []byte) (r rune, size int, short bool) {
	n := len(p)
	if n < 1 {
		return RuneError, 0, true
	}
	c0 := p[0]

	// 1-byte, 7-bit sequence?
	if c0 < tx {
		return rune(c0), 1, false
	}

	// unexpected continuation byte?
	if c0 < t2 {
		return RuneError, 1, false
	}

	// need first continuation byte
	if n < 2 {
		return RuneError, 1, true
	}
	c1 := p[1]
	if c1 < tx || t2 <= c1 {
		return RuneError, 1, false
	}

	// 2-byte, 11-bit sequence?
	if c0 < t3 {
		r = rune(c0&mask2)<<6 | rune(c1&maskx)
		if r <= rune1Max {
			return RuneError, 1, false
		}
		return r, 2, false
	}

	// need second continuation byte
	if n < 3 {
		return RuneError, 1, true
	}
	c2 := p[2]
	if c2 < tx || t2 <= c2 {
		return RuneError, 1, false
	}

	// 3-byte, 16-bit sequence?
	if c0 < t4 {
		r = rune(c0&mask3)<<12 | rune(c1&maskx)<<6 | rune(c2&maskx)
		if r <= rune2Max {
			return RuneError, 1, false
		}
		if surrogateMin <= r && r <= surrogateMax {
			return RuneError, 1, false
		}
		return r, 3, false
	}

	// need third continuation byte
	if n < 4 {
		return RuneError, 1, true
	}
	c3 := p[3]
	if c3 < tx || t2 <= c3 {
		return RuneError, 1, false
	}

	// 4-byte, 21-bit sequence?
	if c0 < t5 {
		r = rune(c0&mask4)<<18 | rune(c1&maskx)<<12 | rune(c2&maskx)<<6 | rune(c3&maskx)
		if r <= rune3Max || MaxRune < r {
			return RuneError, 1, false
		}
		return r, 4, false
	}

	// error
	return RuneError, 1, false
}

func decodeRuneInStringInternal(s string) (r rune, size int, short bool) {
	n := len(s)
	if n < 1 {
		return RuneError, 0, true
	}
	c0 := s[0]

	// 1-byte, 7-bit sequence?
	if c0 < tx {
		return rune(c0), 1, false
	}

	// unexpected continuation byte?
	if c0 < t2 {
		return RuneError, 1, false
	}

	// need first continuation byte
	if n < 2 {
		return RuneError, 1, true
	}
	c1 := s[1]
	if c1 < tx || t2 <= c1 {
		return RuneError, 1, false
	}

	// 2-byte, 11-bit sequence?
	if c0 < t3 {
		r = rune(c0&mask2)<<6 | rune(c1&maskx)
		if r <= rune1Max {
			return RuneError, 1, false
		}
		return r, 2, false
	}

	// need second continuation byte
	if n < 3 {
		return RuneError, 1, true
	}
	c2 := s[2]
	if c2 < tx || t2 <= c2 {
		return RuneError, 1, false
	}

	// 3-byte, 16-bit sequence?
	if c0 < t4 {
		r = rune(c0&mask3)<<12 | rune(c1&maskx)<<6 | rune(c2&maskx)
		if r <= rune2Max {
			return RuneError, 1, false
		}
		if surrogateMin <= r && r <= surrogateMax {
			return RuneError, 1, false
		}
		return r, 3, false
	}

	// need third continuation byte
	if n < 4 {
		return RuneError, 1, true
	}
	c3 := s[3]
	if c3 < tx || t2 <= c3 {
		return RuneError, 1, false
	}

	// 4-byte, 21-bit sequence?
	if c0 < t5 {
		r = rune(c0&mask4)<<18 | rune(c1&maskx)<<12 | rune(c2&maskx)<<6 | rune(c3&maskx)
		if r <= rune3Max || MaxRune < r {
			return RuneError, 1, false
		}
		return r, 4, false
	}

	// error
	return RuneError, 1, false
}

// FullRune reports whether the bytes in p begin with a full UTF-8 encoding of a rune.
// An invalid encoding is considered a full Rune since it will convert as a width-1 error rune.
func FullRune(p []byte) bool {
	_, _, short := decodeRuneInternal(p)
	return !short
}

// FullRuneInString is like FullRune but its input is a string.
func FullRuneInString(s string) bool {
	_, _, short := decodeRuneInStringInternal(s)
	return !short
}

// DecodeRune unpacks the first UTF-8 encoding in p and returns the rune and its width in bytes.
// If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.
// An encoding is invalid if it is incorrect UTF-8, encodes a rune that is
// out of range, or is not the shortest possible UTF-8 encoding for the
// value. No other validation is performed.
func DecodeRune(p []byte) (r rune, size int) {
	r, size, _ = decodeRuneInternal(p)
	return
}

// DecodeRuneInString is like DecodeRune but its input is a string.
// If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.
// An encoding is invalid if it is incorrect UTF-8, encodes a rune that is
// out of range, or is not the shortest possible UTF-8 encoding for the
// value. No other validation is performed.
func DecodeRuneInString(s string) (r rune, size int) {
	r, size, _ = decodeRuneInStringInternal(s)
	return
}

// DecodeLastRune unpacks the last UTF-8 encoding in p and returns the rune and its width in bytes.
// If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.
// An encoding is invalid if it is incorrect UTF-8, encodes a rune that is
// out of range, or is not the shortest possible UTF-8 encoding for the
// value. No other validation is performed.
func DecodeLastRune(p []byte) (r rune, size int) {
	end := len(p)
	if end == 0 {
		return RuneError, 0
	}
	start := end - 1
	r = rune(p[start])
	if r < RuneSelf {
		return r, 1
	}
	// guard against O(n^2) behavior when traversing
	// backwards through strings with long sequences of
	// invalid UTF-8.
	lim := end - UTFMax
	if lim < 0 {
		lim = 0
	}
	for start--; start >= lim; start-- {
		if RuneStart(p[start]) {
			break
		}
	}
	if start < 0 {
		start = 0
	}
	r, size = DecodeRune(p[start:end])
	if start+size != end {
		return RuneError, 1
	}
	return r, size
}

// DecodeLastRuneInString is like DecodeLastRune but its input is a string.
// If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.
// An encoding is invalid if it is incorrect UTF-8, encodes a rune that is
// out of range, or is not the shortest possible UTF-8 encoding for the
// value. No other validation is performed.
func DecodeLastRuneInString(s string) (r rune, size int) {
	end := len(s)
	if end == 0 {
		return RuneError, 0
	}
	start := end - 1
	r = rune(s[start])
	if r < RuneSelf {
		return r, 1
	}
	// guard against O(n^2) behavior when traversing
	// backwards through strings with long sequences of
	// invalid UTF-8.
	lim := end - UTFMax
	if lim < 0 {
		lim = 0
	}
	for start--; start >= lim; start-- {
		if RuneStart(s[start]) {
			break
		}
	}
	if start < 0 {
		start = 0
	}
	r, size = DecodeRuneInString(s[start:end])
	if start+size != end {
		return RuneError, 1
	}
	return r, size
}

// RuneLen returns the number of bytes required to encode the rune.
// It returns -1 if the rune is not a valid value to encode in UTF-8.
func RuneLen(r rune) int {
	switch {
	case r < 0:
		return -1
	case r <= rune1Max:
		return 1
	case r <= rune2Max:
		return 2
	case surrogateMin <= r && r <= surrogateMax:
		return -1
	case r <= rune3Max:
		return 3
	case r <= MaxRune:
		return 4
	}
	return -1
}

// EncodeRune writes into p (which must be large enough) the UTF-8 encoding of the rune.
// It returns the number of bytes written.
func EncodeRune(p []byte, r rune) int {
	// Negative values are erroneous.  Making it unsigned addresses the problem.
	switch i := uint32(r); {
	case i <= rune1Max:
		p[0] = byte(r)
		return 1
	case i <= rune2Max:
		p[0] = t2 | byte(r>>6)
		p[1] = tx | byte(r)&maskx
		return 2
	case i > MaxRune, surrogateMin <= i && i <= surrogateMax:
		r = RuneError
		fallthrough
	case i <= rune3Max:
		p[0] = t3 | byte(r>>12)
		p[1] = tx | byte(r>>6)&maskx
		p[2] = tx | byte(r)&maskx
		return 3
	default:
		p[0] = t4 | byte(r>>18)
		p[1] = tx | byte(r>>12)&maskx
		p[2] = tx | byte(r>>6)&maskx
		p[3] = tx | byte(r)&maskx
		return 4
	}
}

// RuneCount returns the number of runes in p.  Erroneous and short
// encodings are treated as single runes of width 1 byte.
func RuneCount(p []byte) int {
	i := 0
	var n int
	for n = 0; i < len(p); n++ {
		if p[i] < RuneSelf {
			i++
		} else {
			_, size := DecodeRune(p[i:])
			i += size
		}
	}
	return n
}

// RuneCountInString is like RuneCount but its input is a string.
func RuneCountInString(s string) (n int) {
	for _ = range s {
		n++
	}
	return
}

// RuneStart reports whether the byte could be the first byte of
// an encoded rune.  Second and subsequent bytes always have the top
// two bits set to 10.
func RuneStart(b byte) bool { return b&0xC0 != 0x80 }

// Valid reports whether p consists entirely of valid UTF-8-encoded runes.
func Valid(p []byte) bool {
	i := 0
	for i < len(p) {
		if p[i] < RuneSelf {
			i++
		} else {
			_, size := DecodeRune(p[i:])
			if size == 1 {
				// All valid runes of size 1 (those
				// below RuneSelf) were handled above.
				// This must be a RuneError.
				return false
			}
			i += size
		}
	}
	return true
}

// ValidString reports whether s consists entirely of valid UTF-8-encoded runes.
func ValidString(s string) bool {
	for i, r := range s {
		if r == RuneError {
			// The RuneError value can be an error
			// sentinel value (if it's size 1) or the same
			// value encoded properly. Decode it to see if
			// it's the 1 byte sentinel value.
			_, size := DecodeRuneInString(s[i:])
			if size == 1 {
				return false
			}
		}
	}
	return true
}

// ValidRune reports whether r can be legally encoded as UTF-8.
// Code points that are out of range or a surrogate half are illegal.
func ValidRune(r rune) bool {
	switch {
	case r < 0:
		return false
	case surrogateMin <= r && r <= surrogateMax:
		return false
	case r > MaxRune:
		return false
	}
	return true
}
<|endoftext|>


<commit_before>package template

import (
//	"reflect"
	"testing"
//	"fmt"

//	"github.com/hashicorp/consul-template/template"
)

func TestNewMap (t *testing.T) {
	m := NewMap()

	if m.data == nil {
		t.Errorf("expected data to not be nil")
	}
}

func TestMapPut (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)
}

func TestMapPutGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	rt := m.Get("a")
	if rt.(string) != "ABC" {
		t.Errorf("expected value is not be correct. Expected: 'ABC' Got: %s" , rt )
	}

	rt = m.Get("1")
	if rt.(int) != 123 {
		t.Errorf("expected value is not be correct. Expected: 123 Got: %s", rt )
	}

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}
}

func TestMapPutClear (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Clear()

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 0 Got: %i", m.Size() )
	}
}

func TestMapPutClearGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Clear()

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 0 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt)
	}
	rt = m.Get("1")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt)
	}
}

func TestMapPutRemoveGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Remove("a")
	m.Remove("1")

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 0 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt)
	}

	rt = m.Get("1")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt )
	}
}

func TestMapPutClearPutGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Clear()

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Put("a", "XYZ")
	m.Put("1", 789)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt.(string) != "XYZ" {
		t.Errorf("expected value is not be correct. Expected: 'XYZ' Got: %s", rt)
	}
	rt = m.Get("1")
	if rt.(int) != 789 {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt)
	}
}

func TestMapPutPutGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("a", "MNO")
	m.Put("a", "XYZ")
	m.Put("1", 123)
	m.Put("1", 456)
	m.Put("1", 789)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt.(string) != "XYZ" {
		t.Errorf("expected value is not be correct. Expected: 'XYZ' Got: %s", rt )
	}

	rt = m.Get("1")
	if rt.(int) != 789 {
		t.Errorf("expected value is not be correct. Expected: 789 Got: %s ", rt )
	}
}

func TestMapEmptyGet (t *testing.T) {
	m := NewMap()

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 0 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt )
	}

	rt = m.Get("1")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt )
	}
}

// *****************

func TestMapPutContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	rt := m.ContainsKey("a")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s" , rt )
	}

	rt = m.ContainsKey("1")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt )
	}

}

func TestMapPutClearContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Clear()

	rt := m.ContainsKey("a")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}
	rt = m.ContainsKey("1")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}
}

func TestMapPutRemoveContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Remove("a")
	m.Remove("1")

	rt := m.ContainsKey("a")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}

	rt = m.ContainsKey("1")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}
}

func TestMapPutClearPutContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Clear()

	m.Put("a", "XYZ")
	m.Put("1", 789)

	rt := m.ContainsKey("a")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt)
	}
	rt = m.ContainsKey("1")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt)
	}
}

func TestMapPutPutContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("a", "MNO")
	m.Put("a", "XYZ")
	m.Put("1", 123)
	m.Put("1", 456)
	m.Put("1", 789)

	rt := m.ContainsKey("a")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt )
	}

	rt = m.ContainsKey("1")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s ", rt )
	}
}

func TestMapEmptyContainsKey (t *testing.T) {
	m := NewMap()

	rt := m.ContainsKey("a")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}

	rt = m.ContainsKey("1")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}
}

// *****************

func TestMapPutContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	rt := m.ContainsValue("ABC")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s" , rt )
	}

	rt = m.ContainsValue(123)
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt )
	}

}

func TestMapPutClearContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Clear()

	rt := m.ContainsValue("ABC")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}
	rt = m.ContainsValue(123)
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}
}

func TestMapPutRemoveContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Remove("a")
	m.Remove("1")

	rt := m.ContainsValue("ABC")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}

	rt = m.ContainsValue(123)
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}
}

func TestMapPutClearPutContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Clear()

	m.Put("a", "XYZ")
	m.Put("1", 789)

	rt := m.ContainsValue("XYZ")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt)
	}
	rt = m.ContainsValue(789)
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt)
	}
}

func TestMapPutPutContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("a", "MNO")
	m.Put("a", "XYZ")
	m.Put("1", 123)
	m.Put("1", 456)
	m.Put("1", 789)

	rt := m.ContainsValue("XYZ")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt )
	}

	rt = m.ContainsValue(789)
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s ", rt )
	}
}

func TestMapEmptyContainsValue (t *testing.T) {
	m := NewMap()

	rt := m.ContainsValue("ABC")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}

	rt = m.ContainsValue(123)
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}
}
<commit_msg>cleaning up<commit_after>package template

import (
	"testing"
)

func TestNewMap (t *testing.T) {
	m := NewMap()

	if m.data == nil {
		t.Errorf("expected data to not be nil")
	}
}

func TestMapPut (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)
}

func TestMapPutGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	rt := m.Get("a")
	if rt.(string) != "ABC" {
		t.Errorf("expected value is not be correct. Expected: 'ABC' Got: %s" , rt )
	}

	rt = m.Get("1")
	if rt.(int) != 123 {
		t.Errorf("expected value is not be correct. Expected: 123 Got: %s", rt )
	}

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}
}

func TestMapPutClear (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Clear()

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 0 Got: %i", m.Size() )
	}
}

func TestMapPutClearGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Clear()

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 0 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt)
	}
	rt = m.Get("1")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt)
	}
}

func TestMapPutRemoveGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Remove("a")
	m.Remove("1")

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 0 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt)
	}

	rt = m.Get("1")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt )
	}
}

func TestMapPutClearPutGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Clear()

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	m.Put("a", "XYZ")
	m.Put("1", 789)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt.(string) != "XYZ" {
		t.Errorf("expected value is not be correct. Expected: 'XYZ' Got: %s", rt)
	}
	rt = m.Get("1")
	if rt.(int) != 789 {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt)
	}
}

func TestMapPutPutGet (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("a", "MNO")
	m.Put("a", "XYZ")
	m.Put("1", 123)
	m.Put("1", 456)
	m.Put("1", 789)

	if m.Size() != 2 {
		t.Errorf("expected size is not be correct. Expected: 2 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt.(string) != "XYZ" {
		t.Errorf("expected value is not be correct. Expected: 'XYZ' Got: %s", rt )
	}

	rt = m.Get("1")
	if rt.(int) != 789 {
		t.Errorf("expected value is not be correct. Expected: 789 Got: %s ", rt )
	}
}

func TestMapEmptyGet (t *testing.T) {
	m := NewMap()

	if m.Size() != 0 {
		t.Errorf("expected size is not be correct. Expected: 0 Got: %i", m.Size() )
	}

	rt := m.Get("a")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt )
	}

	rt = m.Get("1")
	if rt != nil {
		t.Errorf("expected value is not be correct. Expected: nil Got: %s", rt )
	}
}

// *****************

func TestMapPutContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	rt := m.ContainsKey("a")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s" , rt )
	}

	rt = m.ContainsKey("1")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt )
	}

}

func TestMapPutClearContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Clear()

	rt := m.ContainsKey("a")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}
	rt = m.ContainsKey("1")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}
}

func TestMapPutRemoveContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Remove("a")
	m.Remove("1")

	rt := m.ContainsKey("a")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}

	rt = m.ContainsKey("1")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}
}

func TestMapPutClearPutContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Clear()

	m.Put("a", "XYZ")
	m.Put("1", 789)

	rt := m.ContainsKey("a")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt)
	}
	rt = m.ContainsKey("1")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt)
	}
}

func TestMapPutPutContainsKey (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("a", "MNO")
	m.Put("a", "XYZ")
	m.Put("1", 123)
	m.Put("1", 456)
	m.Put("1", 789)

	rt := m.ContainsKey("a")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt )
	}

	rt = m.ContainsKey("1")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s ", rt )
	}
}

func TestMapEmptyContainsKey (t *testing.T) {
	m := NewMap()

	rt := m.ContainsKey("a")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}

	rt = m.ContainsKey("1")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}
}

// *****************

func TestMapPutContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	rt := m.ContainsValue("ABC")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s" , rt )
	}

	rt = m.ContainsValue(123)
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt )
	}

}

func TestMapPutClearContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Clear()

	rt := m.ContainsValue("ABC")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}
	rt = m.ContainsValue(123)
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}
}

func TestMapPutRemoveContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Remove("a")
	m.Remove("1")

	rt := m.ContainsValue("ABC")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt)
	}

	rt = m.ContainsValue(123)
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}
}

func TestMapPutClearPutContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("1", 123)

	m.Clear()

	m.Put("a", "XYZ")
	m.Put("1", 789)

	rt := m.ContainsValue("XYZ")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt)
	}
	rt = m.ContainsValue(789)
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt)
	}
}

func TestMapPutPutContainsValue (t *testing.T) {
	m := NewMap()
	m.Put("a", "ABC")
	m.Put("a", "MNO")
	m.Put("a", "XYZ")
	m.Put("1", 123)
	m.Put("1", 456)
	m.Put("1", 789)

	rt := m.ContainsValue("XYZ")
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s", rt )
	}

	rt = m.ContainsValue(789)
	if rt != true {
		t.Errorf("expected value is not be correct. Expected: true Got: %s ", rt )
	}
}

func TestMapEmptyContainsValue (t *testing.T) {
	m := NewMap()

	rt := m.ContainsValue("ABC")
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}

	rt = m.ContainsValue(123)
	if rt != false {
		t.Errorf("expected value is not be correct. Expected: false Got: %s", rt )
	}
}
<|endoftext|>


<commit_before>package config

type Server struct {
	Name       string              `json:"-"`
	Connection *Connection         `json:"connection"`
	Login      *Login              `json:"login"`
	Messages   *Messages           `json:"messages"`
	Channels   map[string]*Channel `json:"-"`
}

type Connection struct {
	Address     string `json:"address"`
	SSL         bool   `json:"ssl"`
	Certificate bool   `json:"certificate"`
}

type Login struct {
	User     string    `json:"user"`
	Password string    `json:"password"`
	Name     string    `json:"name"`
	Ident    string    `json:"ident"`
	NickServ *NickServ `json:"nickserv"`
}

type NickServ struct {
	User     string `json:"name"`
	Password string `json:"password"`
}

type Messages struct {
	Version string `json:"version"`
	Quit    string `json:"quit"`
}

func NewServer(name string) *Server {
	return &Server{
		name,
		&Connection{
			SSL:         false,
			Certificate: true,
		},
		&Login{
			NickServ: &NickServ{},
		},
		&Messages{},
		nil,
	}
}
<commit_msg>Add bind host<commit_after>package config

type Server struct {
	Name       string              `json:"-"`
	Connection *Connection         `json:"connection"`
	Login      *Login              `json:"login"`
	Messages   *Messages           `json:"messages"`
	Channels   map[string]*Channel `json:"-"`
}

type Connection struct {
	Address     string `json:"address"`
	Bind        string `json:"bind"`
	SSL         bool   `json:"ssl"`
	Certificate bool   `json:"certificate"`
}

type Login struct {
	User     string    `json:"user"`
	Password string    `json:"password"`
	Name     string    `json:"name"`
	Ident    string    `json:"ident"`
	NickServ *NickServ `json:"nickserv"`
}

type NickServ struct {
	User     string `json:"name"`
	Password string `json:"password"`
}

type Messages struct {
	Version string `json:"version"`
	Quit    string `json:"quit"`
}

func NewServer(name string) *Server {
	return &Server{
		name,
		&Connection{
			SSL:         false,
			Certificate: true,
		},
		&Login{
			NickServ: &NickServ{},
		},
		&Messages{},
		nil,
	}
}
<|endoftext|>


<commit_before>package mackerel

import (
	"encoding/json"
	"fmt"
	"net/http"
)

/*
{
  "dashboards": [
	{
	  "id": "2c5bLca8d",
	  "title": "My Dashboard",
	  "bodyMarkdown": "# A test dashboard",
	  "urlPath": "2u4PP3TJqbu",
	  "createdAt": 1439346145003,
	  "updatedAt": 1439346145003
	}
  ]
}
*/

// Dashboard information
type Dashboard struct {
	ID           string `json:"id,omitempty"`
	Title        string `json:"title,omitempty"`
	BodyMarkDown string `json:"bodyMarkdown,omitempty"`
	URLPath      string `json:"urlPath,omitempty"`
	CreatedAt    int64  `json:"createdAt,omitempty"`
	UpdatedAt    int64  `json:"updatedAt,omitempty"`
	IsLegacy     bool   `json:"isLegacy,omitempty"`
	Memo         string `json:"memo,omitempty"`
}

// FindDashboards find dashboards
func (c *Client) FindDashboards() ([]*Dashboard, error) {
	req, err := http.NewRequest("GET", c.urlFor("/api/v0/dashboards").String(), nil)
	if err != nil {
		return nil, err
	}
	resp, err := c.Request(req)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data struct {
		Dashboards []*Dashboard `json:"dashboards"`
	}
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}

	return data.Dashboards, err
}

// FindDashboard find dashboard
func (c *Client) FindDashboard(dashboardID string) (*Dashboard, error) {
	req, err := http.NewRequest("GET", c.urlFor(fmt.Sprintf("/api/v0/dashboards/%s", dashboardID)).String(), nil)
	if err != nil {
		return nil, err
	}
	resp, err := c.Request(req)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data Dashboard
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}
	return &data, err
}

// CreateDashboard creating dashboard
func (c *Client) CreateDashboard(param *Dashboard) (*Dashboard, error) {
	resp, err := c.PostJSON("/api/v0/dashboards", param)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data Dashboard
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}
	return &data, nil
}

// UpdateDashboard update dashboard
func (c *Client) UpdateDashboard(dashboardID string, param *Dashboard) (*Dashboard, error) {
	resp, err := c.PutJSON(fmt.Sprintf("/api/v0/dashboards/%s", dashboardID), param)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data Dashboard
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}
	return &data, nil
}

// DeleteDashboard delete dashboard
func (c *Client) DeleteDashboard(dashboardID string) (*Dashboard, error) {
	req, err := http.NewRequest(
		"DELETE",
		c.urlFor(fmt.Sprintf("/api/v0/dashboards/%s", dashboardID)).String(),
		nil,
	)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")

	resp, err := c.Request(req)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data Dashboard
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}
	return &data, nil
}
<commit_msg>add struct for custom dashboard<commit_after>package mackerel

import (
	"encoding/json"
	"fmt"
	"net/http"
)

/*
{
  "dashboards": [
	{
	  "id": "2c5bLca8d",
	  "title": "My Dashboard",
	  "bodyMarkdown": "# A test dashboard",
	  "urlPath": "2u4PP3TJqbu",
	  "createdAt": 1439346145003,
	  "updatedAt": 1439346145003
	}
  ]
}
*/

// Dashboard information
type Dashboard struct {
	ID           string   `json:"id,omitempty"`
	Title        string   `json:"title,omitempty"`
	BodyMarkDown string   `json:"bodyMarkdown,omitempty"`
	URLPath      string   `json:"urlPath,omitempty"`
	CreatedAt    int64    `json:"createdAt,omitempty"`
	UpdatedAt    int64    `json:"updatedAt,omitempty"`
	IsLegacy     bool     `json:"isLegacy,omitempty"`
	Memo         string   `json:"memo,omitempty"`
	Widgets      []Widget `json:"widgets,omitenpty"`
}

// Widget information
type Widget struct {
	Type   string   `json:"type,omitempty"`
	Title  string   `json:"title,omitempty"`
	Metric []Metric `json:"metric,omitempty"`
	Graph  []Graph  `json:"graph,omitempty"`
	Layout []Layout `json:"layout,omitempty"`
}

// Metric information
type Metric struct {
}

// Graph information
type Graph struct {
}

// Layout information
type Layout struct {
}

// FindDashboards find dashboards
func (c *Client) FindDashboards() ([]*Dashboard, error) {
	req, err := http.NewRequest("GET", c.urlFor("/api/v0/dashboards").String(), nil)
	if err != nil {
		return nil, err
	}
	resp, err := c.Request(req)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data struct {
		Dashboards []*Dashboard `json:"dashboards"`
	}
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}

	return data.Dashboards, err
}

// FindDashboard find dashboard
func (c *Client) FindDashboard(dashboardID string) (*Dashboard, error) {
	req, err := http.NewRequest("GET", c.urlFor(fmt.Sprintf("/api/v0/dashboards/%s", dashboardID)).String(), nil)
	if err != nil {
		return nil, err
	}
	resp, err := c.Request(req)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data Dashboard
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}
	return &data, err
}

// CreateDashboard creating dashboard
func (c *Client) CreateDashboard(param *Dashboard) (*Dashboard, error) {
	resp, err := c.PostJSON("/api/v0/dashboards", param)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data Dashboard
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}
	return &data, nil
}

// UpdateDashboard update dashboard
func (c *Client) UpdateDashboard(dashboardID string, param *Dashboard) (*Dashboard, error) {
	resp, err := c.PutJSON(fmt.Sprintf("/api/v0/dashboards/%s", dashboardID), param)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data Dashboard
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}
	return &data, nil
}

// DeleteDashboard delete dashboard
func (c *Client) DeleteDashboard(dashboardID string) (*Dashboard, error) {
	req, err := http.NewRequest(
		"DELETE",
		c.urlFor(fmt.Sprintf("/api/v0/dashboards/%s", dashboardID)).String(),
		nil,
	)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")

	resp, err := c.Request(req)
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	var data Dashboard
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		return nil, err
	}
	return &data, nil
}
<|endoftext|>


<commit_before>package terraform

import (
	"reflect"
	"testing"
)

func TestEvalConfigProvider_impl(t *testing.T) {
	var _ EvalNode = new(EvalConfigProvider)
}

func TestEvalConfigProvider(t *testing.T) {
	config := testResourceConfig(t, map[string]interface{}{})
	provider := &MockResourceProvider{}
	n := &EvalConfigProvider{}

	ctx := &MockEvalContext{ProviderProvider: provider}
	args := []interface{}{config}
	if actual, err := n.Eval(ctx, args); err != nil {
		t.Fatalf("err: %s", err)
	} else if actual != nil {
		t.Fatalf("bad: %#v", actual)
	}

	if !provider.ConfigureCalled {
		t.Fatal("should be called")
	}
	if !reflect.DeepEqual(provider.ConfigureConfig, config) {
		t.Fatalf("bad: %#v", provider.ConfigureConfig)
	}
}

func TestEvalConfigProvider_args(t *testing.T) {
	config := testResourceConfig(t, map[string]interface{}{})
	configNode := &EvalLiteral{Value: config}
	n := &EvalConfigProvider{Provider: "foo", Config: configNode}

	args, types := n.Args()
	expectedArgs := []EvalNode{configNode}
	expectedTypes := []EvalType{EvalTypeConfig}
	if !reflect.DeepEqual(args, expectedArgs) {
		t.Fatalf("bad: %#v", args)
	}
	if !reflect.DeepEqual(types, expectedTypes) {
		t.Fatalf("bad: %#v", args)
	}
}

func TestEvalInitProvider_impl(t *testing.T) {
	var _ EvalNode = new(EvalInitProvider)
}

func TestEvalInitProvider(t *testing.T) {
	n := &EvalInitProvider{Name: "foo"}
	provider := &MockResourceProvider{}
	ctx := &MockEvalContext{InitProviderProvider: provider}
	if actual, err := n.Eval(ctx, nil); err != nil {
		t.Fatalf("err: %s", err)
	} else if actual != provider {
		t.Fatalf("bad: %#v", actual)
	}

	if !ctx.InitProviderCalled {
		t.Fatal("should be called")
	}
	if ctx.InitProviderName != "foo" {
		t.Fatalf("bad: %#v", ctx.InitProviderName)
	}
}

func TestEvalGetProvider_impl(t *testing.T) {
	var _ EvalNode = new(EvalGetProvider)
}

func TestEvalGetProvider(t *testing.T) {
	n := &EvalGetProvider{Name: "foo"}
	provider := &MockResourceProvider{}
	ctx := &MockEvalContext{ProviderProvider: provider}
	if actual, err := n.Eval(ctx, nil); err != nil {
		t.Fatalf("err: %s", err)
	} else if actual != provider {
		t.Fatalf("bad: %#v", actual)
	}

	if !ctx.ProviderCalled {
		t.Fatal("should be called")
	}
	if ctx.ProviderName != "foo" {
		t.Fatalf("bad: %#v", ctx.ProviderName)
	}
}
<commit_msg>terraform: fix failing tests<commit_after>package terraform

import (
	"reflect"
	"testing"
)

func TestEvalConfigProvider_impl(t *testing.T) {
	var _ EvalNode = new(EvalConfigProvider)
}

func TestEvalConfigProvider(t *testing.T) {
	config := testResourceConfig(t, map[string]interface{}{})
	provider := &MockResourceProvider{}
	n := &EvalConfigProvider{}

	ctx := &MockEvalContext{ProviderProvider: provider}
	args := []interface{}{config}
	if actual, err := n.Eval(ctx, args); err != nil {
		t.Fatalf("err: %s", err)
	} else if actual != nil {
		t.Fatalf("bad: %#v", actual)
	}

	if !ctx.ConfigureProviderCalled {
		t.Fatal("should be called")
	}
	if !reflect.DeepEqual(ctx.ConfigureProviderConfig, config) {
		t.Fatalf("bad: %#v", ctx.ConfigureProviderConfig)
	}
}

func TestEvalConfigProvider_args(t *testing.T) {
	config := testResourceConfig(t, map[string]interface{}{})
	configNode := &EvalLiteral{Value: config}
	n := &EvalConfigProvider{Provider: "foo", Config: configNode}

	args, types := n.Args()
	expectedArgs := []EvalNode{configNode}
	expectedTypes := []EvalType{EvalTypeConfig}
	if !reflect.DeepEqual(args, expectedArgs) {
		t.Fatalf("bad: %#v", args)
	}
	if !reflect.DeepEqual(types, expectedTypes) {
		t.Fatalf("bad: %#v", args)
	}
}

func TestEvalInitProvider_impl(t *testing.T) {
	var _ EvalNode = new(EvalInitProvider)
}

func TestEvalInitProvider(t *testing.T) {
	n := &EvalInitProvider{Name: "foo"}
	provider := &MockResourceProvider{}
	ctx := &MockEvalContext{InitProviderProvider: provider}
	if actual, err := n.Eval(ctx, nil); err != nil {
		t.Fatalf("err: %s", err)
	} else if actual != provider {
		t.Fatalf("bad: %#v", actual)
	}

	if !ctx.InitProviderCalled {
		t.Fatal("should be called")
	}
	if ctx.InitProviderName != "foo" {
		t.Fatalf("bad: %#v", ctx.InitProviderName)
	}
}

func TestEvalGetProvider_impl(t *testing.T) {
	var _ EvalNode = new(EvalGetProvider)
}

func TestEvalGetProvider(t *testing.T) {
	n := &EvalGetProvider{Name: "foo"}
	provider := &MockResourceProvider{}
	ctx := &MockEvalContext{ProviderProvider: provider}
	if actual, err := n.Eval(ctx, nil); err != nil {
		t.Fatalf("err: %s", err)
	} else if actual != provider {
		t.Fatalf("bad: %#v", actual)
	}

	if !ctx.ProviderCalled {
		t.Fatal("should be called")
	}
	if ctx.ProviderName != "foo" {
		t.Fatalf("bad: %#v", ctx.ProviderName)
	}
}
<|endoftext|>


<commit_before>package eval

import (
	"fmt"
	"reflect"

	"go/ast"
	"go/parser"
	"go/scanner"
)

var emptyEnv Env = MakeSimpleEnv()

func Eval(expr string) (result []reflect.Value, panik error, compileErrors []error) {
	return EvalEnv(expr, emptyEnv)
}

func EvalEnv(expr string, env Env) (result []reflect.Value, panik error, compileErrors []error) {
	if e, err := parser.ParseExpr(expr); err != nil {
		errs := err.(scanner.ErrorList)
		for i := range errs {
			compileErrors = append(compileErrors, errs[i])
		}
	} else if cexpr, errs := CheckExpr(e, env); errs != nil {
		compileErrors = errs
	} else {
		result, panik = EvalExpr(cexpr, env)
	}
	return
}

func Interpret(stmt string, env Env) (result []reflect.Value, panik error, compileErrors []error) {
	if s, err := ParseStmt(stmt); err != nil {
		if errs, ok := err.(scanner.ErrorList); ok {
			for i := range errs {
				compileErrors = append(compileErrors, errs[i])
			}
		} else {
			compileErrors = append(compileErrors, err)
		}
	} else if e, ok := s.(*ast.ExprStmt); ok {
		if cexpr, errs := CheckExpr(e.X, env); errs != nil {
			compileErrors = errs
		} else {
			result, panik = EvalExpr(cexpr, env)
		}
	} else {
		if cstmt, errs := CheckStmt(s, env); errs != nil {
			compileErrors = errs
		} else {
			panik = InterpStmt(cstmt, env)
		}
	}
	return
}

// A convenience function for parsing a Stmt by wrapping it in a func literal
func ParseStmt(stmt string) (ast.Stmt, error) {
	// parser.ParseExpr has some quirks, for example it won't parse unused map literals as
	// ExprStmts. Unused map literals are technically illegal, but it would be
	// nice to check them at a later stage. Therefore, we want to parse expressions
	// as expressions, and stmts and stmts. We try both.
	// However, there is a bug in parser.ParseExpr that it does not detect excess input.
	// Therefore, the _ of _ = 1 will be parsed as an expression. To avoid this, attempt
	// to parse the input as a statement first, and fall back to an expression
	expr := "func(){" + stmt + "}"
	if e, err := parser.ParseExpr(expr); err != nil {
		if e, err := parser.ParseExpr(stmt); err == nil {
			return &ast.ExprStmt{X: e}, nil
		}
		errs := err.(scanner.ErrorList)
		for i := range errs {
			errs[i].Pos.Offset -= 7 // len("func(){")
		}
		return nil, errs
	} else {
		node := e.(*ast.FuncLit).Body.List[0]
		if stmt, ok := node.(Stmt); !ok {
			return nil, fmt.Errorf("%T not supported", node)
		} else {
			return stmt, nil
		}
	}
}

<commit_msg>Fix Column in error positions.<commit_after>package eval

import (
	"fmt"
	"reflect"

	"go/ast"
	"go/parser"
	"go/scanner"
)

var emptyEnv Env = MakeSimpleEnv()

func Eval(expr string) (result []reflect.Value, panik error, compileErrors []error) {
	return EvalEnv(expr, emptyEnv)
}

func EvalEnv(expr string, env Env) (result []reflect.Value, panik error, compileErrors []error) {
	if e, err := parser.ParseExpr(expr); err != nil {
		errs := err.(scanner.ErrorList)
		for i := range errs {
			compileErrors = append(compileErrors, errs[i])
		}
	} else if cexpr, errs := CheckExpr(e, env); errs != nil {
		compileErrors = errs
	} else {
		result, panik = EvalExpr(cexpr, env)
	}
	return
}

func Interpret(stmt string, env Env) (result []reflect.Value, panik error, compileErrors []error) {
	if s, err := ParseStmt(stmt); err != nil {
		if errs, ok := err.(scanner.ErrorList); ok {
			for i := range errs {
				compileErrors = append(compileErrors, errs[i])
			}
		} else {
			compileErrors = append(compileErrors, err)
		}
	} else if e, ok := s.(*ast.ExprStmt); ok {
		if cexpr, errs := CheckExpr(e.X, env); errs != nil {
			compileErrors = errs
		} else {
			result, panik = EvalExpr(cexpr, env)
		}
	} else {
		if cstmt, errs := CheckStmt(s, env); errs != nil {
			compileErrors = errs
		} else {
			panik = InterpStmt(cstmt, env)
		}
	}
	return
}

// A convenience function for parsing a Stmt by wrapping it in a func literal
func ParseStmt(stmt string) (ast.Stmt, error) {
	// parser.ParseExpr has some quirks, for example it won't parse unused map literals as
	// ExprStmts. Unused map literals are technically illegal, but it would be
	// nice to check them at a later stage. Therefore, we want to parse expressions
	// as expressions, and stmts and stmts. We try both.
	// However, there is a bug in parser.ParseExpr that it does not detect excess input.
	// Therefore, the _ of _ = 1 will be parsed as an expression. To avoid this, attempt
	// to parse the input as a statement first, and fall back to an expression
	expr := "func(){" + stmt + ";}"
	if e, err := parser.ParseExpr(expr); err != nil {
		if e, err := parser.ParseExpr(stmt); err == nil {
			return &ast.ExprStmt{X: e}, nil
		}
		errs := err.(scanner.ErrorList)
		for i := range errs {
			errs[i].Pos.Offset -= 7
			errs[i].Pos.Column -= 7
		}
		return nil, errs
	} else {
		node := e.(*ast.FuncLit).Body.List[0]
		if stmt, ok := node.(Stmt); !ok {
			return nil, fmt.Errorf("%T not supported", node)
		} else {
			return stmt, nil
		}
	}
}

<|endoftext|>