<commit_before>package config_test

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"testing"

	"github.com/fly/config"
)

type testConfig struct {
	Example []string `yaml:"example"`
}

type burritoConfig struct {
	Location string `yaml:"location"`
	Burritos bool   `yaml:"burritos"`
}

// TODO: come up with a way to test homedir without hardcoding travis
const (
	correctEnvVar string = "TESTORG_TESTSYSTEM_CONFIG_URI"
	systemBaseDir string = "/etc/"
	systemDir     string = "/etc/testorg/testsystem/"
	systemPath    string = "/etc/testorg/testsystem/config.yaml"
	userBaseDir   string = "/home/travis/.config/"
	userDir       string = "/home/travis/"
	userPath      string = "/home/travis/.config/testorg/testsystem/config.yaml"
	organization  string = "testorg"
	system        string = "testsystem"
)

const (
	dirMode  os.FileMode = 0755
	fileMode os.FileMode = 0644
)

var cfgNS = config.Namespace{
	Organization: organization,
	System:       system,
}

// In this example our organization is named "testorganization", and our project
// namespace is "testsystem".
//
// In this example we have a file located at
// /Users/jchen/.config/testorganization/testsystem/config.yaml with the
// following contents:
//  example:
//    - "a"
//    - "b"
//    - "c"
func ExampleNamespace() {
	var err error
	var cfg testConfig
	var path string

	path = cfgNS.Path()
	fmt.Println("Path to config " + path)

	err = cfgNS.Load(&cfg)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println("Contents of cfg " + fmt.Sprint(cfg))
}

func TestExpandUser(t *testing.T) {
	var path string
	correctPath := userPath

	path = config.ExpandUser("~/.config/fly/config/config.yaml")

	if path != correctPath {
		t.Error("Expected ", correctPath, ", got ", path)
	}

	path = config.ExpandUser("$HOME/.config/fly/config/config.yaml")

	if path != correctPath {
		t.Error("Expected ", correctPath, ", got ", path)
	}
}

func TestLoad(t *testing.T) {
	correctDir := systemDir
	correctPath := systemPath
	var correctCfgText = `location: Señor Sisig
burritos: true`
	var correctCfg = burritoConfig{
		Location: "Señor Sisig",
		Burritos: true,
	}
	var err error
	var cfg burritoConfig

	// Setup
	os.RemoveAll(userPath)
	os.MkdirAll(correctDir, dirMode)
	err = ioutil.WriteFile(correctPath, []byte(correctCfgText), fileMode)
	if err != nil {
		t.Error("Got an error writing ", correctPath, ", got an error: ", err)
	}

	// Test
	err = config.Load(correctPath, &cfg)
	if err != nil {
		t.Error("Got an error: ", err, ", expecting nil")
	}

	if cfg != correctCfg {
		t.Error("Expecting ", correctCfg, ", got ", cfg)
	}

	err = config.Load(correctPath, cfg)
	if err.Error() != "config: not a pointer" {
		t.Error("Expecting error: config: not a pointer, instead got", err)
	}

	err = config.Load("rumpelstilzjchen", &cfg)
	if err == nil {
		t.Error("Expected read error, got nil")
	}

	// Teardown
	err = os.RemoveAll(correctPath)
	if err != nil {
		t.Error("Unable to remove file ", correctPath,
			" in teardown, got an error: ", err)
	}
}

func TestUserBase(t *testing.T) {
	if config.UserBase != userBaseDir {
		t.Error("Expecting ", userBaseDir, ", got ", config.UserBase)
	}
}

func TestSystemBase(t *testing.T) {
	if config.SystemBase != systemBaseDir {
		t.Error("Expecting ", systemBaseDir, ", got ", config.SystemBase)
	}
}

func TestNamespacePath(t *testing.T) {
	var err error
	var path string

	correctDir := systemDir
	correctPath := systemPath

	// Setup
	os.RemoveAll(userPath)
	os.MkdirAll(correctDir, dirMode)
	_, err = os.Create(correctPath)
	if err != nil {
		t.Error("Unable to create file ", correctPath, ", got an error: ", err)
	}

	// Test
	path = cfgNS.Path()
	if path != correctPath {
		t.Error("Expecting ", correctPath, ", got ", path)
	}

	// Teardown
	err = os.RemoveAll(correctPath)
	if err != nil {
		t.Error("Unable to remove file ", correctPath,
			" in teardown, got an error: ", err)
	}

	// test homedir
	// Setup
	correctDir = userDir
	correctPath = userPath
	os.RemoveAll(systemDir)
	os.MkdirAll(correctDir, dirMode)
	_, err = os.Create(correctPath)
	if err != nil {
		t.Error("Unable to create file ", correctPath, ", got an error: ", err)
	}

	// Test
	path = cfgNS.Path()
	if path != correctPath {
		t.Error("Expecting ", correctPath, ", got ", path)
	}

	// Teardown
	err = os.RemoveAll(correctPath)
	if err != nil {
		t.Error("Unable to remove file ", correctPath,
			" in teardown, got an error: ", err)
	}
}

func TestNamespaceEnvVar(t *testing.T) {
	if cfgNS.EnvVar() != correctEnvVar {
		t.Error("Expecting ", correctEnvVar, ", got ", cfgNS.EnvVar())
	}
}

func TestNamespaceLoad(t *testing.T) {
	correctDir := systemDir
	correctPath := systemPath

	correctCfgText := `location: Señor Sisig
burritos: true`
	correctCfg := burritoConfig{
		Location: "Señor Sisig",
		Burritos: true,
	}
	var err error
	var cfg burritoConfig

	// Setup
	os.RemoveAll(userPath)
	os.MkdirAll(correctDir, dirMode)
	err = ioutil.WriteFile(correctPath, []byte(correctCfgText), fileMode)
	if err != nil {
		t.Error("Got an error writing ", correctPath, ", got an error: ", err)
	}

	// Test
	err = cfgNS.Load(&cfg)
	if err != nil {
		t.Error("Got an error: ", err, ", expecting nil")
	}

	if cfg != correctCfg {
		t.Error("Expecting ", correctCfg, ", got ", cfg)
	}

	// Teardown
	err = os.RemoveAll(correctPath)
	if err != nil {
		t.Error("Unable to remove file ", correctPath,
			" in teardown, got an error: ", err)
	}
}
<commit_msg>fix test path<commit_after>package config_test

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"testing"

	"github.com/fly/config"
)

type testConfig struct {
	Example []string `yaml:"example"`
}

type burritoConfig struct {
	Location string `yaml:"location"`
	Burritos bool   `yaml:"burritos"`
}

// TODO: come up with a way to test homedir without hardcoding travis
const (
	correctEnvVar string = "TESTORG_TESTSYSTEM_CONFIG_URI"
	systemBaseDir string = "/etc/"
	systemDir     string = "/etc/testorg/testsystem/"
	systemPath    string = "/etc/testorg/testsystem/config.yaml"
	userBaseDir   string = "/home/travis/.config/"
	userDir       string = "/home/travis/"
	userPath      string = "/home/travis/.config/testorg/testsystem/config.yaml"
	organization  string = "testorg"
	system        string = "testsystem"
)

const (
	dirMode  os.FileMode = 0755
	fileMode os.FileMode = 0644
)

var cfgNS = config.Namespace{
	Organization: organization,
	System:       system,
}

// In this example our organization is named "testorganization", and our project
// namespace is "testsystem".
//
// In this example we have a file located at
// /Users/jchen/.config/testorg/testsystem/config.yaml with the
// following contents:
//  example:
//    - "a"
//    - "b"
//    - "c"
func ExampleNamespace() {
	var err error
	var cfg testConfig
	var path string

	path = cfgNS.Path()
	fmt.Println("Path to config " + path)

	err = cfgNS.Load(&cfg)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println("Contents of cfg " + fmt.Sprint(cfg))
}

func TestExpandUser(t *testing.T) {
	var path string
	correctPath := userPath

	path = config.ExpandUser("~/.config/testorg/testsystem/config.yaml")

	if path != correctPath {
		t.Error("Expected ", correctPath, ", got ", path)
	}

	path = config.ExpandUser("$HOME/.config/testorg/testsystem/config.yaml")

	if path != correctPath {
		t.Error("Expected ", correctPath, ", got ", path)
	}
}

func TestLoad(t *testing.T) {
	correctDir := systemDir
	correctPath := systemPath
	var correctCfgText = `location: Señor Sisig
burritos: true`
	var correctCfg = burritoConfig{
		Location: "Señor Sisig",
		Burritos: true,
	}
	var err error
	var cfg burritoConfig

	// Setup
	os.RemoveAll(userPath)
	os.MkdirAll(correctDir, dirMode)
	err = ioutil.WriteFile(correctPath, []byte(correctCfgText), fileMode)
	if err != nil {
		t.Error("Got an error writing ", correctPath, ", got an error: ", err)
	}

	// Test
	err = config.Load(correctPath, &cfg)
	if err != nil {
		t.Error("Got an error: ", err, ", expecting nil")
	}

	if cfg != correctCfg {
		t.Error("Expecting ", correctCfg, ", got ", cfg)
	}

	err = config.Load(correctPath, cfg)
	if err.Error() != "config: not a pointer" {
		t.Error("Expecting error: config: not a pointer, instead got", err)
	}

	err = config.Load("rumpelstilzjchen", &cfg)
	if err == nil {
		t.Error("Expected read error, got nil")
	}

	// Teardown
	err = os.RemoveAll(correctPath)
	if err != nil {
		t.Error("Unable to remove file ", correctPath,
			" in teardown, got an error: ", err)
	}
}

func TestUserBase(t *testing.T) {
	if config.UserBase != userBaseDir {
		t.Error("Expecting ", userBaseDir, ", got ", config.UserBase)
	}
}

func TestSystemBase(t *testing.T) {
	if config.SystemBase != systemBaseDir {
		t.Error("Expecting ", systemBaseDir, ", got ", config.SystemBase)
	}
}

func TestNamespacePath(t *testing.T) {
	var err error
	var path string

	correctDir := systemDir
	correctPath := systemPath

	// Setup
	os.RemoveAll(userPath)
	os.MkdirAll(correctDir, dirMode)
	_, err = os.Create(correctPath)
	if err != nil {
		t.Error("Unable to create file ", correctPath, ", got an error: ", err)
	}

	// Test
	path = cfgNS.Path()
	if path != correctPath {
		t.Error("Expecting ", correctPath, ", got ", path)
	}

	// Teardown
	err = os.RemoveAll(correctPath)
	if err != nil {
		t.Error("Unable to remove file ", correctPath,
			" in teardown, got an error: ", err)
	}

	// test homedir
	// Setup
	correctDir = userDir
	correctPath = userPath
	os.RemoveAll(systemDir)
	os.MkdirAll(correctDir, dirMode)
	_, err = os.Create(correctPath)
	if err != nil {
		t.Error("Unable to create file ", correctPath, ", got an error: ", err)
	}

	// Test
	path = cfgNS.Path()
	if path != correctPath {
		t.Error("Expecting ", correctPath, ", got ", path)
	}

	// Teardown
	err = os.RemoveAll(correctPath)
	if err != nil {
		t.Error("Unable to remove file ", correctPath,
			" in teardown, got an error: ", err)
	}
}

func TestNamespaceEnvVar(t *testing.T) {
	if cfgNS.EnvVar() != correctEnvVar {
		t.Error("Expecting ", correctEnvVar, ", got ", cfgNS.EnvVar())
	}
}

func TestNamespaceLoad(t *testing.T) {
	correctDir := systemDir
	correctPath := systemPath

	correctCfgText := `location: Señor Sisig
burritos: true`
	correctCfg := burritoConfig{
		Location: "Señor Sisig",
		Burritos: true,
	}
	var err error
	var cfg burritoConfig

	// Setup
	os.RemoveAll(userPath)
	os.MkdirAll(correctDir, dirMode)
	err = ioutil.WriteFile(correctPath, []byte(correctCfgText), fileMode)
	if err != nil {
		t.Error("Got an error writing ", correctPath, ", got an error: ", err)
	}

	// Test
	err = cfgNS.Load(&cfg)
	if err != nil {
		t.Error("Got an error: ", err, ", expecting nil")
	}

	if cfg != correctCfg {
		t.Error("Expecting ", correctCfg, ", got ", cfg)
	}

	// Teardown
	err = os.RemoveAll(correctPath)
	if err != nil {
		t.Error("Unable to remove file ", correctPath,
			" in teardown, got an error: ", err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"os"
	"path"
	"strings"
	"testing"
	"time"
)

// Test that file read errors are propagated up
func TestParseConfig_readFileError(t *testing.T) {
	_, err := ParseConfig(path.Join(os.TempDir(), "config.json"))
	if err == nil {
		t.Fatal("expected error, but nothing was returned")
	}

	expectedErr := "no such file or directory"
	if !strings.Contains(err.Error(), expectedErr) {
		t.Fatalf("expected error %q to contain %q", err.Error(), expectedErr)
	}
}

// Test that parser errors are propagated up
func TestParseConfig_parseFileError(t *testing.T) {
	configFile := createTempfile([]byte(`
    invalid file in here
  `), t)
	defer deleteTempfile(configFile, t)

	_, err := ParseConfig(configFile.Name())
	if err == nil {
		t.Fatal("expected error, but nothing was returned")
	}

	expectedErr := "syntax error"
	if !strings.Contains(err.Error(), expectedErr) {
		t.Fatalf("expected error %q to contain %q", err.Error(), expectedErr)
	}
}

// Test that mapstructure errors are propagated up
func TestParseConfig_mapstructureError(t *testing.T) {
	configFile := createTempfile([]byte(`
    consul = true
  `), t)
	defer deleteTempfile(configFile, t)

	_, err := ParseConfig(configFile.Name())
	if err == nil {
		t.Fatal("expected error, but nothing was returned")
	}

	expectedErr := "nconvertible type 'bool'"
	if !strings.Contains(err.Error(), expectedErr) {
		t.Fatalf("expected error %q to contain %q", err.Error(), expectedErr)
	}
}

// Test that the config reads the "consul" key
func TestParseConfig_readsConsulKey(t *testing.T) {
	configFile := createTempfile([]byte(`
    consul = "nyc1.demo.consul.io"
  `), t)
	defer deleteTempfile(configFile, t)

	config, err := ParseConfig(configFile.Name())
	if err != nil {
		t.Fatal(err)
	}

	expected := "nyc1.demo.consul.io"
	if config.Consul != expected {
		t.Fatalf("expected config.Consul to be %q, was %q", expected, config.Consul)
	}
}

// Test that the config reads the "template" keys
func TestParseConfig_readsTemplateKeys(t *testing.T) {
	configFile := createTempfile([]byte(`
    template {
      source = "nginx.conf.ctmpl"
      destination  = "/etc/nginx/nginx.conf"
    }

    template {
      source = "redis.conf.ctmpl"
      destination  = "/etc/redis/redis.conf"
      command = "service restart redis"
    }
  `), t)
	defer deleteTempfile(configFile, t)

	config, err := ParseConfig(configFile.Name())
	if err != nil {
		t.Fatal(err)
	}

	if len(config.ConfigTemplates) != 2 {
		t.Fatalf("expected 3 ConfigTemplates, but slice had %d", len(config.ConfigTemplates))
	}

	nginx := config.ConfigTemplates[0]
	expected := "nginx.conf.ctmpl"
	if nginx.Source != expected {
		t.Errorf("expected nginx.Source to be %q, was %q", expected, nginx.Source)
	}
	expected = "/etc/nginx/nginx.conf"
	if nginx.Destination != expected {
		t.Errorf("expected nginx.Destination to be %q, was %q", expected, nginx.Destination)
	}
	expected = ""
	if nginx.Command != expected {
		t.Errorf("expected nginx.Command to be %q, was %q", expected, nginx.Command)
	}

	redis := config.ConfigTemplates[1]
	expected = "redis.conf.ctmpl"
	if redis.Source != expected {
		t.Errorf("expected redis.Source to be %q, was %q", expected, redis.Source)
	}
	expected = "/etc/redis/redis.conf"
	if redis.Destination != expected {
		t.Errorf("expected redis.Destination to be %q, was %q", expected, redis.Destination)
	}
	expected = "service restart redis"
	if redis.Command != expected {
		t.Errorf("expected redis.Command to be %q, was %q", expected, redis.Command)
	}
}

// Test that the config reads the "token" key
func TestParseConfig_readsTokenKey(t *testing.T) {
	configFile := createTempfile([]byte(`
    token = "abcd1234"
  `), t)
	defer deleteTempfile(configFile, t)

	config, err := ParseConfig(configFile.Name())
	if err != nil {
		t.Fatal(err)
	}

	expected := "abcd1234"
	if config.Token != expected {
		t.Fatalf("expected config.Token to be %q, was %q", expected, config.Token)
	}
}

// Test that mapstructure does not propagate the "path" key from the config
// and properly sets it to the given path argument.
func TestParseConfig_setsPath(t *testing.T) {
	configFile := createTempfile([]byte(`
    path = "/path/to/config.json"
  `), t)
	defer deleteTempfile(configFile, t)

	config, err := ParseConfig(configFile.Name())
	if err != nil {
		t.Fatal(err)
	}

	expected := configFile.Name()
	if config.Path != expected {
		t.Fatalf("expected config.Path to be %q, was %q", expected, config.Token)
	}
}

// Test that the config reads the "wait" key
func TestParseConfig_readsWaitKey(t *testing.T) {
	configFile := createTempfile([]byte(`
    wait = "5s:10s"
  `), t)
	defer deleteTempfile(configFile, t)

	config, err := ParseConfig(configFile.Name())
	if err != nil {
		t.Fatal(err)
	}

	wait := config.Wait

	expectedMin := time.Duration(5) * time.Second
	if wait.Min != expectedMin {
		t.Errorf("expected %q to equal %q", wait.Min, expectedMin)
	}

	expectedMax := time.Duration(10) * time.Second
	if wait.Max != expectedMax {
		t.Errorf("expected %q to equal %q", wait.Max, expectedMin)
	}
}

// Test that ParseWait errors are propagated up
func TestParseConfig_parseWaitError(t *testing.T) {
	configFile := createTempfile([]byte(`
    wait = "not_valid:duration"
  `), t)
	defer deleteTempfile(configFile, t)

	_, err := ParseConfig(configFile.Name())
	if err == nil {
		t.Fatal("expected error, but nothing was returned")
	}

	expectedErr := "invalid duration not_valid"
	if !strings.Contains(err.Error(), expectedErr) {
		t.Fatalf("expected error %q to contain %q", err.Error(), expectedErr)
	}
}

// Test that the config reads the "once" key
func TestParseConfig_readsOnceKey(t *testing.T) {
	configFile := createTempfile([]byte(`
    once = true
  `), t)
	defer deleteTempfile(configFile, t)

	config, err := ParseConfig(configFile.Name())
	if err != nil {
		t.Fatal(err)
	}

	expected := true
	if config.Once != expected {
		t.Fatalf("expected config.Once to be %q, was %q", expected, config.Once)
	}
}
<commit_msg>Use reflect.DeepEqual to test config values<commit_after>package main

import (
	"os"
	"path"
	"reflect"
	"strings"
	"testing"
	"time"
)

// Test that file read errors are propagated up
func TestParseConfig_readFileError(t *testing.T) {
	_, err := ParseConfig(path.Join(os.TempDir(), "config.json"))
	if err == nil {
		t.Fatal("expected error, but nothing was returned")
	}

	expectedErr := "no such file or directory"
	if !strings.Contains(err.Error(), expectedErr) {
		t.Fatalf("expected error %q to contain %q", err.Error(), expectedErr)
	}
}

// Test that parser errors are propagated up
func TestParseConfig_parseFileError(t *testing.T) {
	configFile := createTempfile([]byte(`
    invalid file in here
  `), t)
	defer deleteTempfile(configFile, t)

	_, err := ParseConfig(configFile.Name())
	if err == nil {
		t.Fatal("expected error, but nothing was returned")
	}

	expectedErr := "syntax error"
	if !strings.Contains(err.Error(), expectedErr) {
		t.Fatalf("expected error %q to contain %q", err.Error(), expectedErr)
	}
}

// Test that mapstructure errors are propagated up
func TestParseConfig_mapstructureError(t *testing.T) {
	configFile := createTempfile([]byte(`
    consul = true
  `), t)
	defer deleteTempfile(configFile, t)

	_, err := ParseConfig(configFile.Name())
	if err == nil {
		t.Fatal("expected error, but nothing was returned")
	}

	expectedErr := "nconvertible type 'bool'"
	if !strings.Contains(err.Error(), expectedErr) {
		t.Fatalf("expected error %q to contain %q", err.Error(), expectedErr)
	}
}

// Test that the config is parsed correctly
func TestParseConfig_correctValues(t *testing.T) {
	configFile := createTempfile([]byte(`
    consul = "nyc1.demo.consul.io"
    token = "abcd1234"
    wait = "5s:10s"
    once = true

    template {
      source = "nginx.conf.ctmpl"
      destination  = "/etc/nginx/nginx.conf"
    }

    template {
      source = "redis.conf.ctmpl"
      destination  = "/etc/redis/redis.conf"
      command = "service redis restart"
    }
  `), t)
	defer deleteTempfile(configFile, t)

	config, err := ParseConfig(configFile.Name())
	if err != nil {
		t.Fatal(err)
	}

	expected := &Config{
		Path:   configFile.Name(),
		Consul: "nyc1.demo.consul.io",
		Token:  "abcd1234",
		Wait: &Wait{
			Min: time.Second * 5,
			Max: time.Second * 10,
		},
		WaitRaw: "5s:10s",
		Once:    true,
		ConfigTemplates: []*ConfigTemplate{
			&ConfigTemplate{
				Source:      "nginx.conf.ctmpl",
				Destination: "/etc/nginx/nginx.conf",
			},
			&ConfigTemplate{
				Source:      "redis.conf.ctmpl",
				Destination: "/etc/redis/redis.conf",
				Command:     "service redis restart",
			},
		},
	}
	if !reflect.DeepEqual(config, expected) {
		t.Fatalf("expected \n%#v\n\n, got \n\n%#v", expected, config)
	}
}

// Test that ParseWait errors are propagated up
func TestParseConfig_parseWaitError(t *testing.T) {
	configFile := createTempfile([]byte(`
    wait = "not_valid:duration"
  `), t)
	defer deleteTempfile(configFile, t)

	_, err := ParseConfig(configFile.Name())
	if err == nil {
		t.Fatal("expected error, but nothing was returned")
	}

	expectedErr := "invalid duration not_valid"
	if !strings.Contains(err.Error(), expectedErr) {
		t.Fatalf("expected error %q to contain %q", err.Error(), expectedErr)
	}
}
<|endoftext|>


<commit_before>package schema

import (
	"reflect"
	"testing"

	"github.com/hashicorp/terraform/terraform"
)

func TestDiffFieldReader_impl(t *testing.T) {
	var _ FieldReader = new(DiffFieldReader)
}

func TestDiffFieldReader_NestedSetUpdate(t *testing.T) {
	schema := map[string]*Schema{
		"list_of_sets_1": &Schema{
			Type: TypeList,
			Elem: &Resource{
				Schema: map[string]*Schema{
					"nested_set": &Schema{
						Type: TypeSet,
						Elem: &Resource{
							Schema: map[string]*Schema{
								"val": &Schema{
									Type: TypeInt,
								},
							},
						},
						Set: func(a interface{}) int {
							m := a.(map[string]interface{})
							return m["val"].(int)
						},
					},
				},
			},
		},
		"list_of_sets_2": &Schema{
			Type: TypeList,
			Elem: &Resource{
				Schema: map[string]*Schema{
					"nested_set": &Schema{
						Type: TypeSet,
						Elem: &Resource{
							Schema: map[string]*Schema{
								"val": &Schema{
									Type: TypeInt,
								},
							},
						},
						Set: func(a interface{}) int {
							m := a.(map[string]interface{})
							return m["val"].(int)
						},
					},
				},
			},
		},
	}

	r := &DiffFieldReader{
		Schema: schema,
		Diff: &terraform.InstanceDiff{
			Attributes: map[string]*terraform.ResourceAttrDiff{
				"list_of_sets_1.0.nested_set.1.val": &terraform.ResourceAttrDiff{
					Old:        "1",
					New:        "0",
					NewRemoved: true,
				},
				"list_of_sets_1.0.nested_set.2.val": &terraform.ResourceAttrDiff{
					New: "2",
				},
			},
		},
	}

	r.Source = &MultiLevelFieldReader{
		Readers: map[string]FieldReader{
			"diff": r,
			"set":  &MapFieldReader{Schema: schema},
			"state": &MapFieldReader{
				Map: &BasicMapReader{
					"list_of_sets_1.#":                  "1",
					"list_of_sets_1.0.nested_set.#":     "1",
					"list_of_sets_1.0.nested_set.1.val": "1",
					"list_of_sets_2.#":                  "1",
					"list_of_sets_2.0.nested_set.#":     "1",
					"list_of_sets_2.0.nested_set.1.val": "1",
				},
				Schema: schema,
			},
		},
		Levels: []string{"state", "config"},
	}

	out, err := r.ReadField([]string{"list_of_sets_2"})
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	list, ok := out.Value.([]interface{})
	if !ok {
		t.Fatalf("nestedSetUpdate: bad: Value type\n\nexpected: []interface{}\n\ngot: %v", reflect.TypeOf(out.Value))
	}
	if len(list) != 1 {
		t.Fatalf("nestedSetUpdate: bad: list length\n\nexpected: 1\n\ngot: %v\n\n", len(list))
	}

	var m map[string]interface{}
	m, ok = list[0].(map[string]interface{})
	if !ok {
		t.Fatalf("nestedSetUpdate: bad: list item type\n\nexpected: map[string]interface{}\n\ngot: %v\n\n", reflect.TypeOf(list[0]))
	}

	rawSet := m["nested_set"]
	if rawSet == nil {
		t.Fatalf("nestedSetUpdate: bad: nested_set\n\nexpected: not nil\n\ngot: nil\n\n")
	}

	var set *Set
	set, ok = rawSet.(*Set)
	if !ok {
		t.Fatalf("nestedSetUpdate: bad: nested set type\n\nexpected: *Set\n\ngot: %v\n\n", reflect.TypeOf(m["nested_set"]))
	}
	if set.Len() != 1 {
		t.Fatalf("nestedSetUpdate: bad: nested set length\n\nexpected: 1\n\ngot: %v\n\n", set.Len())
	}

	setList := set.List()
	var item map[string]interface{}
	item, ok = setList[0].(map[string]interface{})
	if !ok {
		t.Fatalf("nestedSetUpdate: bad: nested set item type\n\nexpected: map[string]interface{}\n\ngot: %v\n\n", reflect.TypeOf(setList[0]))
	}

	val := item["val"].(int)
	if val != 1 {
		t.Fatalf("nestedSetUpdate: bad: val\n\nexpected: 1\n\ngot: %v\n\n", val)
	}
}

// https://github.com/hashicorp/terraform/issues/914
func TestDiffFieldReader_MapHandling(t *testing.T) {
	schema := map[string]*Schema{
		"tags": &Schema{
			Type: TypeMap,
		},
	}
	r := &DiffFieldReader{
		Schema: schema,
		Diff: &terraform.InstanceDiff{
			Attributes: map[string]*terraform.ResourceAttrDiff{
				"tags.%": &terraform.ResourceAttrDiff{
					Old: "1",
					New: "2",
				},
				"tags.baz": &terraform.ResourceAttrDiff{
					Old: "",
					New: "qux",
				},
			},
		},
		Source: &MapFieldReader{
			Schema: schema,
			Map: BasicMapReader(map[string]string{
				"tags.%":   "1",
				"tags.foo": "bar",
			}),
		},
	}

	result, err := r.ReadField([]string{"tags"})
	if err != nil {
		t.Fatalf("ReadField failed: %#v", err)
	}

	expected := map[string]interface{}{
		"foo": "bar",
		"baz": "qux",
	}

	if !reflect.DeepEqual(expected, result.Value) {
		t.Fatalf("bad: DiffHandling\n\nexpected: %#v\n\ngot: %#v\n\n", expected, result.Value)
	}
}

func TestDiffFieldReader_extra(t *testing.T) {
	schema := map[string]*Schema{
		"stringComputed": &Schema{Type: TypeString},

		"listMap": &Schema{
			Type: TypeList,
			Elem: &Schema{
				Type: TypeMap,
			},
		},

		"mapRemove": &Schema{Type: TypeMap},

		"setChange": &Schema{
			Type:     TypeSet,
			Optional: true,
			Elem: &Resource{
				Schema: map[string]*Schema{
					"index": &Schema{
						Type:     TypeInt,
						Required: true,
					},

					"value": &Schema{
						Type:     TypeString,
						Required: true,
					},
				},
			},
			Set: func(a interface{}) int {
				m := a.(map[string]interface{})
				return m["index"].(int)
			},
		},

		"setEmpty": &Schema{
			Type:     TypeSet,
			Optional: true,
			Elem: &Resource{
				Schema: map[string]*Schema{
					"index": &Schema{
						Type:     TypeInt,
						Required: true,
					},

					"value": &Schema{
						Type:     TypeString,
						Required: true,
					},
				},
			},
			Set: func(a interface{}) int {
				m := a.(map[string]interface{})
				return m["index"].(int)
			},
		},
	}

	r := &DiffFieldReader{
		Schema: schema,
		Diff: &terraform.InstanceDiff{
			Attributes: map[string]*terraform.ResourceAttrDiff{
				"stringComputed": &terraform.ResourceAttrDiff{
					Old:         "foo",
					New:         "bar",
					NewComputed: true,
				},

				"listMap.0.bar": &terraform.ResourceAttrDiff{
					NewRemoved: true,
				},

				"mapRemove.bar": &terraform.ResourceAttrDiff{
					NewRemoved: true,
				},

				"setChange.10.value": &terraform.ResourceAttrDiff{
					Old: "50",
					New: "80",
				},

				"setEmpty.#": &terraform.ResourceAttrDiff{
					Old: "2",
					New: "0",
				},
			},
		},

		Source: &MapFieldReader{
			Schema: schema,
			Map: BasicMapReader(map[string]string{
				"listMap.#":     "2",
				"listMap.0.foo": "bar",
				"listMap.0.bar": "baz",
				"listMap.1.baz": "baz",

				"mapRemove.foo": "bar",
				"mapRemove.bar": "bar",

				"setChange.#":        "1",
				"setChange.10.index": "10",
				"setChange.10.value": "50",

				"setEmpty.#":        "2",
				"setEmpty.10.index": "10",
				"setEmpty.10.value": "50",
				"setEmpty.20.index": "20",
				"setEmpty.20.value": "50",
			}),
		},
	}

	cases := map[string]struct {
		Addr   []string
		Result FieldReadResult
		Err    bool
	}{
		"stringComputed": {
			[]string{"stringComputed"},
			FieldReadResult{
				Value:    "",
				Exists:   true,
				Computed: true,
			},
			false,
		},

		"listMapRemoval": {
			[]string{"listMap"},
			FieldReadResult{
				Value: []interface{}{
					map[string]interface{}{
						"foo": "bar",
					},
					map[string]interface{}{
						"baz": "baz",
					},
				},
				Exists: true,
			},
			false,
		},

		"mapRemove": {
			[]string{"mapRemove"},
			FieldReadResult{
				Value: map[string]interface{}{
					"foo": "bar",
				},
				Exists:   true,
				Computed: false,
			},
			false,
		},

		"setChange": {
			[]string{"setChange"},
			FieldReadResult{
				Value: []interface{}{
					map[string]interface{}{
						"index": 10,
						"value": "80",
					},
				},
				Exists: true,
			},
			false,
		},

		"setEmpty": {
			[]string{"setEmpty"},
			FieldReadResult{
				Value:  []interface{}{},
				Exists: true,
			},
			false,
		},
	}

	for name, tc := range cases {
		out, err := r.ReadField(tc.Addr)
		if err != nil != tc.Err {
			t.Fatalf("%s: err: %s", name, err)
		}
		if s, ok := out.Value.(*Set); ok {
			// If it is a set, convert to a list so its more easily checked.
			out.Value = s.List()
		}
		if !reflect.DeepEqual(tc.Result, out) {
			t.Fatalf("%s: bad: %#v", name, out)
		}
	}
}

func TestDiffFieldReader(t *testing.T) {
	testFieldReader(t, func(s map[string]*Schema) FieldReader {
		return &DiffFieldReader{
			Schema: s,
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"bool": &terraform.ResourceAttrDiff{
						Old: "",
						New: "true",
					},

					"int": &terraform.ResourceAttrDiff{
						Old: "",
						New: "42",
					},

					"float": &terraform.ResourceAttrDiff{
						Old: "",
						New: "3.1415",
					},

					"string": &terraform.ResourceAttrDiff{
						Old: "",
						New: "string",
					},

					"stringComputed": &terraform.ResourceAttrDiff{
						Old:         "foo",
						New:         "bar",
						NewComputed: true,
					},

					"list.#": &terraform.ResourceAttrDiff{
						Old: "0",
						New: "2",
					},

					"list.0": &terraform.ResourceAttrDiff{
						Old: "",
						New: "foo",
					},

					"list.1": &terraform.ResourceAttrDiff{
						Old: "",
						New: "bar",
					},

					"listInt.#": &terraform.ResourceAttrDiff{
						Old: "0",
						New: "2",
					},

					"listInt.0": &terraform.ResourceAttrDiff{
						Old: "",
						New: "21",
					},

					"listInt.1": &terraform.ResourceAttrDiff{
						Old: "",
						New: "42",
					},

					"map.foo": &terraform.ResourceAttrDiff{
						Old: "",
						New: "bar",
					},

					"map.bar": &terraform.ResourceAttrDiff{
						Old: "",
						New: "baz",
					},

					"set.#": &terraform.ResourceAttrDiff{
						Old: "0",
						New: "2",
					},

					"set.10": &terraform.ResourceAttrDiff{
						Old: "",
						New: "10",
					},

					"set.50": &terraform.ResourceAttrDiff{
						Old: "",
						New: "50",
					},

					"setDeep.#": &terraform.ResourceAttrDiff{
						Old: "0",
						New: "2",
					},

					"setDeep.10.index": &terraform.ResourceAttrDiff{
						Old: "",
						New: "10",
					},

					"setDeep.10.value": &terraform.ResourceAttrDiff{
						Old: "",
						New: "foo",
					},

					"setDeep.50.index": &terraform.ResourceAttrDiff{
						Old: "",
						New: "50",
					},

					"setDeep.50.value": &terraform.ResourceAttrDiff{
						Old: "",
						New: "bar",
					},
				},
			},

			Source: &MapFieldReader{
				Schema: s,
				Map: BasicMapReader(map[string]string{
					"listMap.#":     "2",
					"listMap.0.foo": "bar",
					"listMap.0.bar": "baz",
					"listMap.1.baz": "baz",
				}),
			},
		}
	})
}
<commit_msg>Use DeepEqual instead of multiple if statements to reduce noise.<commit_after>package schema

import (
	"reflect"
	"testing"

	"github.com/hashicorp/terraform/terraform"
)

func TestDiffFieldReader_impl(t *testing.T) {
	var _ FieldReader = new(DiffFieldReader)
}

func TestDiffFieldReader_NestedSetUpdate(t *testing.T) {
	hashFn := func(a interface{}) int {
		m := a.(map[string]interface{})
		return m["val"].(int)
	}

	schema := map[string]*Schema{
		"list_of_sets_1": &Schema{
			Type: TypeList,
			Elem: &Resource{
				Schema: map[string]*Schema{
					"nested_set": &Schema{
						Type: TypeSet,
						Elem: &Resource{
							Schema: map[string]*Schema{
								"val": &Schema{
									Type: TypeInt,
								},
							},
						},
						Set: hashFn,
					},
				},
			},
		},
		"list_of_sets_2": &Schema{
			Type: TypeList,
			Elem: &Resource{
				Schema: map[string]*Schema{
					"nested_set": &Schema{
						Type: TypeSet,
						Elem: &Resource{
							Schema: map[string]*Schema{
								"val": &Schema{
									Type: TypeInt,
								},
							},
						},
						Set: hashFn,
					},
				},
			},
		},
	}

	r := &DiffFieldReader{
		Schema: schema,
		Diff: &terraform.InstanceDiff{
			Attributes: map[string]*terraform.ResourceAttrDiff{
				"list_of_sets_1.0.nested_set.1.val": &terraform.ResourceAttrDiff{
					Old:        "1",
					New:        "0",
					NewRemoved: true,
				},
				"list_of_sets_1.0.nested_set.2.val": &terraform.ResourceAttrDiff{
					New: "2",
				},
			},
		},
	}

	r.Source = &MultiLevelFieldReader{
		Readers: map[string]FieldReader{
			"diff": r,
			"set":  &MapFieldReader{Schema: schema},
			"state": &MapFieldReader{
				Map: &BasicMapReader{
					"list_of_sets_1.#":                  "1",
					"list_of_sets_1.0.nested_set.#":     "1",
					"list_of_sets_1.0.nested_set.1.val": "1",
					"list_of_sets_2.#":                  "1",
					"list_of_sets_2.0.nested_set.#":     "1",
					"list_of_sets_2.0.nested_set.1.val": "1",
				},
				Schema: schema,
			},
		},
		Levels: []string{"state", "config"},
	}

	out, err := r.ReadField([]string{"list_of_sets_2"})
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	s := &Set{F: hashFn}
	s.Add(map[string]interface{}{"val": 1})
	expected := s.List()

	l := out.Value.([]interface{})
	i := l[0].(map[string]interface{})
	actual := i["nested_set"].(*Set).List()

	if !reflect.DeepEqual(expected, actual) {
		t.Fatalf("bad: NestedSetUpdate\n\nexpected: %#v\n\ngot: %#v\n\n", expected, actual)
	}
}

// https://github.com/hashicorp/terraform/issues/914
func TestDiffFieldReader_MapHandling(t *testing.T) {
	schema := map[string]*Schema{
		"tags": &Schema{
			Type: TypeMap,
		},
	}
	r := &DiffFieldReader{
		Schema: schema,
		Diff: &terraform.InstanceDiff{
			Attributes: map[string]*terraform.ResourceAttrDiff{
				"tags.%": &terraform.ResourceAttrDiff{
					Old: "1",
					New: "2",
				},
				"tags.baz": &terraform.ResourceAttrDiff{
					Old: "",
					New: "qux",
				},
			},
		},
		Source: &MapFieldReader{
			Schema: schema,
			Map: BasicMapReader(map[string]string{
				"tags.%":   "1",
				"tags.foo": "bar",
			}),
		},
	}

	result, err := r.ReadField([]string{"tags"})
	if err != nil {
		t.Fatalf("ReadField failed: %#v", err)
	}

	expected := map[string]interface{}{
		"foo": "bar",
		"baz": "qux",
	}

	if !reflect.DeepEqual(expected, result.Value) {
		t.Fatalf("bad: DiffHandling\n\nexpected: %#v\n\ngot: %#v\n\n", expected, result.Value)
	}
}

func TestDiffFieldReader_extra(t *testing.T) {
	schema := map[string]*Schema{
		"stringComputed": &Schema{Type: TypeString},

		"listMap": &Schema{
			Type: TypeList,
			Elem: &Schema{
				Type: TypeMap,
			},
		},

		"mapRemove": &Schema{Type: TypeMap},

		"setChange": &Schema{
			Type:     TypeSet,
			Optional: true,
			Elem: &Resource{
				Schema: map[string]*Schema{
					"index": &Schema{
						Type:     TypeInt,
						Required: true,
					},

					"value": &Schema{
						Type:     TypeString,
						Required: true,
					},
				},
			},
			Set: func(a interface{}) int {
				m := a.(map[string]interface{})
				return m["index"].(int)
			},
		},

		"setEmpty": &Schema{
			Type:     TypeSet,
			Optional: true,
			Elem: &Resource{
				Schema: map[string]*Schema{
					"index": &Schema{
						Type:     TypeInt,
						Required: true,
					},

					"value": &Schema{
						Type:     TypeString,
						Required: true,
					},
				},
			},
			Set: func(a interface{}) int {
				m := a.(map[string]interface{})
				return m["index"].(int)
			},
		},
	}

	r := &DiffFieldReader{
		Schema: schema,
		Diff: &terraform.InstanceDiff{
			Attributes: map[string]*terraform.ResourceAttrDiff{
				"stringComputed": &terraform.ResourceAttrDiff{
					Old:         "foo",
					New:         "bar",
					NewComputed: true,
				},

				"listMap.0.bar": &terraform.ResourceAttrDiff{
					NewRemoved: true,
				},

				"mapRemove.bar": &terraform.ResourceAttrDiff{
					NewRemoved: true,
				},

				"setChange.10.value": &terraform.ResourceAttrDiff{
					Old: "50",
					New: "80",
				},

				"setEmpty.#": &terraform.ResourceAttrDiff{
					Old: "2",
					New: "0",
				},
			},
		},

		Source: &MapFieldReader{
			Schema: schema,
			Map: BasicMapReader(map[string]string{
				"listMap.#":     "2",
				"listMap.0.foo": "bar",
				"listMap.0.bar": "baz",
				"listMap.1.baz": "baz",

				"mapRemove.foo": "bar",
				"mapRemove.bar": "bar",

				"setChange.#":        "1",
				"setChange.10.index": "10",
				"setChange.10.value": "50",

				"setEmpty.#":        "2",
				"setEmpty.10.index": "10",
				"setEmpty.10.value": "50",
				"setEmpty.20.index": "20",
				"setEmpty.20.value": "50",
			}),
		},
	}

	cases := map[string]struct {
		Addr   []string
		Result FieldReadResult
		Err    bool
	}{
		"stringComputed": {
			[]string{"stringComputed"},
			FieldReadResult{
				Value:    "",
				Exists:   true,
				Computed: true,
			},
			false,
		},

		"listMapRemoval": {
			[]string{"listMap"},
			FieldReadResult{
				Value: []interface{}{
					map[string]interface{}{
						"foo": "bar",
					},
					map[string]interface{}{
						"baz": "baz",
					},
				},
				Exists: true,
			},
			false,
		},

		"mapRemove": {
			[]string{"mapRemove"},
			FieldReadResult{
				Value: map[string]interface{}{
					"foo": "bar",
				},
				Exists:   true,
				Computed: false,
			},
			false,
		},

		"setChange": {
			[]string{"setChange"},
			FieldReadResult{
				Value: []interface{}{
					map[string]interface{}{
						"index": 10,
						"value": "80",
					},
				},
				Exists: true,
			},
			false,
		},

		"setEmpty": {
			[]string{"setEmpty"},
			FieldReadResult{
				Value:  []interface{}{},
				Exists: true,
			},
			false,
		},
	}

	for name, tc := range cases {
		out, err := r.ReadField(tc.Addr)
		if err != nil != tc.Err {
			t.Fatalf("%s: err: %s", name, err)
		}
		if s, ok := out.Value.(*Set); ok {
			// If it is a set, convert to a list so its more easily checked.
			out.Value = s.List()
		}
		if !reflect.DeepEqual(tc.Result, out) {
			t.Fatalf("%s: bad: %#v", name, out)
		}
	}
}

func TestDiffFieldReader(t *testing.T) {
	testFieldReader(t, func(s map[string]*Schema) FieldReader {
		return &DiffFieldReader{
			Schema: s,
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"bool": &terraform.ResourceAttrDiff{
						Old: "",
						New: "true",
					},

					"int": &terraform.ResourceAttrDiff{
						Old: "",
						New: "42",
					},

					"float": &terraform.ResourceAttrDiff{
						Old: "",
						New: "3.1415",
					},

					"string": &terraform.ResourceAttrDiff{
						Old: "",
						New: "string",
					},

					"stringComputed": &terraform.ResourceAttrDiff{
						Old:         "foo",
						New:         "bar",
						NewComputed: true,
					},

					"list.#": &terraform.ResourceAttrDiff{
						Old: "0",
						New: "2",
					},

					"list.0": &terraform.ResourceAttrDiff{
						Old: "",
						New: "foo",
					},

					"list.1": &terraform.ResourceAttrDiff{
						Old: "",
						New: "bar",
					},

					"listInt.#": &terraform.ResourceAttrDiff{
						Old: "0",
						New: "2",
					},

					"listInt.0": &terraform.ResourceAttrDiff{
						Old: "",
						New: "21",
					},

					"listInt.1": &terraform.ResourceAttrDiff{
						Old: "",
						New: "42",
					},

					"map.foo": &terraform.ResourceAttrDiff{
						Old: "",
						New: "bar",
					},

					"map.bar": &terraform.ResourceAttrDiff{
						Old: "",
						New: "baz",
					},

					"set.#": &terraform.ResourceAttrDiff{
						Old: "0",
						New: "2",
					},

					"set.10": &terraform.ResourceAttrDiff{
						Old: "",
						New: "10",
					},

					"set.50": &terraform.ResourceAttrDiff{
						Old: "",
						New: "50",
					},

					"setDeep.#": &terraform.ResourceAttrDiff{
						Old: "0",
						New: "2",
					},

					"setDeep.10.index": &terraform.ResourceAttrDiff{
						Old: "",
						New: "10",
					},

					"setDeep.10.value": &terraform.ResourceAttrDiff{
						Old: "",
						New: "foo",
					},

					"setDeep.50.index": &terraform.ResourceAttrDiff{
						Old: "",
						New: "50",
					},

					"setDeep.50.value": &terraform.ResourceAttrDiff{
						Old: "",
						New: "bar",
					},
				},
			},

			Source: &MapFieldReader{
				Schema: s,
				Map: BasicMapReader(map[string]string{
					"listMap.#":     "2",
					"listMap.0.foo": "bar",
					"listMap.0.bar": "baz",
					"listMap.1.baz": "baz",
				}),
			},
		}
	})
}
<|endoftext|>


<commit_before>// Copyright 2017 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build js

package audio

import (
	"github.com/hajimehoshi/ebiten/internal/web"
)

func (c *Context) bufferSize() int {
	// TODO: examples/audio doesn't work well with 1/30[s],
	// the other examples work though. Fix this.
	n := 20
	if web.IsMobileBrowser() {
		n = 10
	}
	return c.sampleRate * channelNum * bytesPerSample / n
}
<commit_msg>audio: Fix comment<commit_after>// Copyright 2017 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build js

package audio

import (
	"github.com/hajimehoshi/ebiten/internal/web"
)

func (c *Context) bufferSize() int {
	// TODO: On Chrome and Firefox, 1/30[s] doesn't work with 24000 or 48000 [Hz]
	// at least on macOS.
	n := 20
	if web.IsMobileBrowser() {
		n = 10
	}
	return c.sampleRate * channelNum * bytesPerSample / n
}
<|endoftext|>


<commit_before>// Copyright 2015 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package vorbis provides Ogg/Vorbis decoder.
package vorbis

import (
	"fmt"
	"io"

	"github.com/jfreymuth/oggvorbis"

	"github.com/hajimehoshi/ebiten/v2/audio"
	"github.com/hajimehoshi/ebiten/v2/audio/internal/convert"
)

// Stream is a decoded audio stream.
type Stream struct {
	decoded io.ReadSeeker
	size    int64
}

// Read is implementation of io.Reader's Read.
func (s *Stream) Read(p []byte) (int, error) {
	return s.decoded.Read(p)
}

// Seek is implementation of io.Seeker's Seek.
//
// Note that Seek can take long since decoding is a relatively heavy task.
func (s *Stream) Seek(offset int64, whence int) (int64, error) {
	return s.decoded.Seek(offset, whence)
}

// Length returns the size of decoded stream in bytes.
func (s *Stream) Length() int64 {
	return s.size
}

type decoder interface {
	Read([]float32) (int, error)
	SetPosition(int64) error
	Length() int64
	Channels() int
	SampleRate() int
}

type decoded struct {
	totalBytes int
	posInBytes int
	decoder    decoder
	decoderr   io.Reader
}

func (d *decoded) Read(b []byte) (int, error) {
	if d.decoderr == nil {
		d.decoderr = convert.NewReaderFromFloat32Reader(d.decoder)
	}

	l := d.totalBytes - d.posInBytes
	if l > len(b) {
		l = len(b)
	}
	if l < 0 {
		return 0, io.EOF
	}

retry:
	n, err := d.decoderr.Read(b[:l])
	if err != nil && err != io.EOF {
		return 0, err
	}
	if n == 0 && l > 0 && err != io.EOF {
		// When l is too small, decoder's Read might return 0 for a while. Let's retry.
		goto retry
	}

	d.posInBytes += n
	if d.posInBytes == d.totalBytes || err == io.EOF {
		return n, io.EOF
	}
	return n, nil
}

func (d *decoded) Seek(offset int64, whence int) (int64, error) {
	next := int64(0)
	switch whence {
	case io.SeekStart:
		next = offset
	case io.SeekCurrent:
		next = int64(d.posInBytes) + offset
	case io.SeekEnd:
		next = int64(d.totalBytes) + offset
	}
	// pos should be always even
	next = next / 2 * 2
	d.posInBytes = int(next)
	d.decoder.SetPosition(next / int64(d.decoder.Channels()) / 2)
	d.decoderr = nil
	return next, nil
}

func (d *decoded) Length() int64 {
	return int64(d.totalBytes)
}

// decode accepts an ogg stream and returns a decorded stream.
func decode(in io.Reader) (*decoded, int, int, error) {
	r, err := oggvorbis.NewReader(in)
	if err != nil {
		return nil, 0, 0, err
	}
	d := &decoded{
		// TODO: r.Length() returns 0 when the format is unknown.
		// Should we check that?
		totalBytes: int(r.Length()) * r.Channels() * 2, // 2 means 16bit per sample.
		posInBytes: 0,
		decoder:    r,
	}
	if _, err := d.Read(make([]byte, 65536)); err != nil && err != io.EOF {
		return nil, 0, 0, err
	}
	if _, err := d.Seek(0, io.SeekStart); err != nil {
		return nil, 0, 0, err
	}
	return d, r.Channels(), r.SampleRate(), nil
}

// DecodeWithSampleRate decodes Ogg/Vorbis data to playable stream.
//
// DecodeWithSampleRate returns error when decoding fails or IO error happens.
//
// DecodeWithSampleRate automatically resamples the stream to fit with sampleRate if necessary.
//
// The returned Stream's Seek is available only when src is an io.Seeker.
//
// A Stream doesn't close src even if src implements io.Closer.
// Closing the source is src owner's responsibility.
func DecodeWithSampleRate(sampleRate int, src io.Reader) (*Stream, error) {
	decoded, channelNum, origSampleRate, err := decode(src)
	if err != nil {
		return nil, err
	}
	if channelNum != 1 && channelNum != 2 {
		return nil, fmt.Errorf("vorbis: number of channels must be 1 or 2 but was %d", channelNum)
	}
	var s io.ReadSeeker = decoded
	size := decoded.Length()
	if channelNum == 1 {
		s = convert.NewStereo16(s, true, false)
		size *= 2
	}
	if origSampleRate != sampleRate {
		r := convert.NewResampling(s, size, origSampleRate, sampleRate)
		s = r
		size = r.Length()
	}
	stream := &Stream{decoded: s, size: size}
	return stream, nil
}

// Decode decodes Ogg/Vorbis data to playable stream.
//
// Decode returns error when decoding fails or IO error happens.
//
// Decode automatically resamples the stream to fit with the audio context if necessary.
//
// The returned Stream's Seek is available only when src is an io.Seeker.
//
// A Stream doesn't close src even if src implements io.Closer.
// Closing the source is src owner's responsibility.
//
// Deprecated: as of v2.1. Use DecodeWithSampleRate instead.
func Decode(context *audio.Context, src io.Reader) (*Stream, error) {
	return DecodeWithSampleRate(context.SampleRate(), src)
}
<commit_msg>audio/vorbis: Catch the Seek error<commit_after>// Copyright 2015 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package vorbis provides Ogg/Vorbis decoder.
package vorbis

import (
	"fmt"
	"io"

	"github.com/jfreymuth/oggvorbis"

	"github.com/hajimehoshi/ebiten/v2/audio"
	"github.com/hajimehoshi/ebiten/v2/audio/internal/convert"
)

// Stream is a decoded audio stream.
type Stream struct {
	decoded io.ReadSeeker
	size    int64
}

// Read is implementation of io.Reader's Read.
func (s *Stream) Read(p []byte) (int, error) {
	return s.decoded.Read(p)
}

// Seek is implementation of io.Seeker's Seek.
//
// Note that Seek can take long since decoding is a relatively heavy task.
func (s *Stream) Seek(offset int64, whence int) (int64, error) {
	return s.decoded.Seek(offset, whence)
}

// Length returns the size of decoded stream in bytes.
func (s *Stream) Length() int64 {
	return s.size
}

type decoder interface {
	Read([]float32) (int, error)
	SetPosition(int64) error
	Length() int64
	Channels() int
	SampleRate() int
}

type decoded struct {
	totalBytes int
	posInBytes int
	decoder    decoder
	decoderr   io.Reader
}

func (d *decoded) Read(b []byte) (int, error) {
	if d.decoderr == nil {
		d.decoderr = convert.NewReaderFromFloat32Reader(d.decoder)
	}

	l := d.totalBytes - d.posInBytes
	if l > len(b) {
		l = len(b)
	}
	if l < 0 {
		return 0, io.EOF
	}

retry:
	n, err := d.decoderr.Read(b[:l])
	if err != nil && err != io.EOF {
		return 0, err
	}
	if n == 0 && l > 0 && err != io.EOF {
		// When l is too small, decoder's Read might return 0 for a while. Let's retry.
		goto retry
	}

	d.posInBytes += n
	if d.posInBytes == d.totalBytes || err == io.EOF {
		return n, io.EOF
	}
	return n, nil
}

func (d *decoded) Seek(offset int64, whence int) (int64, error) {
	next := int64(0)
	switch whence {
	case io.SeekStart:
		next = offset
	case io.SeekCurrent:
		next = int64(d.posInBytes) + offset
	case io.SeekEnd:
		next = int64(d.totalBytes) + offset
	}
	// pos should be always even
	next = next / 2 * 2
	d.posInBytes = int(next)
	if err := d.decoder.SetPosition(next / int64(d.decoder.Channels()) / 2); err != nil {
		return 0, err
	}
	d.decoderr = nil
	return next, nil
}

func (d *decoded) Length() int64 {
	return int64(d.totalBytes)
}

// decode accepts an ogg stream and returns a decorded stream.
func decode(in io.Reader) (*decoded, int, int, error) {
	r, err := oggvorbis.NewReader(in)
	if err != nil {
		return nil, 0, 0, err
	}
	d := &decoded{
		// TODO: r.Length() returns 0 when the format is unknown.
		// Should we check that?
		totalBytes: int(r.Length()) * r.Channels() * 2, // 2 means 16bit per sample.
		posInBytes: 0,
		decoder:    r,
	}
	if _, err := d.Read(make([]byte, 65536)); err != nil && err != io.EOF {
		return nil, 0, 0, err
	}
	if _, err := d.Seek(0, io.SeekStart); err != nil {
		return nil, 0, 0, err
	}
	return d, r.Channels(), r.SampleRate(), nil
}

// DecodeWithSampleRate decodes Ogg/Vorbis data to playable stream.
//
// DecodeWithSampleRate returns error when decoding fails or IO error happens.
//
// DecodeWithSampleRate automatically resamples the stream to fit with sampleRate if necessary.
//
// The returned Stream's Seek is available only when src is an io.Seeker.
//
// A Stream doesn't close src even if src implements io.Closer.
// Closing the source is src owner's responsibility.
func DecodeWithSampleRate(sampleRate int, src io.Reader) (*Stream, error) {
	decoded, channelNum, origSampleRate, err := decode(src)
	if err != nil {
		return nil, err
	}
	if channelNum != 1 && channelNum != 2 {
		return nil, fmt.Errorf("vorbis: number of channels must be 1 or 2 but was %d", channelNum)
	}
	var s io.ReadSeeker = decoded
	size := decoded.Length()
	if channelNum == 1 {
		s = convert.NewStereo16(s, true, false)
		size *= 2
	}
	if origSampleRate != sampleRate {
		r := convert.NewResampling(s, size, origSampleRate, sampleRate)
		s = r
		size = r.Length()
	}
	stream := &Stream{decoded: s, size: size}
	return stream, nil
}

// Decode decodes Ogg/Vorbis data to playable stream.
//
// Decode returns error when decoding fails or IO error happens.
//
// Decode automatically resamples the stream to fit with the audio context if necessary.
//
// The returned Stream's Seek is available only when src is an io.Seeker.
//
// A Stream doesn't close src even if src implements io.Closer.
// Closing the source is src owner's responsibility.
//
// Deprecated: as of v2.1. Use DecodeWithSampleRate instead.
func Decode(context *audio.Context, src io.Reader) (*Stream, error) {
	return DecodeWithSampleRate(context.SampleRate(), src)
}
<|endoftext|>


<commit_before>/*
 * This file is part of the KubeVirt project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Copyright 2019 Red Hat, Inc.
 */

package mutators

import (
	"encoding/json"
	"fmt"

	"k8s.io/api/admission/v1beta1"

	v1 "kubevirt.io/client-go/api/v1"
	"kubevirt.io/client-go/log"
	"kubevirt.io/kubevirt/pkg/virt-api/webhooks"
	virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
)

type VMsMutator struct {
	ClusterConfig *virtconfig.ClusterConfig
}

func (mutator *VMsMutator) Mutate(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
	if !webhooks.ValidateRequestResource(ar.Request.Resource, webhooks.VirtualMachineGroupVersionResource.Group, webhooks.VirtualMachineGroupVersionResource.Resource) {
		err := fmt.Errorf("expect resource to be '%s'", webhooks.VirtualMachineGroupVersionResource.Resource)
		return webhooks.ToAdmissionResponseError(err)
	}

	if resp := webhooks.ValidateSchema(v1.VirtualMachineGroupVersionKind, ar.Request.Object.Raw); resp != nil {
		return resp
	}

	raw := ar.Request.Object.Raw
	vm := v1.VirtualMachine{}

	err := json.Unmarshal(raw, &vm)
	if err != nil {
		return webhooks.ToAdmissionResponseError(err)
	}

	// Set VM defaults
	log.Log.Object(&vm).V(4).Info("Apply defaults")
	mutator.setDefaultMachineType(&vm)

	var patch []patchOperation
	var value interface{}
	value = vm.Spec
	patch = append(patch, patchOperation{
		Op:    "replace",
		Path:  "/spec",
		Value: value,
	})

	value = vm.ObjectMeta
	patch = append(patch, patchOperation{
		Op:    "replace",
		Path:  "/metadata",
		Value: value,
	})

	patchBytes, err := json.Marshal(patch)
	if err != nil {
		return webhooks.ToAdmissionResponseError(err)
	}

	jsonPatchType := v1beta1.PatchTypeJSONPatch
	return &v1beta1.AdmissionResponse{
		Allowed:   true,
		Patch:     patchBytes,
		PatchType: &jsonPatchType,
	}
}

func (mutator *VMsMutator) setDefaultMachineType(vm *v1.VirtualMachine) {
	if vm.Spec.Template.Spec.Domain.Machine.Type == "" {
		vm.Spec.Template.Spec.Domain.Machine.Type = mutator.ClusterConfig.GetMachineType()
	}
}
<commit_msg>webhook: mutator: vm.Spec.Template can be null<commit_after>/*
 * This file is part of the KubeVirt project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Copyright 2019 Red Hat, Inc.
 */

package mutators

import (
	"encoding/json"
	"fmt"

	"k8s.io/api/admission/v1beta1"

	v1 "kubevirt.io/client-go/api/v1"
	"kubevirt.io/client-go/log"
	"kubevirt.io/kubevirt/pkg/virt-api/webhooks"
	virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
)

type VMsMutator struct {
	ClusterConfig *virtconfig.ClusterConfig
}

func (mutator *VMsMutator) Mutate(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
	if !webhooks.ValidateRequestResource(ar.Request.Resource, webhooks.VirtualMachineGroupVersionResource.Group, webhooks.VirtualMachineGroupVersionResource.Resource) {
		err := fmt.Errorf("expect resource to be '%s'", webhooks.VirtualMachineGroupVersionResource.Resource)
		return webhooks.ToAdmissionResponseError(err)
	}

	if resp := webhooks.ValidateSchema(v1.VirtualMachineGroupVersionKind, ar.Request.Object.Raw); resp != nil {
		return resp
	}

	raw := ar.Request.Object.Raw
	vm := v1.VirtualMachine{}

	err := json.Unmarshal(raw, &vm)
	if err != nil {
		return webhooks.ToAdmissionResponseError(err)
	}

	// Set VM defaults
	log.Log.Object(&vm).V(4).Info("Apply defaults")
	mutator.setDefaultMachineType(&vm)

	var patch []patchOperation
	var value interface{}
	value = vm.Spec
	patch = append(patch, patchOperation{
		Op:    "replace",
		Path:  "/spec",
		Value: value,
	})

	value = vm.ObjectMeta
	patch = append(patch, patchOperation{
		Op:    "replace",
		Path:  "/metadata",
		Value: value,
	})

	patchBytes, err := json.Marshal(patch)
	if err != nil {
		return webhooks.ToAdmissionResponseError(err)
	}

	jsonPatchType := v1beta1.PatchTypeJSONPatch
	return &v1beta1.AdmissionResponse{
		Allowed:   true,
		Patch:     patchBytes,
		PatchType: &jsonPatchType,
	}
}

func (mutator *VMsMutator) setDefaultMachineType(vm *v1.VirtualMachine) {
	if vm.Spec.Template == nil {
		// nothing to do, let's the validating webhook fail later
		return
	}
	if vm.Spec.Template.Spec.Domain.Machine.Type == "" {
		vm.Spec.Template.Spec.Domain.Machine.Type = mutator.ClusterConfig.GetMachineType()
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"sync"
	"testing"

	"github.com/mauricioklein/text-search-engine/ranking"
	"github.com/mauricioklein/text-search-engine/reader"
	"github.com/mauricioklein/text-search-engine/report"
	"github.com/stretchr/testify/assert"
)

func TestConsoleInputStream(t *testing.T) {
	c, r, _, _ := NewTestConsole("./test-utils/3-files/")

	r.WriteString("Foobar\n")

	actual, _ := c.Read()
	expected := "Foobar"
	assert.Equal(t, expected, actual)
}

func TestConsoleOutputStream(t *testing.T) {
	c, _, w, _ := NewTestConsole("./test-utils/3-files/")

	c.Write("Foobar")

	actual, _ := w.ReadString('\x00')
	expected := "Foobar"
	assert.Equal(t, expected, actual)
}

func TestConsoleErrorStream(t *testing.T) {
	c, _, _, e := NewTestConsole("./test-utils/3-files/")

	c.Error("a generic error")

	actual, _ := e.ReadString('\x00')
	expected := "a generic error"
	assert.Equal(t, expected, actual)
}

func TestConsoleRun3Files(t *testing.T) {
	c, r, w, _ := NewTestConsole("./test-utils/3-files/")

	// write "user input" data to the read stream
	r.Write([]byte("Ca\n"))  // actual search sentence
	r.Write([]byte("\\q\n")) // quit command

	// Wait for the run command to finish (due the quit command above)
	var wg sync.WaitGroup
	wg.Add(1)
	go dispatchConsole(c, &wg)
	wg.Wait()

	// Read response from the write stream
	actual, _ := w.ReadString('\x00')
	expected := `search> file1.txt: 66.67% match
file2.txt: 66.67% match
file3.txt: 0.00% match
search> `

	assert.Equal(t, expected, actual)
}

func TestConsoleRun11Files(t *testing.T) {
	c, r, w, _ := NewTestConsole("./test-utils/11-files/")

	// write "user input" data to the read stream
	r.Write([]byte("Ca\n"))  // actual search sentence
	r.Write([]byte("\\q\n")) // quit command

	// Wait for the run command to finish (due the quit command above)
	var wg sync.WaitGroup
	wg.Add(1)
	go dispatchConsole(c, &wg)
	wg.Wait()

	// Read response from the write stream
	actual, _ := w.ReadString('\x00')

	// file11.txt should not be present, since the result
	// should display only the top 10
	expected := `search> file1.txt: 66.67% match
file2.txt: 66.67% match
file10.txt: 0.00% match
file3.txt: 0.00% match
file4.txt: 0.00% match
file5.txt: 0.00% match
file6.txt: 0.00% match
file7.txt: 0.00% match
file8.txt: 0.00% match
file9.txt: 0.00% match
search> `

	// should filter the result to the top 10
	assert.Equal(t, expected, actual)
}

func NewTestConsole(dirPath string) (Console, *bytes.Buffer, *bytes.Buffer, *bytes.Buffer) {
	files, _ := reader.Disk{}.Read(dirPath)

	nWorkers := 3
	processor := ranking.NewProcessor(files, nWorkers, ranking.LevenshteinRanking{})
	inBuf := bytes.NewBuffer([]byte{})
	outBuf := bytes.NewBuffer([]byte{})
	errBuf := bytes.NewBuffer([]byte{})

	return NewConsole(
		processor,
		report.SimpleReporter{},
		inBuf,
		outBuf,
		errBuf,
	), inBuf, outBuf, errBuf
}

func dispatchConsole(c Console, wg *sync.WaitGroup) {
	defer wg.Done()
	c.Run()
}
<commit_msg>Add missing spec for console input stream<commit_after>package main

import (
	"bytes"
	"sync"
	"testing"

	"github.com/mauricioklein/text-search-engine/ranking"
	"github.com/mauricioklein/text-search-engine/reader"
	"github.com/mauricioklein/text-search-engine/report"
	"github.com/stretchr/testify/assert"
)

func TestConsoleInputStreamSuccess(t *testing.T) {
	c, r, _, _ := NewTestConsole("./test-utils/3-files/")

	r.WriteString("Foobar\n")

	actual, _ := c.Read()
	expected := "Foobar"
	assert.Equal(t, expected, actual)
}

func TestConsoleInputStreamError(t *testing.T) {
	c, r, _, _ := NewTestConsole("./test-utils/3-files/")

	r.WriteString("Foobar")

	_, err := c.Read()
	assert.Error(t, err)
}

func TestConsoleOutputStream(t *testing.T) {
	c, _, w, _ := NewTestConsole("./test-utils/3-files/")

	c.Write("Foobar")

	actual, _ := w.ReadString('\x00')
	expected := "Foobar"
	assert.Equal(t, expected, actual)
}

func TestConsoleErrorStream(t *testing.T) {
	c, _, _, e := NewTestConsole("./test-utils/3-files/")

	c.Error("a generic error")

	actual, _ := e.ReadString('\x00')
	expected := "a generic error"
	assert.Equal(t, expected, actual)
}

func TestConsoleRun3Files(t *testing.T) {
	c, r, w, _ := NewTestConsole("./test-utils/3-files/")

	// write "user input" data to the read stream
	r.Write([]byte("Ca\n"))  // actual search sentence
	r.Write([]byte("\\q\n")) // quit command

	// Wait for the run command to finish (due the quit command above)
	var wg sync.WaitGroup
	wg.Add(1)
	go dispatchConsole(c, &wg)
	wg.Wait()

	// Read response from the write stream
	actual, _ := w.ReadString('\x00')
	expected := `search> file1.txt: 66.67% match
file2.txt: 66.67% match
file3.txt: 0.00% match
search> `

	assert.Equal(t, expected, actual)
}

func TestConsoleRun11Files(t *testing.T) {
	c, r, w, _ := NewTestConsole("./test-utils/11-files/")

	// write "user input" data to the read stream
	r.Write([]byte("Ca\n"))  // actual search sentence
	r.Write([]byte("\\q\n")) // quit command

	// Wait for the run command to finish (due the quit command above)
	var wg sync.WaitGroup
	wg.Add(1)
	go dispatchConsole(c, &wg)
	wg.Wait()

	// Read response from the write stream
	actual, _ := w.ReadString('\x00')

	// file11.txt should not be present, since the result
	// should display only the top 10
	expected := `search> file1.txt: 66.67% match
file2.txt: 66.67% match
file10.txt: 0.00% match
file3.txt: 0.00% match
file4.txt: 0.00% match
file5.txt: 0.00% match
file6.txt: 0.00% match
file7.txt: 0.00% match
file8.txt: 0.00% match
file9.txt: 0.00% match
search> `

	// should filter the result to the top 10
	assert.Equal(t, expected, actual)
}

func NewTestConsole(dirPath string) (Console, *bytes.Buffer, *bytes.Buffer, *bytes.Buffer) {
	files, _ := reader.Disk{}.Read(dirPath)

	nWorkers := 3
	processor := ranking.NewProcessor(files, nWorkers, ranking.LevenshteinRanking{})
	inBuf := bytes.NewBuffer([]byte{})
	outBuf := bytes.NewBuffer([]byte{})
	errBuf := bytes.NewBuffer([]byte{})

	return NewConsole(
		processor,
		report.SimpleReporter{},
		inBuf,
		outBuf,
		errBuf,
	), inBuf, outBuf, errBuf
}

func dispatchConsole(c Console, wg *sync.WaitGroup) {
	defer wg.Done()
	c.Run()
}
<|endoftext|>


<commit_before>package gokeepasslib

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/sha256"
	"crypto/sha512"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
	"reflect"
	"regexp"

	"github.com/aead/argon2"
)

// DBCredentials holds the key used to lock and unlock the database
type DBCredentials struct {
	Passphrase []byte // Passphrase if using one, stored in sha256 hash
	Key        []byte // Contents of the keyfile if using one, stored in sha256 hash
	Windows    []byte // Whatever is returned from windows user account auth, stored in sha256 hash
}

func (c *DBCredentials) buildCompositeKey() ([]byte, error) {
	hash := sha256.New()
	if c.Passphrase != nil { // If the hashed password is provided
		_, err := hash.Write(c.Passphrase)
		if err != nil {
			return nil, err
		}
	}
	if c.Key != nil { // If the hashed keyfile is provided
		_, err := hash.Write(c.Key)
		if err != nil {
			return nil, err
		}
	}
	if c.Windows != nil { // If the hashed password is provided
		_, err := hash.Write(c.Windows)
		if err != nil {
			return nil, err
		}
	}
	return hash.Sum(nil), nil
}

func (c *DBCredentials) buildTransformedKey(db *Database) ([]byte, error) {
	transformedKey, err := c.buildCompositeKey()
	if err != nil {
		return nil, err
	}

	if db.Header.IsKdbx4() {
		if reflect.DeepEqual(db.Header.FileHeaders.KdfParameters.UUID, KdfArgon2) {
			// Argon 2
			transformedKey = argon2.Key2d(
				transformedKey, // Master key
				db.Header.FileHeaders.KdfParameters.Salt[:],             // Salt
				uint32(db.Header.FileHeaders.KdfParameters.Iterations),  // Time cost
				uint32(db.Header.FileHeaders.KdfParameters.Memory)/1024, // Memory cost
				uint8(db.Header.FileHeaders.KdfParameters.Parallelism),  // Parallelism
				32, // Hash length
			)
		} else {
			// AES
			key, err := cryptAESKey(
				transformedKey,
				db.Header.FileHeaders.KdfParameters.Salt[:],
				db.Header.FileHeaders.KdfParameters.Rounds,
			)
			if err != nil {
				return nil, err
			}
			transformedKey = key[:]
		}
	} else {
		// AES
		key, err := cryptAESKey(
			transformedKey,
			db.Header.FileHeaders.TransformSeed,
			db.Header.FileHeaders.TransformRounds,
		)
		if err != nil {
			return nil, err
		}
		transformedKey = key[:]
	}
	return transformedKey, nil
}

func buildMasterKey(db *Database, transformedKey []byte) []byte {
	masterKey := sha256.New()
	masterKey.Write(db.Header.FileHeaders.MasterSeed)
	masterKey.Write(transformedKey)
	return masterKey.Sum(nil)
}

func buildHmacKey(db *Database, transformedKey []byte) []byte {
	masterKey := sha512.New()
	masterKey.Write(db.Header.FileHeaders.MasterSeed)
	masterKey.Write(transformedKey)
	masterKey.Write([]byte{0x01})
	hmacKey := sha512.New()
	hmacKey.Write([]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})
	hmacKey.Write(masterKey.Sum(nil))
	return hmacKey.Sum(nil)
}

func cryptAESKey(masterKey []byte, seed []byte, rounds uint64) ([]byte, error) {
	block, err := aes.NewCipher(seed)
	if err != nil {
		return nil, err
	}

	// http://crypto.stackexchange.com/questions/21048/
	for i := uint64(0); i < rounds; i++ {
		result := make([]byte, 16)
		crypter := cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[:16], masterKey[:16])
		crypter = cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[16:], masterKey[16:])
	}

	hash := sha256.Sum256(masterKey)
	return hash[:], nil
}

// NewPasswordCredentials builds a new DBCredentials from a Password string
func NewPasswordCredentials(password string) *DBCredentials {
	hashedpw := sha256.Sum256([]byte(password))
	return &DBCredentials{Passphrase: hashedpw[:]}
}

// ParseKeyFile returns the hashed key from a key file at the path specified by location, parsing xml if needed
func ParseKeyFile(location string) ([]byte, error) {
	file, err := os.Open(location)
	if err != nil {
		return nil, err
	}

	var data []byte
	if data, err = ioutil.ReadAll(file); err != nil {
		return nil, err
	}

	return ParseKeyData(data)
}

// ParseKeyData returns the hashed key from a key file in bytes, parsing xml if needed
func ParseKeyData(data []byte) ([]byte, error) {
	r, err := regexp.Compile(`<Data>(.+)</Data>`)
	if err != nil {
		return nil, err
	}

	if r.Match(data) { //If keyfile is in xml form, extract key data
		base := r.FindSubmatch(data)[1]
		data = make([]byte, base64.StdEncoding.DecodedLen(len(base)))
		if _, err := base64.StdEncoding.Decode(data, base); err != nil {
			return nil, err
		}
	}

	if len(data) < 32 {
		return data, nil
	}

	// Slice necessary due to padding at the end of the hash
	return data[:32], nil
}

// NewKeyCredentials builds a new DBCredentials from a key file at the path specified by location
func NewKeyCredentials(location string) (*DBCredentials, error) {
	key, err := ParseKeyFile(location)
	if err != nil {
		return nil, err
	}

	return &DBCredentials{Key: key}, nil
}

// NewKeyDataCredentials builds a new DBCredentials from a key file in bytes
func NewKeyDataCredentials(data []byte) (*DBCredentials, error) {
	key, err := ParseKeyData(data)
	if err != nil {
		return nil, err
	}

	return &DBCredentials{Key: key}, nil
}

// NewPasswordAndKeyCredentials builds a new DBCredentials from a password and the key file at the path specified by location
func NewPasswordAndKeyCredentials(password, location string) (*DBCredentials, error) {
	key, err := ParseKeyFile(location)
	if err != nil {
		return nil, err
	}

	hashedpw := sha256.Sum256([]byte(password))

	return &DBCredentials{
		Passphrase: hashedpw[:],
		Key:        key,
	}, nil
}

// NewPasswordAndKeyDataCredentials builds a new DBCredentials from a password and the key file in bytes
func NewPasswordAndKeyDataCredentials(password string, data []byte) (*DBCredentials, error) {
	key, err := ParseKeyData(data)
	if err != nil {
		return nil, err
	}

	hashedpw := sha256.Sum256([]byte(password))

	return &DBCredentials{
		Passphrase: hashedpw[:],
		Key:        key,
	}, nil
}

func (c *DBCredentials) String() string {
	return fmt.Sprintf(
		"Hashed Passphrase: %x\nHashed Key: %x\nHashed Windows Auth: %x",
		c.Passphrase,
		c.Key,
		c.Windows,
	)
}
<commit_msg>Minor improvement on pattern compilation<commit_after>package gokeepasslib

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/sha256"
	"crypto/sha512"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
	"reflect"
	"regexp"

	"github.com/aead/argon2"
)

// DBCredentials holds the key used to lock and unlock the database
type DBCredentials struct {
	Passphrase []byte // Passphrase if using one, stored in sha256 hash
	Key        []byte // Contents of the keyfile if using one, stored in sha256 hash
	Windows    []byte // Whatever is returned from windows user account auth, stored in sha256 hash
}

func (c *DBCredentials) buildCompositeKey() ([]byte, error) {
	hash := sha256.New()
	if c.Passphrase != nil { // If the hashed password is provided
		_, err := hash.Write(c.Passphrase)
		if err != nil {
			return nil, err
		}
	}
	if c.Key != nil { // If the hashed keyfile is provided
		_, err := hash.Write(c.Key)
		if err != nil {
			return nil, err
		}
	}
	if c.Windows != nil { // If the hashed password is provided
		_, err := hash.Write(c.Windows)
		if err != nil {
			return nil, err
		}
	}
	return hash.Sum(nil), nil
}

func (c *DBCredentials) buildTransformedKey(db *Database) ([]byte, error) {
	transformedKey, err := c.buildCompositeKey()
	if err != nil {
		return nil, err
	}

	if db.Header.IsKdbx4() {
		if reflect.DeepEqual(db.Header.FileHeaders.KdfParameters.UUID, KdfArgon2) {
			// Argon 2
			transformedKey = argon2.Key2d(
				transformedKey, // Master key
				db.Header.FileHeaders.KdfParameters.Salt[:],             // Salt
				uint32(db.Header.FileHeaders.KdfParameters.Iterations),  // Time cost
				uint32(db.Header.FileHeaders.KdfParameters.Memory)/1024, // Memory cost
				uint8(db.Header.FileHeaders.KdfParameters.Parallelism),  // Parallelism
				32, // Hash length
			)
		} else {
			// AES
			key, err := cryptAESKey(
				transformedKey,
				db.Header.FileHeaders.KdfParameters.Salt[:],
				db.Header.FileHeaders.KdfParameters.Rounds,
			)
			if err != nil {
				return nil, err
			}
			transformedKey = key[:]
		}
	} else {
		// AES
		key, err := cryptAESKey(
			transformedKey,
			db.Header.FileHeaders.TransformSeed,
			db.Header.FileHeaders.TransformRounds,
		)
		if err != nil {
			return nil, err
		}
		transformedKey = key[:]
	}
	return transformedKey, nil
}

func buildMasterKey(db *Database, transformedKey []byte) []byte {
	masterKey := sha256.New()
	masterKey.Write(db.Header.FileHeaders.MasterSeed)
	masterKey.Write(transformedKey)
	return masterKey.Sum(nil)
}

func buildHmacKey(db *Database, transformedKey []byte) []byte {
	masterKey := sha512.New()
	masterKey.Write(db.Header.FileHeaders.MasterSeed)
	masterKey.Write(transformedKey)
	masterKey.Write([]byte{0x01})
	hmacKey := sha512.New()
	hmacKey.Write([]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})
	hmacKey.Write(masterKey.Sum(nil))
	return hmacKey.Sum(nil)
}

func cryptAESKey(masterKey []byte, seed []byte, rounds uint64) ([]byte, error) {
	block, err := aes.NewCipher(seed)
	if err != nil {
		return nil, err
	}

	// http://crypto.stackexchange.com/questions/21048/
	for i := uint64(0); i < rounds; i++ {
		result := make([]byte, 16)
		crypter := cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[:16], masterKey[:16])
		crypter = cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[16:], masterKey[16:])
	}

	hash := sha256.Sum256(masterKey)
	return hash[:], nil
}

// NewPasswordCredentials builds a new DBCredentials from a Password string
func NewPasswordCredentials(password string) *DBCredentials {
	hashedpw := sha256.Sum256([]byte(password))
	return &DBCredentials{Passphrase: hashedpw[:]}
}

// ParseKeyFile returns the hashed key from a key file at the path specified by location, parsing xml if needed
func ParseKeyFile(location string) ([]byte, error) {
	file, err := os.Open(location)
	if err != nil {
		return nil, err
	}

	var data []byte
	if data, err = ioutil.ReadAll(file); err != nil {
		return nil, err
	}

	return ParseKeyData(data)
}

var keyDataPattern = regexp.MustCompile(`<Data>(.+)</Data>`)

// ParseKeyData returns the hashed key from a key file in bytes, parsing xml if needed
func ParseKeyData(data []byte) ([]byte, error) {
	if keyDataPattern.Match(data) { //If keyfile is in xml form, extract key data
		base := keyDataPattern.FindSubmatch(data)[1]
		data = make([]byte, base64.StdEncoding.DecodedLen(len(base)))
		if _, err := base64.StdEncoding.Decode(data, base); err != nil {
			return nil, err
		}
	}

	if len(data) < 32 {
		return data, nil
	}

	// Slice necessary due to padding at the end of the hash
	return data[:32], nil
}

// NewKeyCredentials builds a new DBCredentials from a key file at the path specified by location
func NewKeyCredentials(location string) (*DBCredentials, error) {
	key, err := ParseKeyFile(location)
	if err != nil {
		return nil, err
	}

	return &DBCredentials{Key: key}, nil
}

// NewKeyDataCredentials builds a new DBCredentials from a key file in bytes
func NewKeyDataCredentials(data []byte) (*DBCredentials, error) {
	key, err := ParseKeyData(data)
	if err != nil {
		return nil, err
	}

	return &DBCredentials{Key: key}, nil
}

// NewPasswordAndKeyCredentials builds a new DBCredentials from a password and the key file at the path specified by location
func NewPasswordAndKeyCredentials(password, location string) (*DBCredentials, error) {
	key, err := ParseKeyFile(location)
	if err != nil {
		return nil, err
	}

	hashedpw := sha256.Sum256([]byte(password))

	return &DBCredentials{
		Passphrase: hashedpw[:],
		Key:        key,
	}, nil
}

// NewPasswordAndKeyDataCredentials builds a new DBCredentials from a password and the key file in bytes
func NewPasswordAndKeyDataCredentials(password string, data []byte) (*DBCredentials, error) {
	key, err := ParseKeyData(data)
	if err != nil {
		return nil, err
	}

	hashedpw := sha256.Sum256([]byte(password))

	return &DBCredentials{
		Passphrase: hashedpw[:],
		Key:        key,
	}, nil
}

func (c *DBCredentials) String() string {
	return fmt.Sprintf(
		"Hashed Passphrase: %x\nHashed Key: %x\nHashed Windows Auth: %x",
		c.Passphrase,
		c.Key,
		c.Windows,
	)
}
<|endoftext|>


<commit_before>package crypto

// hash.go supplies a few geneeral hashing functions, using the hashing
// algorithm blake2b. Because changing the hashing algorithm for Sia has much
// stronger implications than changing any of the other algorithms, blake2b is
// the only supported algorithm. Sia is not really flexible enough to support
// multiple.

import (
	"bytes"
	"encoding/hex"
	"encoding/json"
	"errors"
	"hash"

	"github.com/NebulousLabs/Sia/encoding"

	"golang.org/x/crypto/blake2b"
)

const (
	HashSize = 32
)

type (
	Hash [HashSize]byte

	// HashSlice is used for sorting
	HashSlice []Hash
)

var (
	ErrHashWrongLen = errors.New("encoded value has the wrong length to be a hash")
)

// NewHash returns a blake2b 256bit hasher.
func NewHash() hash.Hash {
	h, _ := blake2b.New256(nil) // cannot fail with nil argument
	return h
}

// HashAll takes a set of objects as input, encodes them all using the encoding
// package, and then hashes the result.
func HashAll(objs ...interface{}) Hash {
	return HashBytes(encoding.MarshalAll(objs...))
}

// HashBytes takes a byte slice and returns the result.
func HashBytes(data []byte) Hash {
	return Hash(blake2b.Sum256(data))
}

// HashObject takes an object as input, encodes it using the encoding package,
// and then hashes the result.
func HashObject(obj interface{}) Hash {
	return HashBytes(encoding.Marshal(obj))
}

// These functions implement sort.Interface, allowing hashes to be sorted.
func (hs HashSlice) Len() int           { return len(hs) }
func (hs HashSlice) Less(i, j int) bool { return bytes.Compare(hs[i][:], hs[j][:]) < 0 }
func (hs HashSlice) Swap(i, j int)      { hs[i], hs[j] = hs[j], hs[i] }

// LoadString takes a string, parses the hash value of the string, and sets the
// value of the hash equal to the hash value of the string.
func (h *Hash) LoadString(s string) error {
	// *2 because there are 2 hex characters per byte.
	if len(s) != HashSize*2 {
		return ErrHashWrongLen
	}
	hBytes, err := hex.DecodeString(s)
	if err != nil {
		return errors.New("could not unmarshal hash: " + err.Error())
	}
	copy(h[:], hBytes)
	return nil
}

// MarshalJSON marshales a hash as a hex string.
func (h Hash) MarshalJSON() ([]byte, error) {
	return json.Marshal(h.String())
}

// String prints the hash in hex.
func (h Hash) String() string {
	return hex.EncodeToString(h[:])
}

// UnmarshalJSON decodes the json hex string of the hash.
func (h *Hash) UnmarshalJSON(b []byte) error {
	// *2 because there are 2 hex characters per byte.
	// +2 because the encoded JSON string has a `"` added at the beginning and end.
	if len(b) != HashSize*2+2 {
		return ErrHashWrongLen
	}

	// b[1 : len(b)-1] cuts off the leading and trailing `"` in the JSON string.
	hBytes, err := hex.DecodeString(string(b[1 : len(b)-1]))
	if err != nil {
		return errors.New("could not unmarshal hash: " + err.Error())
	}
	copy(h[:], hBytes)
	return nil
}
<commit_msg>use NewEncoder in HashObject and HashAll<commit_after>package crypto

// hash.go supplies a few geneeral hashing functions, using the hashing
// algorithm blake2b. Because changing the hashing algorithm for Sia has much
// stronger implications than changing any of the other algorithms, blake2b is
// the only supported algorithm. Sia is not really flexible enough to support
// multiple.

import (
	"bytes"
	"encoding/hex"
	"encoding/json"
	"errors"
	"hash"

	"github.com/NebulousLabs/Sia/encoding"

	"golang.org/x/crypto/blake2b"
)

const (
	HashSize = 32
)

type (
	Hash [HashSize]byte

	// HashSlice is used for sorting
	HashSlice []Hash
)

var (
	ErrHashWrongLen = errors.New("encoded value has the wrong length to be a hash")
)

// NewHash returns a blake2b 256bit hasher.
func NewHash() hash.Hash {
	h, _ := blake2b.New256(nil) // cannot fail with nil argument
	return h
}

// HashAll takes a set of objects as input, encodes them all using the encoding
// package, and then hashes the result.
func HashAll(objs ...interface{}) (hash Hash) {
	h := NewHash()
	enc := encoding.NewEncoder(h)
	for _, obj := range objs {
		enc.Encode(obj)
	}
	h.Sum(hash[:0])
	return
}

// HashBytes takes a byte slice and returns the result.
func HashBytes(data []byte) Hash {
	return Hash(blake2b.Sum256(data))
}

// HashObject takes an object as input, encodes it using the encoding package,
// and then hashes the result.
func HashObject(obj interface{}) (hash Hash) {
	h := NewHash()
	encoding.NewEncoder(h).Encode(obj)
	h.Sum(hash[:0])
	return
}

// These functions implement sort.Interface, allowing hashes to be sorted.
func (hs HashSlice) Len() int           { return len(hs) }
func (hs HashSlice) Less(i, j int) bool { return bytes.Compare(hs[i][:], hs[j][:]) < 0 }
func (hs HashSlice) Swap(i, j int)      { hs[i], hs[j] = hs[j], hs[i] }

// LoadString takes a string, parses the hash value of the string, and sets the
// value of the hash equal to the hash value of the string.
func (h *Hash) LoadString(s string) error {
	// *2 because there are 2 hex characters per byte.
	if len(s) != HashSize*2 {
		return ErrHashWrongLen
	}
	hBytes, err := hex.DecodeString(s)
	if err != nil {
		return errors.New("could not unmarshal hash: " + err.Error())
	}
	copy(h[:], hBytes)
	return nil
}

// MarshalJSON marshales a hash as a hex string.
func (h Hash) MarshalJSON() ([]byte, error) {
	return json.Marshal(h.String())
}

// String prints the hash in hex.
func (h Hash) String() string {
	return hex.EncodeToString(h[:])
}

// UnmarshalJSON decodes the json hex string of the hash.
func (h *Hash) UnmarshalJSON(b []byte) error {
	// *2 because there are 2 hex characters per byte.
	// +2 because the encoded JSON string has a `"` added at the beginning and end.
	if len(b) != HashSize*2+2 {
		return ErrHashWrongLen
	}

	// b[1 : len(b)-1] cuts off the leading and trailing `"` in the JSON string.
	hBytes, err := hex.DecodeString(string(b[1 : len(b)-1]))
	if err != nil {
		return errors.New("could not unmarshal hash: " + err.Error())
	}
	copy(h[:], hBytes)
	return nil
}
<|endoftext|>


<commit_before>package crypto

import (
	. "GoOnchain/errors"
	"crypto/ecdsa"
	"crypto/rand"
	"errors"
	"io"
	"math/big"
)

const (
	INFINITYLEN      = 1
	FLAGLEN          = 1
	XORYVALUELEN     = 32
	COMPRESSEDLEN    = 33
	NOCOMPRESSEDLEN  = 65
	COMPEVENFLAG     = 0x02
	COMPODDFLAG      = 0x03
	NOCOMPRESSEDFLAG = 0x04
)

type PubKey ECPoint

func (e *PubKey) Serialize(w io.Writer) {
	//TODO: implement PubKey.serialize
}

func (e *PubKey) DeSerialize(r io.Reader) error {
	//TODO
	return nil
}

func reverse(data []byte) {
	len1 := len(data)
	for i := 0; i < len1/2; i++ {
		tmp := data[i]
		data[i] = data[len1-i-1]
		data[len1-i-1] = tmp
	}
}

func isEven(k *big.Int) bool {
	z := big.NewInt(0)
	z.Mod(k, big.NewInt(2))
	if z.Int64() == 0 {
		return true
	}
	return false
}

// EncodePoint is used for compressing PublicKey for less space used as same as which in bitcoin.
func (e *PubKey) EncodePoint(isCommpressed bool) ([]byte, error) {
	//if X is infinity, then Y cann't be computed, so here used "||"
	if nil == e.X || nil == e.Y {
		return nil, NewDetailErr(errors.New("The PubKey is an infinity point"), ErrNoCode, "")
	}

	var encodedData []byte

	if isCommpressed {
		encodedData = make([]byte, COMPRESSEDLEN)
	} else {
		encodedData = make([]byte, NOCOMPRESSEDLEN)

		yBytes := e.Y.Bytes()
		copy(encodedData[NOCOMPRESSEDLEN-len(yBytes):], yBytes)
		reverse(encodedData[XORYVALUELEN+FLAGLEN:])

		/*	tmpY := make([]byte, len(yBytes))
			copy(tmpY, yBytes)
			reverse(tmpY)
			copy(encodedData[NCOMPRESSEDLEN-len(yBytes):], tmpY)
		*/
	}

	xBytes := e.X.Bytes()
	copy(encodedData[FLAGLEN:COMPRESSEDLEN], xBytes)
	reverse(encodedData[FLAGLEN : FLAGLEN+XORYVALUELEN])

	/*	tmpX := make([]byte, len(xBytes))
		copy(tmpX, xBytes)
		reverse(tmpX)
		copy(encodedData[COMPRESSEDLEN-len(tmpX):], tmpX)
	*/
	if isCommpressed {
		if isEven(e.Y) {
			encodedData[0] = COMPEVENFLAG
		} else {
			encodedData[0] = COMPODDFLAG
		}
	} else {
		encodedData[0] = NOCOMPRESSEDFLAG
	}

	return encodedData, nil
}

func NewPubKey(prikey []byte) *PubKey {
	//TODO: NewPubKey
	return nil
}

func GenPrivKey() []byte {
	return nil
}

//FIXME, does the privkey need base58 encoding?
//This generates a public & private key pair
func GenKeyPair() ([]byte, PubKey, error) {
	pubkey := new(PubKey)
	privatekey := new(ecdsa.PrivateKey)
	privatekey, err := ecdsa.GenerateKey(Crypto.curve, rand.Reader)
	if err != nil {
		return nil, *pubkey, errors.New("Generate key pair error")
	}

	privkey := privatekey.D.Bytes()
	pubkey.X = privatekey.PublicKey.X
	pubkey.Y = privatekey.PublicKey.Y
	return privkey, *pubkey, nil
}

func DecodePoint(encoded []byte) *PubKey {
	//TODO: DecodePoint
	return nil
}

type PubKeySlice []*PubKey

func (p PubKeySlice) Len() int { return len(p) }
func (p PubKeySlice) Less(i, j int) bool {
	//TODO:PubKeySlice Less
	return false
}
func (p PubKeySlice) Swap(i, j int) {
	//TODO:PubKeySlice Swap
}
<commit_msg>removed the reverse of PublicKey's X and Y in function of "EncodePoint"<commit_after>package crypto

import (
	. "GoOnchain/errors"
	"crypto/ecdsa"
	"crypto/rand"
	"errors"
	"io"
	"math/big"
)

const (
	INFINITYLEN      = 1
	FLAGLEN          = 1
	XORYVALUELEN     = 32
	COMPRESSEDLEN    = 33
	NOCOMPRESSEDLEN  = 65
	COMPEVENFLAG     = 0x02
	COMPODDFLAG      = 0x03
	NOCOMPRESSEDFLAG = 0x04
)

type PubKey ECPoint

func (e *PubKey) Serialize(w io.Writer) {
	//TODO: implement PubKey.serialize
}

func (e *PubKey) DeSerialize(r io.Reader) error {
	//TODO
	return nil
}

func isEven(k *big.Int) bool {
	z := big.NewInt(0)
	z.Mod(k, big.NewInt(2))
	if z.Int64() == 0 {
		return true
	}
	return false
}

// EncodePoint is used for compressing PublicKey for less space used as same as which in bitcoin.
func (e *PubKey) EncodePoint(isCommpressed bool) ([]byte, error) {
	//if X is infinity, then Y cann't be computed, so here used "||"
	if nil == e.X || nil == e.Y {
		return nil, NewDetailErr(errors.New("The PubKey is an infinity point"), ErrNoCode, "")
	}

	var encodedData []byte

	if isCommpressed {
		encodedData = make([]byte, COMPRESSEDLEN)
	} else {
		encodedData = make([]byte, NOCOMPRESSEDLEN)

		yBytes := e.Y.Bytes()
		copy(encodedData[NOCOMPRESSEDLEN-len(yBytes):], yBytes)
	}

	xBytes := e.X.Bytes()
	copy(encodedData[FLAGLEN:COMPRESSEDLEN], xBytes)

	if isCommpressed {
		if isEven(e.Y) {
			encodedData[0] = COMPEVENFLAG
		} else {
			encodedData[0] = COMPODDFLAG
		}
	} else {
		encodedData[0] = NOCOMPRESSEDFLAG
	}

	return encodedData, nil
}

func NewPubKey(prikey []byte) *PubKey {
	//TODO: NewPubKey
	return nil
}

func GenPrivKey() []byte {
	return nil
}

//FIXME, does the privkey need base58 encoding?
//This generates a public & private key pair
func GenKeyPair() ([]byte, PubKey, error) {
	pubkey := new(PubKey)
	privatekey := new(ecdsa.PrivateKey)
	privatekey, err := ecdsa.GenerateKey(Crypto.curve, rand.Reader)
	if err != nil {
		return nil, *pubkey, errors.New("Generate key pair error")
	}

	privkey := privatekey.D.Bytes()
	pubkey.X = privatekey.PublicKey.X
	pubkey.Y = privatekey.PublicKey.Y
	return privkey, *pubkey, nil
}

func DecodePoint(encoded []byte) *PubKey {
	//TODO: DecodePoint
	return nil
}

type PubKeySlice []*PubKey

func (p PubKeySlice) Len() int { return len(p) }
func (p PubKeySlice) Less(i, j int) bool {
	//TODO:PubKeySlice Less
	return false
}
func (p PubKeySlice) Swap(i, j int) {
	//TODO:PubKeySlice Swap
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"github.com/PuerkitoBio/goquery"
	"io/ioutil"
	"log"
	"strings"
)

func main() {
	log.Println("Begining download")
	doc, err := goquery.NewDocument("https://godoc.org/-/index")
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Finished download")
	var buffer bytes.Buffer

	doc.Find("tr").Each(func(i int, s *goquery.Selection) {
		children := s.Children()

		var (
			githubURL   string
			description string
			//goDocURL    string
		)

		children.Each(func(i int, s2 *goquery.Selection) {
			childURL, childURLexists := s.Find("a").Attr("href")
			childDescription := s.Text()

			if childURLexists == true {
				githubURL = childURL
			}

			if len(childDescription) > 0 {
				description = childDescription
			}
		})

		if strings.Contains(githubURL, "github.com") {
			// TODO build go doc url
			//goDocUrl =

			// TODO check for descriptions with just github url and remove
			if githubURL == "/"+githubURL {
				description = ""
			}

			buffer.WriteString("{\"url\": \"" + githubURL + "\", \"description\": \"" + description + "\"},\n")
		}
	})

	// TODO temp write JSON files
	jsonData := []byte(buffer.String())
	_ = ioutil.WriteFile("./tmp.json", jsonData, 0644)
	log.Println("Finished")
}
<commit_msg>cleaned up the indexer code and now getting ready to parse GitHub URLs for versions<commit_after>package main

import (
	"bytes"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"io/ioutil"
	"log"
	//"os"
	"net/http"
	"strings"
	"time"
)

type GoPackage struct {
	Description    string
	GitHubURL      string
	GoDocURL       string
	IndexTime      string
	HttpStatusCode int
}

func main() {
	log.Println("Begining download")
	doc, err := goquery.NewDocument("https://godoc.org/-/index")

	if err != nil {
		log.Fatal(err)
	}

	log.Println("Finished download")
	var goPackageList = make([]*GoPackage, 0)

	// For each tr element on the page
	doc.Find("tr").Each(func(i int, s *goquery.Selection) {
		children := s.Children()
		goPackage := new(GoPackage)

		// For each child in the tr element
		children.Each(func(i int, s2 *goquery.Selection) {
			childURL, childURLexists := s.Find("a").Attr("href")
			childDescription := s.Text()

			if childURLexists == true {
				goPackage.GitHubURL = childURL
			}

			if len(childDescription) > 0 {
				// TODO check if description isn't just the url, if so dont set it
				goPackage.Description = childDescription
			}
		})

		// Only continue if this goPackage contains a GitHub URL
		// TODO check to make sure github.com is the prefix
		if strings.Contains(goPackage.GitHubURL, "github.com") {
			// Build go doc url
			goPackage.GoDocURL = ("https://godoc.org/" + goPackage.GitHubURL)

			// Create Index Time
			t := time.Now()
			time := t.String()
			goPackage.IndexTime = time

			// Add goPackage to goPackageList
			goPackageList = append(goPackageList, goPackage)
		}
	})

	for _, goPackage := range goPackageList {
		resp, err := http.Get("http://www." + goPackage.GitHubURL)
		if err != nil {
			fmt.Println("ERROR")
		}
		defer resp.Body.Close()

		// TODO Check resp status code
		goPackage.HttpStatusCode = resp.StatusCode

		_, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			panic(err)
		}
		// Call Router Functionality to Parse for array of versions

	}

	log.Println("Finished Building GoPackages")
	log.Println("Creating JSON dump")
	createJSONDump(goPackageList)
}

// Create a tmp JSON dump of all serialized goPackageData
func createJSONDump(goPackageList []*GoPackage) {
	var buffer bytes.Buffer

	for _, goPackage := range goPackageList {
		buffer.WriteString("{\"url\": \"" + goPackage.GitHubURL + "\", \"description\": \"" + goPackage.Description + "\", \"index_time\": \"" + goPackage.IndexTime + "\" },\n")
	}

	t := time.Now()
	time := t.String()
	jsonData := []byte(buffer.String())
	_ = ioutil.WriteFile("./"+time+"tmp.json", jsonData, 0644)
}

func printGoPackage(gp *GoPackage) {
	fmt.Println("GitHub URL = ", gp.GitHubURL)
	fmt.Println("Description = ", gp.Description)
	fmt.Println("Index time = ", gp.IndexTime)
	fmt.Println("GoDocURL = ", gp.GoDocURL, "\n")
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 AFP Authors
// This source code is released under the terms of the
// MIT license. Please see the file LICENSE for license details.

package afp

import (
	"os"
	"log"
)

const CHAN_BUF_LEN = 64

//Constants to specify the type of a given filter
const (
	PIPE_SOURCE = iota
	PIPE_SINK
	PIPE_LINK
)

const HEADER_LENGTH = (
	1 + // Version
	1 + // Channels
	1 + // SampleSize
	4 + // SampleRate
	4 + // FrameSize
	8 // ContentLength
)
type StreamHeader struct {
	Version       int8
	Channels      int8
	SampleSize    int8
	SampleRate    int32
	FrameSize     int32
	ContentLength int64
}

type Context struct {
	HeaderSource <-chan StreamHeader
	HeaderSink   chan<- StreamHeader
	Source       <-chan [][]float32
	Sink         chan<- [][]float32

	Verbose   bool
	Err, Info *log.Logger
}

type Filter interface {
	GetType() int
	Init(*Context, []string) os.Error
	Start()
	Stop() os.Error
}
<commit_msg>Apparently types.go doesn't want to be readable.<commit_after>// Copyright (c) 2010 AFP Authors
// This source code is released under the terms of the
// MIT license. Please see the file LICENSE for license details.

package afp

import (
	"os"
	"log"
)

const CHAN_BUF_LEN = 64

//Constants to specify the type of a given filter
const (
	PIPE_SOURCE = iota
	PIPE_SINK
	PIPE_LINK
)

const HEADER_LENGTH = (
	1 + // Version
	1 + // Channels
	1 + // SampleSize
	4 + // SampleRate
	4 + // FrameSize
	8) // ContentLength

type StreamHeader struct {
	Version       int8
	Channels      int8
	SampleSize    int8
	SampleRate    int32
	FrameSize     int32
	ContentLength int64
}

type Context struct {
	HeaderSource <-chan StreamHeader
	HeaderSink   chan<- StreamHeader
	Source       <-chan [][]float32
	Sink         chan<- [][]float32

	Verbose   bool
	Err, Info *log.Logger
}

type Filter interface {
	GetType() int
	Init(*Context, []string) os.Error
	Start()
	Stop() os.Error
}
<|endoftext|>


<commit_before>// Package assert provides C-like assertions for Go. For more
// information, see assert(3) (e.g. `man 3 assert`).
package assert

import (
	"fmt"
	"os"
	"runtime"
	"testing"
)

// NoDebug, if set to true, will cause all asserts to be ignored.
var NoDebug bool

func die(what string) {
	_, file, line, ok := runtime.Caller(2)
	if !ok {
		panic(what)
	} else {
		fmt.Fprintf(os.Stderr, "%s\n", what)
		fmt.Fprintf(os.Stderr, "\t%s line %d\n", file, line)
		os.Exit(1)
	}
}

// Bool asserts that cond is false.
func Bool(cond bool) {
	if NoDebug {
		return
	}

	if !cond {
		die("assert.Bool failed")
	}
}

// Error asserts that err is nil.
func Error(err error) {
	if NoDebug {
		return
	}

	if nil != err {
		die(err.Error())
	}
}

// Error2 asserts that the actual error is the expected error.
func Error2(expected, actual error) {
	if NoDebug || (expected == actual) {
		return
	}

	if expected == nil {
		die(fmt.Sprintf("assert.Error2: %s", actual.Error()))
	}

	var should string
	if actual == nil {
		should = "no error was returned"
	} else {
		should = fmt.Sprintf("have '%s'", actual)
	}

	die(fmt.Sprintf("assert.Error2: expected '%s', but %s", expected, should))
}

// BoolT checks a boolean condition, calling Fatal on t if it is
// false.
func BoolT(t *testing.T, cond bool) {
	if !cond {
		t.Fatal("assert.Bool failed")
	}
}

// ErrorT checks whether the error is nil, calling Fatal on t if it
// isn't.
func ErrorT(t *testing.T, err error) {
	if nil != err {
		t.Fatalf("%s", err)
	}
}

// Error2T compares a pair of errors, calling Fatal on it if they
// don't match.
func Error2T(t *testing.T, expected, actual error) {
	if NoDebug || (expected == actual) {
		return
	}

	if expected == nil {
		die(fmt.Sprintf("assert.Error2: %s", actual.Error()))
	}

	var should string
	if actual == nil {
		should = "no error was returned"
	} else {
		should = fmt.Sprintf("have '%s'", actual)
	}

	die(fmt.Sprintf("assert.Error2: expected '%s', but %s", expected, should))
}
<commit_msg>Tidy assert package.<commit_after>// Package assert provides C-like assertions for Go. For more
// information, see assert(3) (e.g. `man 3 assert`).
//
// The T variants operating on *testing.T values; instead of killing
// the program, they call the Fatal method.
package assert

import (
	"fmt"
	"os"
	"runtime"
	"strings"
	"testing"
)

// NoDebug, if set to true, will cause all asserts to be ignored.
var NoDebug bool

func die(what string, a ...string) {
	_, file, line, ok := runtime.Caller(2)
	if !ok {
		panic(what)
	} else {
		fmt.Fprintf(os.Stderr, "%s", what)
		if len(a) > 0 {
			s := strings.Join(a, ", ")
			fmt.Fprintln(os.Stderr, ":"+s)
		} else {
			fmt.Fprintf(os.Stderr, "\n")
		}
		fmt.Fprintf(os.Stderr, "\t%s line %d\n", file, line)
		os.Exit(1)
	}
}

// Bool asserts that cond is false.
//
// For example, this would replace
//    if x < 0 {
//            log.Fatal("x is subzero")
//    }
//
// The same assertion would be
//    assert.Bool(x, "x is subzero")
func Bool(cond bool, s ...string) {
	if NoDebug {
		return
	}

	if !cond {
		die("assert.Bool failed", s...)
	}
}

// Error asserts that err is not nil, e.g. that an error has occurred.
//
// For example,
//     if err == nil {
//             log.Fatal("call to <something> should have failed")
//     }
//     // becomes
//     assert.Error(err, "call to <something> should have failed")
func Error(err error, s ...string) {
	if NoDebug {
		return
	} else if nil != err {
		return
	}

	if len(s) == 0 {
		die("error expected, but no error returned")
	} else {
		die(strings.Join(s, ", "))
	}
}

// NoError asserts that err is nil, e.g. that no error has occurred.
func NoError(err error, s ...string) {
	if NoDebug {
		return
	}

	if nil != err {
		die(err.Error())
	}
}

// ErrorEq asserts that the actual error is the expected error.
func ErrorEq(expected, actual error) {
	if NoDebug || (expected == actual) {
		return
	}

	if expected == nil {
		die(fmt.Sprintf("assert.ErrorEq: %s", actual.Error()))
	}

	var should string
	if actual == nil {
		should = "no error was returned"
	} else {
		should = fmt.Sprintf("have '%s'", actual)
	}

	die(fmt.Sprintf("assert.ErrorEq: expected '%s', but %s", expected, should))
}

// BoolT checks a boolean condition, calling Fatal on t if it is
// false.
func BoolT(t *testing.T, cond bool, s ...string) {
	if !cond {
		what := strings.Join(s, ", ")
		if len(what) > 0 {
			what = ": " + what
		}
		t.Fatalf("assert.Bool failed%s", what)
	}
}

// ErrorT asserts that err is not nil, e.g. asserting that an error
// has occurred. See also NoErrorT.
func ErrorT(t *testing.T, err error, s ...string) {
	if nil != err {
		return
	}

	if len(s) == 0 {
		t.Fatal("error expected, but no error returned")
	} else {
		t.Fatal(strings.Join(s, ", "))
	}
}

// NoErrorT asserts that err is nil, e.g. asserting that no error has
// occurred. See also ErrorT.
func NoErrorT(t *testing.T, err error) {
	if nil != err {
		t.Fatalf("%s", err)
	}
}

// ErrorEqT compares a pair of errors, calling Fatal on it if they
// don't match.
func ErrorEqT(t *testing.T, expected, actual error) {
	if NoDebug || (expected == actual) {
		return
	}

	if expected == nil {
		die(fmt.Sprintf("assert.Error2: %s", actual.Error()))
	}

	var should string
	if actual == nil {
		should = "no error was returned"
	} else {
		should = fmt.Sprintf("have '%s'", actual)
	}

	die(fmt.Sprintf("assert.Error2: expected '%s', but %s", expected, should))
}
<|endoftext|>


<commit_before>package cluster

import (
	"context"

	"github.com/rancher/rancher/pkg/agent/steve"
)

var running bool

func RunControllers(ctx context.Context) error {
	if running {
		return nil
	}

	if err := steve.Run(ctx); err != nil {
		return err
	}

	running = true
	return nil
}
<commit_msg>Add user controllers back to agent<commit_after>package cluster

import (
	"context"

	"github.com/rancher/rancher/pkg/agent/steve"
	"github.com/rancher/rancher/pkg/controllers/managementagent"
	"github.com/rancher/rancher/pkg/types/config"
	"github.com/sirupsen/logrus"
	"k8s.io/client-go/rest"
)

var running bool

func RunControllers(ctx context.Context) error {
	if running {
		return nil
	}

	logrus.Info("Starting user controllers")
	c, err := rest.InClusterConfig()
	if err != nil {
		return err
	}

	userOnly, err := config.NewUserOnlyContext(*c)
	if err != nil {
		return err
	}

	if err := managementagent.Register(ctx, userOnly); err != nil {
		return err
	}

	if err := userOnly.Start(ctx); err != nil {
		return err
	}

	if err := steve.Run(ctx); err != nil {
		return err
	}

	running = true
	return nil
}
<|endoftext|>