<commit_before>// Wraps the rancher GO API client for caching and easier testing.

package main

import (
	"errors"

	"github.com/rancher/go-rancher/v2"
)

type RancherGenClient interface {
	AddEnvironment(client.Project)
	Environments() (*client.ProjectCollection, error)
	GetEnvironment(string) client.Project
	DeleteEnvironment(string) error
	AddHost(client.Host)
	Hosts() (*client.HostCollection, error)
	GetHost(string) client.Host
	DeleteHost(string) error
	AddStack(client.Stack)
	Stacks() (*client.StackCollection, error)
	GetStack(string) client.Stack
	DeleteStack(string) error
	AddService(client.Service)
	Services() (*client.ServiceCollection, error)
	GetService(string) client.Service
	DeleteService(string) error
}

type RancherWebClient struct {
	rancher      *client.RancherClient
	environments map[string]client.Project
	hosts        map[string]client.Host
	stacks       map[string]client.Stack
	services     map[string]client.Service
}

type RancherMockClient struct {
	environments map[string]client.Project
	hosts        map[string]client.Host
	stacks       map[string]client.Stack
	services     map[string]client.Service
}

func NewRancherWebClient(rancher *client.RancherClient) *RancherWebClient {
	r := new(RancherWebClient)
	r.rancher = rancher
	r.environments = make(map[string]client.Project)
	r.stacks = make(map[string]client.Stack)
	r.services = make(map[string]client.Service)
	r.hosts = make(map[string]client.Host)
	return r
}

func NewRancherMockClient() *RancherMockClient {
	r := new(RancherMockClient)
	r.environments = make(map[string]client.Project)
	r.stacks = make(map[string]client.Stack)
	r.services = make(map[string]client.Service)
	r.hosts = make(map[string]client.Host)
	return r
}

// ---------

func (r *RancherWebClient) AddEnvironment(env client.Project) {
	r.environments[env.Id] = env
}

func (r *RancherWebClient) AddStack(stack client.Stack) {
	r.stacks[stack.Id] = stack
}

func (r *RancherWebClient) AddService(service client.Service) {
	r.services[service.Id] = service
}

func (r *RancherWebClient) AddHost(host client.Host) {
	r.hosts[host.Id] = host
}

func (r *RancherWebClient) Environments() (environments *client.ProjectCollection, err error) {
	environments, err = r.rancher.Project.List(nil)
	if err != nil {
		return
	}
	for _, env := range environments.Data {
		r.AddEnvironment(env)
	}

	return
}

func (r *RancherWebClient) Hosts() (hosts *client.HostCollection, err error) {
	hosts, err = r.rancher.Host.List(nil)
	if err != nil {
		return
	}
	for _, host := range hosts.Data {
		r.AddHost(host)
	}

	return
}

func (r *RancherWebClient) GetEnvironment(id string) client.Project {
	if _, ok := r.environments[id]; !ok {
		x, _ := r.rancher.Project.ById(id)
		r.environments[id] = *x
	}
	return r.environments[id]
}

func (r *RancherWebClient) GetHost(id string) client.Host {
	if _, ok := r.hosts[id]; !ok {
		x, _ := r.rancher.Host.ById(id)
		r.hosts[id] = *x
	}

	return r.hosts[id]
}

func (r *RancherWebClient) Stacks() (stacks *client.StackCollection, err error) {
	stacks, err = r.rancher.Stack.List(nil)
	if err != nil {
		return
	}
	for _, env := range stacks.Data {
		r.AddStack(env)
	}
	return
}

func (r *RancherWebClient) GetStack(id string) client.Stack {
	if _, ok := r.stacks[id]; !ok {
		x, _ := r.rancher.Stack.ById(id)
		r.stacks[id] = *x
	}
	return r.stacks[id]
}

func (r *RancherWebClient) Services() (services *client.ServiceCollection, err error) {
	services, err = r.rancher.Service.List(nil)
	if err != nil {
		return
	}
	for _, env := range services.Data {
		r.AddService(env)
	}
	return
}

func (r *RancherWebClient) GetService(id string) client.Service {
	if _, ok := r.services[id]; !ok {
		x, _ := r.rancher.Service.ById(id)
		r.services[id] = *x
	}
	return r.services[id]
}

func (r *RancherWebClient) DeleteService(id string) error {
	return errors.New("deleting objects not supported in Rancher web client")
}

func (r *RancherWebClient) DeleteStack(id string) error {
	return errors.New("deleting objects not supported in Rancher web client")
}

func (r *RancherWebClient) DeleteHost(id string) error {
	return errors.New("deleting objects not supported in Rancher web client")
}

func (r *RancherWebClient) DeleteEnvironment(id string) error {
	return errors.New("deleting objects not supported in Rancher web client")
}

// ---------

func (r *RancherMockClient) AddEnvironment(env client.Project) {
	r.environments[env.Id] = env
}

func (r *RancherMockClient) AddHost(host client.Host) {
	r.hosts[host.Id] = host
}

func (r *RancherMockClient) AddStack(stack client.Stack) {
	r.stacks[stack.Id] = stack
}

func (r *RancherMockClient) AddService(service client.Service) {
	r.services[service.Id] = service
}

func (r *RancherMockClient) GetEnvironment(id string) client.Project {
	return r.environments[id]
}

func (r *RancherMockClient) GetHost(id string) client.Host {
	return r.hosts[id]
}

func (r *RancherMockClient) GetStack(id string) client.Stack {
	return r.stacks[id]
}

func (r *RancherMockClient) GetService(id string) client.Service {
	return r.services[id]
}

func (r *RancherMockClient) Environments() (*client.ProjectCollection, error) {
	coll := make([]client.Project, 0, len(r.environments))

	for _, e := range r.environments {
		coll = append(coll, e)
	}

	return &client.ProjectCollection{Data: coll}, nil
}

func (r *RancherMockClient) Hosts() (*client.HostCollection, error) {
	coll := make([]client.Host, 0, len(r.hosts))

	for _, e := range r.hosts {
		coll = append(coll, e)
	}

	return &client.HostCollection{Data: coll}, nil
}

func (r *RancherMockClient) Stacks() (*client.StackCollection, error) {
	coll := make([]client.Stack, 0, len(r.stacks))

	for _, e := range r.stacks {
		coll = append(coll, e)
	}

	return &client.StackCollection{Data: coll}, nil
}

func (r *RancherMockClient) Services() (*client.ServiceCollection, error) {
	coll := make([]client.Service, 0, len(r.services))

	for _, e := range r.services {
		coll = append(coll, e)
	}

	return &client.ServiceCollection{Data: coll}, nil
}

func (r *RancherMockClient) DeleteService(id string) error {
	delete(r.services, id)
	return nil
}

func (r *RancherMockClient) DeleteStack(id string) error {
	delete(r.stacks, id)
	return nil
}

func (r *RancherMockClient) DeleteHost(id string) error {
	delete(r.hosts, id)
	return nil
}

func (r *RancherMockClient) DeleteEnvironment(id string) error {
	delete(r.environments, id)
	return nil
}
<commit_msg>handle pagination<commit_after>// Wraps the rancher GO API client for caching and easier testing.

package main

import (
	"errors"

	"github.com/rancher/go-rancher/v2"
)

type RancherGenClient interface {
	AddEnvironment(client.Project)
	Environments() (*client.ProjectCollection, error)
	GetEnvironment(string) client.Project
	DeleteEnvironment(string) error
	AddHost(client.Host)
	Hosts() (*client.HostCollection, error)
	GetHost(string) client.Host
	DeleteHost(string) error
	AddStack(client.Stack)
	Stacks() (*client.StackCollection, error)
	GetStack(string) client.Stack
	DeleteStack(string) error
	AddService(client.Service)
	Services() (*client.ServiceCollection, error)
	GetService(string) client.Service
	DeleteService(string) error
}

type RancherWebClient struct {
	rancher      *client.RancherClient
	environments map[string]client.Project
	hosts        map[string]client.Host
	stacks       map[string]client.Stack
	services     map[string]client.Service
}

type RancherMockClient struct {
	environments map[string]client.Project
	hosts        map[string]client.Host
	stacks       map[string]client.Stack
	services     map[string]client.Service
}

func NewRancherWebClient(rancher *client.RancherClient) *RancherWebClient {
	r := new(RancherWebClient)
	r.rancher = rancher
	r.environments = make(map[string]client.Project)
	r.stacks = make(map[string]client.Stack)
	r.services = make(map[string]client.Service)
	r.hosts = make(map[string]client.Host)
	return r
}

func NewRancherMockClient() *RancherMockClient {
	r := new(RancherMockClient)
	r.environments = make(map[string]client.Project)
	r.stacks = make(map[string]client.Stack)
	r.services = make(map[string]client.Service)
	r.hosts = make(map[string]client.Host)
	return r
}

// ---------

func (r *RancherWebClient) AddEnvironment(env client.Project) {
	r.environments[env.Id] = env
}

func (r *RancherWebClient) AddStack(stack client.Stack) {
	r.stacks[stack.Id] = stack
}

func (r *RancherWebClient) AddService(service client.Service) {
	r.services[service.Id] = service
}

func (r *RancherWebClient) AddHost(host client.Host) {
	r.hosts[host.Id] = host
}

func (r *RancherWebClient) Environments() (environments *client.ProjectCollection, err error) {
	envList, err := r.rancher.Project.List(nil)
	envArr := envList.Data

	for envList.Pagination != nil && envList.Pagination.Partial {
		envList, err = envList.Next()
		if err != nil {
			return
		}

		envArr = append(envArr, envList.Data...)
	}

	if err != nil {
		return
	}
	for _, env := range envArr {
		r.AddEnvironment(env)
	}
	return &client.ProjectCollection{Data: envArr}, nil
}

func (r *RancherWebClient) Hosts() (hosts *client.HostCollection, err error) {
	hostList, err := r.rancher.Host.List(nil)
	hostArr := hostList.Data

	for hostList.Pagination != nil && hostList.Pagination.Partial {
		hostList, err = hostList.Next()
		if err != nil {
			return
		}

		hostArr = append(hostArr, hostList.Data...)
	}

	if err != nil {
		return
	}
	for _, env := range hostArr {
		r.AddHost(env)
	}
	return &client.HostCollection{Data: hostArr}, nil
}

func (r *RancherWebClient) GetEnvironment(id string) client.Project {
	if _, ok := r.environments[id]; !ok {
		x, _ := r.rancher.Project.ById(id)
		r.environments[id] = *x
	}
	return r.environments[id]
}

func (r *RancherWebClient) GetHost(id string) client.Host {
	if _, ok := r.hosts[id]; !ok {
		x, _ := r.rancher.Host.ById(id)
		r.hosts[id] = *x
	}

	return r.hosts[id]
}

func (r *RancherWebClient) Stacks() (stacks *client.StackCollection, err error) {
	stackList, err := r.rancher.Stack.List(nil)
	stackArr := stackList.Data

	for stackList.Pagination != nil && stackList.Pagination.Partial {
		stackList, err = stackList.Next()
		if err != nil {
			return
		}

		stackArr = append(stackArr, stackList.Data...)
	}

	if err != nil {
		return
	}
	for _, env := range stackArr {
		r.AddStack(env)
	}
	return &client.StackCollection{Data: stackArr}, nil
}

func (r *RancherWebClient) GetStack(id string) client.Stack {
	if _, ok := r.stacks[id]; !ok {
		x, _ := r.rancher.Stack.ById(id)
		r.stacks[id] = *x
	}
	return r.stacks[id]
}

func (r *RancherWebClient) Services() (services *client.ServiceCollection, err error) {
	serviceList, err := r.rancher.Service.List(nil)
	serviceArr := serviceList.Data

	for serviceList.Pagination != nil && serviceList.Pagination.Partial {
		serviceList, err = serviceList.Next()
		if err != nil {
			return
		}

		serviceArr = append(serviceArr, serviceList.Data...)
	}

	if err != nil {
		return
	}
	for _, env := range serviceArr {
		r.AddService(env)
	}
	return &client.ServiceCollection{Data: serviceArr}, nil
}

func (r *RancherWebClient) GetService(id string) client.Service {
	if _, ok := r.services[id]; !ok {
		x, _ := r.rancher.Service.ById(id)
		r.services[id] = *x
	}
	return r.services[id]
}

func (r *RancherWebClient) DeleteService(id string) error {
	return errors.New("deleting objects not supported in Rancher web client")
}

func (r *RancherWebClient) DeleteStack(id string) error {
	return errors.New("deleting objects not supported in Rancher web client")
}

func (r *RancherWebClient) DeleteHost(id string) error {
	return errors.New("deleting objects not supported in Rancher web client")
}

func (r *RancherWebClient) DeleteEnvironment(id string) error {
	return errors.New("deleting objects not supported in Rancher web client")
}

// ---------

func (r *RancherMockClient) AddEnvironment(env client.Project) {
	r.environments[env.Id] = env
}

func (r *RancherMockClient) AddHost(host client.Host) {
	r.hosts[host.Id] = host
}

func (r *RancherMockClient) AddStack(stack client.Stack) {
	r.stacks[stack.Id] = stack
}

func (r *RancherMockClient) AddService(service client.Service) {
	r.services[service.Id] = service
}

func (r *RancherMockClient) GetEnvironment(id string) client.Project {
	return r.environments[id]
}

func (r *RancherMockClient) GetHost(id string) client.Host {
	return r.hosts[id]
}

func (r *RancherMockClient) GetStack(id string) client.Stack {
	return r.stacks[id]
}

func (r *RancherMockClient) GetService(id string) client.Service {
	return r.services[id]
}

func (r *RancherMockClient) Environments() (*client.ProjectCollection, error) {
	coll := make([]client.Project, 0, len(r.environments))

	for _, e := range r.environments {
		coll = append(coll, e)
	}

	return &client.ProjectCollection{Data: coll}, nil
}

func (r *RancherMockClient) Hosts() (*client.HostCollection, error) {
	coll := make([]client.Host, 0, len(r.hosts))

	for _, e := range r.hosts {
		coll = append(coll, e)
	}

	return &client.HostCollection{Data: coll}, nil
}

func (r *RancherMockClient) Stacks() (*client.StackCollection, error) {
	coll := make([]client.Stack, 0, len(r.stacks))

	for _, e := range r.stacks {
		coll = append(coll, e)
	}

	return &client.StackCollection{Data: coll}, nil
}

func (r *RancherMockClient) Services() (*client.ServiceCollection, error) {
	coll := make([]client.Service, 0, len(r.services))

	for _, e := range r.services {
		coll = append(coll, e)
	}

	return &client.ServiceCollection{Data: coll}, nil
}

func (r *RancherMockClient) DeleteService(id string) error {
	delete(r.services, id)
	return nil
}

func (r *RancherMockClient) DeleteStack(id string) error {
	delete(r.stacks, id)
	return nil
}

func (r *RancherMockClient) DeleteHost(id string) error {
	delete(r.hosts, id)
	return nil
}

func (r *RancherMockClient) DeleteEnvironment(id string) error {
	delete(r.environments, id)
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2014 CoreOS, Inc.
//
// 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 main

import (
	"fmt"
	"net/url"
	"os"
	"path/filepath"
	"runtime"

	"github.com/appc/spec/discovery"
	"github.com/appc/spec/schema/types"
	"github.com/coreos/rocket/cas"
)

const (
	imgDir = "images"

	defaultOS   = runtime.GOOS
	defaultArch = runtime.GOARCH
)

var (
	cmdFetch = &Command{
		Name:    "fetch",
		Summary: "Fetch image(s) and store them in the local cache",
		Usage:   "IMAGE_URL...",
		Run:     runFetch,
	}
)

func init() {
	commands = append(commands, cmdFetch)
}

func runFetch(args []string) (exit int) {
	if len(args) < 1 {
		fmt.Fprintf(os.Stderr, "fetch: Must provide at least one image\n")
		return 1
	}
	root := filepath.Join(globalFlags.Dir, imgDir)
	if err := os.MkdirAll(root, 0755); err != nil {
		fmt.Fprintf(os.Stderr, "fetch: error creating image directory: %v\n", err)
		return 1
	}

	ds := cas.NewStore(globalFlags.Dir)

	for _, img := range args {
		hash, err := fetchImage(img, ds)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%v\n", err)
			return 1
		}
		shortHash := types.ShortHash(hash)
		fmt.Println(shortHash)
	}

	return
}

// fetchImage will take an image as either a URL or a name string and import it
// into the store if found.
func fetchImage(img string, ds *cas.Store) (string, error) {
	u, err := url.Parse(img)
	if err == nil && u.Scheme == "" {
		if app := newDiscoveryApp(img); app != nil {
			fmt.Printf("rkt: starting to discover app img %s\n", img)
			u, err = discover(app)
			if err != nil {
				return "", err
			}
		}
	}
	if err != nil {
		return "", fmt.Errorf("not a valid URL (%s)", img)
	}
	if u.Scheme != "http" && u.Scheme != "https" {
		return "", fmt.Errorf("rkt only supports http or https URLs (%s)", img)
	}
	return fetchURL(u.String(), ds)
}

func fetchURL(u string, ds *cas.Store) (string, error) {
	fmt.Printf("rkt: starting to fetch img from %s\n", u)
	rem := cas.NewRemote(u, []string{})
	err := ds.ReadIndex(rem)
	if err != nil && rem.Blob == "" {
		rem, err = rem.Download(*ds)
		if err != nil {
			return "", err
		}
	}
	return rem.Blob, nil
}

func discover(app *discovery.App) (*url.URL, error) {
	ep, err := discovery.DiscoverEndpoints(*app, true)
	if err != nil {
		return nil, fmt.Errorf("discovery: %v", err)
	}
	// TODO(philips): use all available mirrors
	if globalFlags.Debug {
		fmt.Printf("discovery: trying %v\n", ep.ACI[0])
	}
	imgurl := ep.ACI[0]
	u, err := url.Parse(imgurl)
	if err != nil {
		return nil, fmt.Errorf("discovery: fetched img URL (%s) is invalid (%v)", imgurl, err)
	}
	return u, nil
}

// newDiscoveryApp creates a discovery app if the given img is an app name and
// has a URL-like structure, for example example.com/reduce-worker.
// Or it returns nil.
func newDiscoveryApp(img string) *discovery.App {
	app, err := discovery.NewAppFromString(img)
	if err != nil {
		return nil
	}
	u, err := url.Parse(app.Name.String())
	if err != nil || u.Scheme != "" {
		return nil
	}
	if _, ok := app.Labels["arch"]; !ok {
		app.Labels["arch"] = defaultArch
	}
	if _, ok := app.Labels["os"]; !ok {
		app.Labels["os"] = defaultOS
	}
	return app
}
<commit_msg>rkt: remove unused images directory<commit_after>// Copyright 2014 CoreOS, Inc.
//
// 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 main

import (
	"fmt"
	"net/url"
	"os"
	"runtime"

	"github.com/appc/spec/discovery"
	"github.com/appc/spec/schema/types"
	"github.com/coreos/rocket/cas"
)

const (
	defaultOS   = runtime.GOOS
	defaultArch = runtime.GOARCH
)

var (
	cmdFetch = &Command{
		Name:    "fetch",
		Summary: "Fetch image(s) and store them in the local cache",
		Usage:   "IMAGE_URL...",
		Run:     runFetch,
	}
)

func init() {
	commands = append(commands, cmdFetch)
}

func runFetch(args []string) (exit int) {
	if len(args) < 1 {
		fmt.Fprintf(os.Stderr, "fetch: Must provide at least one image\n")
		return 1
	}

	ds := cas.NewStore(globalFlags.Dir)

	for _, img := range args {
		hash, err := fetchImage(img, ds)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%v\n", err)
			return 1
		}
		shortHash := types.ShortHash(hash)
		fmt.Println(shortHash)
	}

	return
}

// fetchImage will take an image as either a URL or a name string and import it
// into the store if found.
func fetchImage(img string, ds *cas.Store) (string, error) {
	u, err := url.Parse(img)
	if err == nil && u.Scheme == "" {
		if app := newDiscoveryApp(img); app != nil {
			fmt.Printf("rkt: starting to discover app img %s\n", img)
			u, err = discover(app)
			if err != nil {
				return "", err
			}
		}
	}
	if err != nil {
		return "", fmt.Errorf("not a valid URL (%s)", img)
	}
	if u.Scheme != "http" && u.Scheme != "https" {
		return "", fmt.Errorf("rkt only supports http or https URLs (%s)", img)
	}
	return fetchURL(u.String(), ds)
}

func fetchURL(u string, ds *cas.Store) (string, error) {
	fmt.Printf("rkt: starting to fetch img from %s\n", u)
	rem := cas.NewRemote(u, []string{})
	err := ds.ReadIndex(rem)
	if err != nil && rem.Blob == "" {
		rem, err = rem.Download(*ds)
		if err != nil {
			return "", err
		}
	}
	return rem.Blob, nil
}

func discover(app *discovery.App) (*url.URL, error) {
	ep, err := discovery.DiscoverEndpoints(*app, true)
	if err != nil {
		return nil, fmt.Errorf("discovery: %v", err)
	}
	// TODO(philips): use all available mirrors
	if globalFlags.Debug {
		fmt.Printf("discovery: trying %v\n", ep.ACI[0])
	}
	imgurl := ep.ACI[0]
	u, err := url.Parse(imgurl)
	if err != nil {
		return nil, fmt.Errorf("discovery: fetched img URL (%s) is invalid (%v)", imgurl, err)
	}
	return u, nil
}

// newDiscoveryApp creates a discovery app if the given img is an app name and
// has a URL-like structure, for example example.com/reduce-worker.
// Or it returns nil.
func newDiscoveryApp(img string) *discovery.App {
	app, err := discovery.NewAppFromString(img)
	if err != nil {
		return nil
	}
	u, err := url.Parse(app.Name.String())
	if err != nil || u.Scheme != "" {
		return nil
	}
	if _, ok := app.Labels["arch"]; !ok {
		app.Labels["arch"] = defaultArch
	}
	if _, ok := app.Labels["os"]; !ok {
		app.Labels["os"] = defaultOS
	}
	return app
}
<|endoftext|>


<commit_before>package fragbag

// BOWDiff represents the difference between two bag-of-words vectors. The
// types are quite similar, except diffFreqs represents difference between
// the frequency of a particular fragment number.
//
// The BOW difference is simply the pairwise differences of fragment
// frequencies.
type BOWDiff struct {
	library   *Library
	diffFreqs []int16
}

// NewBowDiff creates a new BOWDiff by subtracting the 'old' frequencies from
// the 'new' frequencies.
//
// NewBowDiff will panic if 'oldbow' and 'newbow' weren't generated from the
// same library.
func NewBowDiff(oldbow, newbow BOW) BOWDiff {
	mustHaveSameLibrary(oldbow, newbow)
	mustHaveSameLength(oldbow, newbow)

	dfreqs := make([]int16, len(oldbow.fragfreqs))
	for i := range oldbow.fragfreqs {
		oldfreq := oldbow.fragfreqs[i]
		newfreq := newbow.fragfreqs[i]
		dfreqs[i] = newfreq - oldfreq
	}
	return BOWDiff{
		library:   oldbow.library,
		diffFreqs: dfreqs,
	}
}

// IsSame returns true if there are no differences. (i.e., all diff frequencies
// are zero.)
func (bdiff BOWDiff) IsSame() bool {
	for _, dfreq := range bdiff.diffFreqs {
		if dfreq != 0 {
			return false
		}
	}
	return true
}
<commit_msg>Add a string representation of a BOW diff.<commit_after>package fragbag

import (
	"fmt"
	"strings"
)

// BOWDiff represents the difference between two bag-of-words vectors. The
// types are quite similar, except diffFreqs represents difference between
// the frequency of a particular fragment number.
//
// The BOW difference is simply the pairwise differences of fragment
// frequencies.
type BOWDiff struct {
	library   *Library
	diffFreqs []int16
}

// NewBowDiff creates a new BOWDiff by subtracting the 'old' frequencies from
// the 'new' frequencies.
//
// NewBowDiff will panic if 'oldbow' and 'newbow' weren't generated from the
// same library.
func NewBowDiff(oldbow, newbow BOW) BOWDiff {
	mustHaveSameLibrary(oldbow, newbow)
	mustHaveSameLength(oldbow, newbow)

	dfreqs := make([]int16, len(oldbow.fragfreqs))
	for i := range oldbow.fragfreqs {
		oldfreq := oldbow.fragfreqs[i]
		newfreq := newbow.fragfreqs[i]
		dfreqs[i] = newfreq - oldfreq
	}
	return BOWDiff{
		library:   oldbow.library,
		diffFreqs: dfreqs,
	}
}

// IsSame returns true if there are no differences. (i.e., all diff frequencies
// are zero.)
func (bdiff BOWDiff) IsSame() bool {
	for _, dfreq := range bdiff.diffFreqs {
		if dfreq != 0 {
			return false
		}
	}
	return true
}

// String returns a string representation of the BOW diff vector. Only fragments
// with non-zero differences are emitted.
//
// The output looks like
// '{fragNum: diff-frequency, fragNum: diff-frequency, ...}'.
// i.e., '{1: 4, 3: 1}' where all fragment numbers except '1' and '3' have
// a difference frequency of zero.
func (bdiff BOWDiff) String() string {
	pieces := make([]string, 0, 10)
	for i := 0; i < bdiff.library.Size(); i++ {
		freq := bdiff.diffFreqs[i]
		if freq != 0 {
			pieces = append(pieces, fmt.Sprintf("%d: %d", i, freq))
		}
	}
	return fmt.Sprintf("{%s}", strings.Join(pieces, ", "))
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/draringi/SermonStation/audio"
	"github.com/gordonklaus/portaudio"
	"fmt"
	"os"
	"os/signal"
)

func getDevice() *portaudio.DeviceInfo {
	hs, err := portaudio.HostApis()
	if err != nil {
		panic(err)
	}
	for {
		fmt.Println("Please Select an API")
		for index, api := range hs {
			fmt.Printf("%d: %s\n", index, api.Name)
		}
		var selection int
		fmt.Printf("API #: ")
		fmt.Scanf("%d", &selection)
		api := hs[selection]
		fmt.Println("Please select an input device")
		for index, dev := range api.Devices {
			fmt.Printf("%d: %s (%d channels)\n", index, dev.Name, dev.MaxInputChannels)
		}
		fmt.Printf("Device #: ")
		fmt.Scanf("%d", &selection)
		dev := api.Devices[selection]
		return dev
	}
}

func getSampleSize() int {
	for {
		var sampleSize int
		fmt.Printf("How big should a sample be? {32, 24, 16, 8} ")
		fmt.Scanf("%d", &sampleSize)
		switch sampleSize {
		case 8, 16, 24, 32:
			return sampleSize
		default:
			fmt.Println("Invalid Sample Size. Must be 32, 24, 16 or 8")
		}
	}
}

func main() {
	device := getDevice()
	fmt.Printf("Recording with %s\n", device.Name)
	var chanCount, sampleSize int
	for {
		fmt.Printf("How many channels? [1,%d] ", device.MaxInputChannels)
		fmt.Scanf("%d", &chanCount)
		if chanCount > 0 && chanCount <= device.MaxInputChannels {
			break
		} else {
			fmt.Println("Invalid number of channels")
		}
	}
	sampleSize = getSampleSize()
	var path string
	fmt.Println("Where should the audio be saved to?")
	fmt.Scanf("%s", &path)
	var params portaudio.StreamParameters
	var devParams portaudio.StreamDeviceParameters
	devParams.Channels = chanCount
	devParams.Device = device
	devParams.Latency = device.DefaultLowInputLatency
	params.SampleRate = device.DefaultSampleRate
	params.FramesPerBuffer = 128
	params.Input = devParams
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, os.Kill)
	recorder := audio.NewRecording(path, params, chanCount, sampleSize)
	fmt.Println("Starting Recording")
	recorder.start()
	fmt.Println("Recording")
	for {
		switch {
		case <-sig:
			recorder.Stop()
		case recorder.Status() == audio.STOPPED:
			fmt.Println("Recording Stopped")
			return
		default:
		}
	}
}
<commit_msg>Oh them typos<commit_after>package main

import (
	"github.com/draringi/SermonStation/audio"
	"github.com/gordonklaus/portaudio"
	"fmt"
	"os"
	"os/signal"
)

func getDevice() *portaudio.DeviceInfo {
	hs, err := portaudio.HostApis()
	if err != nil {
		panic(err)
	}
	for {
		fmt.Println("Please Select an API")
		for index, api := range hs {
			fmt.Printf("%d: %s\n", index, api.Name)
		}
		var selection int
		fmt.Printf("API #: ")
		fmt.Scanf("%d", &selection)
		api := hs[selection]
		fmt.Println("Please select an input device")
		for index, dev := range api.Devices {
			fmt.Printf("%d: %s (%d channels)\n", index, dev.Name, dev.MaxInputChannels)
		}
		fmt.Printf("Device #: ")
		fmt.Scanf("%d", &selection)
		dev := api.Devices[selection]
		return dev
	}
}

func getSampleSize() int {
	for {
		var sampleSize int
		fmt.Printf("How big should a sample be? {32, 24, 16, 8} ")
		fmt.Scanf("%d", &sampleSize)
		switch sampleSize {
		case 8, 16, 24, 32:
			return sampleSize
		default:
			fmt.Println("Invalid Sample Size. Must be 32, 24, 16 or 8")
		}
	}
}

func main() {
	device := getDevice()
	fmt.Printf("Recording with %s\n", device.Name)
	var chanCount, sampleSize int
	for {
		fmt.Printf("How many channels? [1,%d] ", device.MaxInputChannels)
		fmt.Scanf("%d", &chanCount)
		if chanCount > 0 && chanCount <= device.MaxInputChannels {
			break
		} else {
			fmt.Println("Invalid number of channels")
		}
	}
	sampleSize = getSampleSize()
	var path string
	fmt.Println("Where should the audio be saved to?")
	fmt.Scanf("%s", &path)
	var params portaudio.StreamParameters
	var devParams portaudio.StreamDeviceParameters
	devParams.Channels = chanCount
	devParams.Device = device
	devParams.Latency = device.DefaultLowInputLatency
	params.SampleRate = device.DefaultSampleRate
	params.FramesPerBuffer = 128
	params.Input = devParams
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, os.Kill)
	recorder := audio.NewRecording(path, params, chanCount, sampleSize)
	fmt.Println("Starting Recording")
	recorder.Start()
	fmt.Println("Recording")
	for {
		switch {
		case stopCmd := <-sig:
			recorder.Stop()
		case recorder.Status() == audio.STOPPED:
			fmt.Println("Recording Stopped")
			return
		default:
		}
	}
}
<|endoftext|>


<commit_before>// +build windows

package main

import (
	"testing"
)

func TestGetValue(t *testing.T) {
	var registry = realRegistry{}
	expected := `AMD64`
	actual, err := registry.GetString(REG_KEY_MACHINE, "PROCESSOR_ARCHITECTURE")
	if err != nil {
		t.Errorf("Error in SetString", err)
	}
	assertEquals(t, expected, actual)
}
<commit_msg>add formatting directive<commit_after>// +build windows

package main

import (
	"testing"
)

func TestGetValue(t *testing.T) {
	var registry = realRegistry{}
	expected := `AMD64`
	actual, err := registry.GetString(REG_KEY_MACHINE, "PROCESSOR_ARCHITECTURE")
	if err != nil {
		t.Errorf("Error in SetString: %q", err)
	}
	assertEquals(t, expected, actual)
}
<|endoftext|>


<commit_before>package main

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

	"github.com/gorilla/mux"
)

// Sparkle datatype
type Sparkle struct {
	Sparkler string    `json:"sparkler"`
	Sparklee string    `json:"sparklee"`
	Reason   string    `json:"reason,omitempty"`
	Time     time.Time `json:"time,omitempty"`
}

// Leader datatype
type Leader struct {
	Name  string `json:"name"`
	Score int    `json:"score"`
}

// Return the data in JSON format. This is the default return method.
func returnJSON(obj interface{}, w http.ResponseWriter, h *http.Request) {
	// Don't cache json returns. This is to work around ie's weird caching behavior
	w.Header().Set("Cache-Control", "no-cache")
	// Set the content type to json
	w.Header().Set("Content-Type", "application/json")

	j, err := json.Marshal(obj)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	fmt.Fprint(w, string(j))
}

// Placeholder in case anyone calls the root of the service.
// Perhaps change this to 404.
func defaultHandler(w http.ResponseWriter, h *http.Request) {
	fmt.Fprint(w, "Default sparkles")
}

// Add a sparkle!
func addSparkle(w http.ResponseWriter, h *http.Request) {
	var s Sparkle
	b := json.NewDecoder(h.Body)
	b.Decode(&s)

	result := db.AddSparkle(s)
	returnJSON(result, w, h)
}

// Get the entire data set
func getSparkles(w http.ResponseWriter, h *http.Request) {
	returnJSON(db.Sparkles, w, h)
}

// This only goes back 60 days
func topGiven(w http.ResponseWriter, h *http.Request) {
	afterDate := time.Now().AddDate(0, 0, -60)
	result := db.TopGiven(afterDate)
	returnJSON(result, w, h)
}

// This only goes back 60 days
func topReceived(w http.ResponseWriter, h *http.Request) {
	afterDate := time.Now().AddDate(0, 0, -60)
	result := db.TopReceived(afterDate)
	returnJSON(result, w, h)
}

// Get all the sparkles for someone in particular
func getSparklesForRecipient(w http.ResponseWriter, h *http.Request) {
	vars := mux.Vars(h)
	rcpt := vars["recipient"]
	sparkles := db.SparklesForUser(rcpt)
	returnJSON(sparkles, w, h)
}
<commit_msg>Putting Room back in<commit_after>package main

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

	"github.com/gorilla/mux"
)

// Sparkle datatype
type Sparkle struct {
	Sparkler string    `json:"sparkler"`
	Sparklee string    `json:"sparklee"`
	Reason   string    `json:"reason,omitempty"`
	Room     string    `json:"room,omitempty"`
	Time     time.Time `json:"time,omitempty"`
}

// Leader datatype
type Leader struct {
	Name  string `json:"name"`
	Score int    `json:"score"`
}

// Return the data in JSON format. This is the default return method.
func returnJSON(obj interface{}, w http.ResponseWriter, h *http.Request) {
	// Don't cache json returns. This is to work around ie's weird caching behavior
	w.Header().Set("Cache-Control", "no-cache")
	// Set the content type to json
	w.Header().Set("Content-Type", "application/json")

	j, err := json.Marshal(obj)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	fmt.Fprint(w, string(j))
}

// Placeholder in case anyone calls the root of the service.
// Perhaps change this to 404.
func defaultHandler(w http.ResponseWriter, h *http.Request) {
	fmt.Fprint(w, "Default sparkles")
}

// Add a sparkle!
func addSparkle(w http.ResponseWriter, h *http.Request) {
	var s Sparkle
	b := json.NewDecoder(h.Body)
	b.Decode(&s)

	result := db.AddSparkle(s)
	returnJSON(result, w, h)
}

// Get the entire data set
func getSparkles(w http.ResponseWriter, h *http.Request) {
	returnJSON(db.Sparkles, w, h)
}

// This only goes back 60 days
func topGiven(w http.ResponseWriter, h *http.Request) {
	afterDate := time.Now().AddDate(0, 0, -60)
	result := db.TopGiven(afterDate)
	returnJSON(result, w, h)
}

// This only goes back 60 days
func topReceived(w http.ResponseWriter, h *http.Request) {
	afterDate := time.Now().AddDate(0, 0, -60)
	result := db.TopReceived(afterDate)
	returnJSON(result, w, h)
}

// Get all the sparkles for someone in particular
func getSparklesForRecipient(w http.ResponseWriter, h *http.Request) {
	vars := mux.Vars(h)
	rcpt := vars["recipient"]
	sparkles := db.SparklesForUser(rcpt)
	returnJSON(sparkles, w, h)
}
<|endoftext|>


<commit_before>package geoffrey

import (
	"fmt"
	"strings"

	"log"

	"github.com/jriddick/geoffrey/irc"
	"github.com/jriddick/geoffrey/msg"
)

// MessageHandler is the function type for
// message handlers
type MessageHandler func(*Bot, msg.Message)

// Bot is the structure for an IRC bot
type Bot struct {
	client          *irc.IRC
	writer          chan<- string
	reader          <-chan *msg.Message
	config          Config
	messageHandlers []MessageHandler
}

// Config is the configuration structure for Bot
type Config struct {
	Hostname           string
	Port               int
	Secure             bool
	InsecureSkipVerify bool
	Nick               string
	User               string
	Name               string
	Channels           []string
}

// NewBot creates a new bot
func NewBot(config Config) *Bot {
	// Create the bot
	bot := &Bot{
		client: irc.NewIRC(irc.Config{
			Hostname:           config.Hostname,
			Port:               config.Port,
			Secure:             config.Secure,
			InsecureSkipVerify: config.InsecureSkipVerify,
		}),
		config: config,
	}

	return bot
}

// Connect will connect the bot to the server
func (b *Bot) Connect() error {
	// Connect the client
	if err := b.client.Connect(); err != nil {
		return err
	}

	// Get the reader and writer channels
	b.writer = b.client.Writer()
	b.reader = b.client.Reader()

	return nil
}

// Handler will start processing messages
func (b *Bot) Handler() {
	for msg := range b.reader {
		// Log all messages
		log.Println(msg.String())

		// Send nick and user after connecting
		if msg.Trailing == "*** Looking up your hostname..." {
			b.writer <- fmt.Sprintf("NICK %s", b.config.Nick)
			b.writer <- fmt.Sprintf("USER %s 0 * :%s", b.config.User, b.config.Name)
			continue
		}

		// Answer PING with PONG
		if msg.Command == "PING" {
			b.writer <- fmt.Sprintf("PONG %s", msg.Trailing)
			continue
		}

		// Join channels when ready
		if msg.Command == irc.RPL_WELCOME {
			for _, channel := range b.config.Channels {
				b.Join(channel)
			}
			continue
		}

		// Let our handlers handle PRIVMSG
		if msg.Command == "PRIVMSG" {
			go func() {
				for _, handler := range b.messageHandlers {
					handler(b, *msg)
				}
			}()
			continue
		}
	}
}

// Send will send the given message to the given receiver
func (b *Bot) Send(recv, msg string) {
	b.writer <- fmt.Sprintf("PRIVMSG %s :%s", recv, msg)
}

// Join will join the given channel
func (b *Bot) Join(channel string) {
	// Make sure we have a hashtag
	if !strings.HasPrefix(channel, "#") {
		channel = "#" + channel
	}

	// Send the join command
	b.writer <- fmt.Sprintf("JOIN %s", channel)
}

// OnMessage registeres a new PRIVMSG handler
func (b *Bot) OnMessage(handler MessageHandler) {
	b.messageHandlers = append(b.messageHandlers, handler)
}
<commit_msg>updated message handler and added handling for join and parts<commit_after>package geoffrey

import (
	"fmt"
	"strings"

	"log"

	"github.com/jriddick/geoffrey/irc"
	"github.com/jriddick/geoffrey/msg"
)

// MessageHandler is the function type for
// message handlers
type MessageHandler func(*Bot, *Channel, User, string)

// Bot is the structure for an IRC bot
type Bot struct {
	client          *irc.IRC
	writer          chan<- string
	reader          <-chan *msg.Message
	config          Config
	messageHandlers []MessageHandler
	channels        map[string]*Channel
}

// Config is the configuration structure for Bot
type Config struct {
	Hostname           string
	Port               int
	Secure             bool
	InsecureSkipVerify bool
	Nick               string
	User               string
	Name               string
	Channels           []string
}

// NewBot creates a new bot
func NewBot(config Config) *Bot {
	// Create the bot
	bot := &Bot{
		client: irc.NewIRC(irc.Config{
			Hostname:           config.Hostname,
			Port:               config.Port,
			Secure:             config.Secure,
			InsecureSkipVerify: config.InsecureSkipVerify,
		}),
		config:   config,
		channels: make(map[string]*Channel),
	}

	return bot
}

// Connect will connect the bot to the server
func (b *Bot) Connect() error {
	// Connect the client
	if err := b.client.Connect(); err != nil {
		return err
	}

	// Get the reader and writer channels
	b.writer = b.client.Writer()
	b.reader = b.client.Reader()

	return nil
}

// Handler will start processing messages
func (b *Bot) Handler() {
	for msg := range b.reader {
		// Log all messages
		log.Println(msg.String())

		// Send nick and user after connecting
		if msg.Trailing == "*** Looking up your hostname..." {
			b.writer <- fmt.Sprintf("NICK %s", b.config.Nick)
			b.writer <- fmt.Sprintf("USER %s 0 * :%s", b.config.User, b.config.Name)
			continue
		}

		// Answer PING with PONG
		if msg.Command == "PING" {
			b.writer <- fmt.Sprintf("PONG %s", msg.Trailing)
			continue
		}

		// Join channels when ready
		if msg.Command == irc.RPL_WELCOME {
			for _, channel := range b.config.Channels {
				b.Join(channel)
			}
			continue
		}

		// Handle JOINs
		if msg.Command == "JOIN" {
			// Add the channel if we just joined it
			if msg.Prefix.Name == b.config.Nick {
				// Add the channel
				b.AddChannel(msg.Trailing)
			} else {
				// Add the user
				b.channels[msg.Trailing].AddUser(msg.Prefix.Name)
			}
		}

		// Check if this is a name reply
		if msg.Command == irc.RPL_NAMREPLY {
			for _, nick := range strings.Split(msg.Trailing, " ") {
				if nick != b.config.Nick {
					b.channels[msg.Params[2]].AddUser(nick)
				}
			}
		}

		// Handle PARTs
		if msg.Command == "PART" {
			// Remove the user
			b.channels[msg.Params[0]].RemoveUser(msg.Prefix.Name)
		}

		// Let our handlers handle PRIVMSG
		if msg.Command == "PRIVMSG" {
			// Get the channel
			channel := b.channels[msg.Params[0]]

			// Get the sender
			sender := channel.Users[msg.Prefix.Name]

			// Run the handlers
			go func() {
				for _, handler := range b.messageHandlers {
					go handler(b, channel, sender, msg.Trailing)
				}
			}()
			continue
		}
	}
}

// Send will send the given message to the given receiver
func (b *Bot) Send(recv, msg string) {
	b.writer <- fmt.Sprintf("PRIVMSG %s :%s", recv, msg)
}

// Join will join the given channel
func (b *Bot) Join(channel string) {
	// Make sure we have a hashtag
	if !strings.HasPrefix(channel, "#") {
		channel = "#" + channel
	}

	// Send the join command
	b.writer <- fmt.Sprintf("JOIN %s", channel)
}

// AddChannel will add channel to list of joined channels
func (b *Bot) AddChannel(channel string) {
	// Make sure we do not replace any existing channels
	if _, ok := b.channels[channel]; ok {
		return
	}

	// Add the channel to the list
	b.channels[channel] = &Channel{
		Name: channel,
		bot:  b,
	}
}

// OnMessage registeres a new PRIVMSG handler
func (b *Bot) OnMessage(handler MessageHandler) {
	b.messageHandlers = append(b.messageHandlers, handler)
}
<|endoftext|>


<commit_before>package router551

import (
	"github.com/go51/container551"
	"github.com/go51/string551"
	"regexp"
	"runtime"
)

type routerMethod int

const (
	GET     routerMethod = 1
	POST    routerMethod = 2
	PUT     routerMethod = 4
	DELETE  routerMethod = 8
	COMMAND routerMethod = 16
	UNKNOWN routerMethod = 32
)

func (rm routerMethod) String() string {
	switch rm {
	case GET:
		return "GET"
	case POST:
		return "POST"
	case PUT:
		return "PUT"
	case DELETE:
		return "DELETE"
	case COMMAND:
		return "COMMAND"
	}
	return "UNKNOWN"
}

type ActionFunc func(c *container551.Container) interface{}

type Router struct {
	get     map[string]*route
	post    map[string]*route
	put     map[string]*route
	delete  map[string]*route
	command map[string]*route
}

var routerInstance *Router

func Load() *Router {
	if routerInstance != nil {
		return routerInstance
	}

	routerInstance = &Router{
		get:     make(map[string]*route, 0),
		post:    make(map[string]*route, 0),
		put:     make(map[string]*route, 0),
		delete:  make(map[string]*route, 0),
		command: make(map[string]*route, 0),
	}

	return routerInstance
}

type route struct {
	name        string
	pattern     string
	regex       *regexp.Regexp
	packageName string
	action      ActionFunc
	keys        []string
}

func (r *route) Name() string {
	return r.name
}

func (r *route) Keys() []string {
	return r.keys
}

func (r *route) Action() ActionFunc {
	return r.action
}

func (r *route) PackageName() string {
	return r.packageName
}

func (r *Router) Add(method routerMethod, name, pattern string, action ActionFunc) {

	pc, _, _, _ := runtime.Caller(1)
	path := runtime.FuncForPC(pc).Name()

	route := &route{
		name:        name,
		pattern:     pattern,
		regex:       nil,
		packageName: r.getPackageName(path),
		action:      action,
		keys:        []string{},
	}

	if method != COMMAND {
		route.keys = r.getKeys(pattern)
		regexPattern := pattern
		for i := 0; i < len(route.keys); i++ {
			regexPattern = string551.Replace(regexPattern, ":"+route.keys[i]+":", ".*")
		}
		route.regex = regexp.MustCompile(regexPattern)
	}

	if method&GET == GET {
		r.addGet(name, route)
	}
	if method&POST == POST {
		r.addPost(name, route)
	}
	if method&PUT == PUT {
		r.addPut(name, route)
	}
	if method&DELETE == DELETE {
		r.addDelete(name, route)
	}
	if method&COMMAND == COMMAND {
		r.addCommand(name, route)
	}
}

func (r *Router) addGet(name string, route *route) {
	r.get[name] = route
}

func (r *Router) addPost(name string, route *route) {
	r.post[name] = route
}

func (r *Router) addPut(name string, route *route) {
	r.put[name] = route
}

func (r *Router) addDelete(name string, route *route) {
	r.delete[name] = route
}

func (r *Router) addCommand(name string, route *route) {
	r.command[name] = route
}

func (r *Router) getKeys(pattern string) []string {
	keys := []string{}

	patternBytes := string551.StringToBytes(pattern)
	coron := false

	keyBytes := []byte{}

	for i := 0; i < len(patternBytes); i++ {
		if patternBytes[i] == 0x3A {
			// 0x3A => ":"
			if !coron {
				keyBytes = []byte{}
				coron = true
			} else {
				keys = append(keys, string551.BytesToString(keyBytes))
				coron = false
			}
		} else {
			if coron {
				keyBytes = append(keyBytes, patternBytes[i])
			}
		}
	}

	return keys
}

var regexpControllerPattern *regexp.Regexp

func (r *Router) getPackageName(path string) string {
	if regexpControllerPattern == nil {
		regexpControllerPattern = regexp.MustCompile(`\/\w+\.`)
	}

	packageName := regexpControllerPattern.FindString(path)

	return packageName[1 : len(packageName)-1]
}

func (r *Router) FindRouteByName(method, name string) *route {
	if method == GET.String() {
		return r.get[name]
	}
	if method == POST.String() {
		return r.post[name]
	}
	if method == PUT.String() {
		return r.put[name]
	}
	if method == DELETE.String() {
		return r.delete[name]
	}
	if method == COMMAND.String() {
		return r.command[name]
	}

	return nil
}

func (r *Router) FindRouteByPathMatch(method, path string) *route {
	routes := r.getRoutes(method)

	for _, route := range routes {
		if route.pattern == path {
			return route
		}
	}

	for _, route := range routes {
		if route.pattern == "/" {
			continue
		}
		if route.regex.MatchString(path) {
			return route
		}
	}

	return nil
}

func (r *Router) getRoutes(method string) map[string]*route {
	switch method {
	case GET.String():
		return r.get
	case POST.String():
		return r.post
	case PUT.String():
		return r.put
	case DELETE.String():
		return r.delete
	case COMMAND.String():
		return r.command
	}

	return make(map[string]*route)
}

func (r *Router) Url(name string, parameter ...string) string {

	var route *route = nil

	if r.get[name] != nil {
		route = r.get[name]
	} else if r.post[name] != nil {
		route = r.post[name]
	} else if r.put[name] != nil {
		route = r.put[name]
	} else if r.delete[name] != nil {
		route = r.delete[name]
	}

	if route == nil {
		// Not Found
		return "#"
	}

	if len(parameter) != 0 && len(parameter) != len(route.keys) {
		// No Match
		return "#"
	}

	//----------------------------------------
	// Match
	//----------------------------------------
	if len(parameter) == 0 {
		// No paramter
		return route.pattern
	}

	url := route.pattern
	keys := route.keys
	for i := 0; i < len(parameter); i++ {
		url = string551.Replace(url, ":"+keys[i]+":", parameter[i])

	}

	return url
}
<commit_msg>refs #22 マッチングする際に部分一致ではなく完全一致するように regexp.MustCompile を実施しする際に "^", "$" を付加する<commit_after>package router551

import (
	"github.com/go51/container551"
	"github.com/go51/string551"
	"regexp"
	"runtime"
)

type routerMethod int

const (
	GET     routerMethod = 1
	POST    routerMethod = 2
	PUT     routerMethod = 4
	DELETE  routerMethod = 8
	COMMAND routerMethod = 16
	UNKNOWN routerMethod = 32
)

func (rm routerMethod) String() string {
	switch rm {
	case GET:
		return "GET"
	case POST:
		return "POST"
	case PUT:
		return "PUT"
	case DELETE:
		return "DELETE"
	case COMMAND:
		return "COMMAND"
	}
	return "UNKNOWN"
}

type ActionFunc func(c *container551.Container) interface{}

type Router struct {
	get     map[string]*route
	post    map[string]*route
	put     map[string]*route
	delete  map[string]*route
	command map[string]*route
}

var routerInstance *Router

func Load() *Router {
	if routerInstance != nil {
		return routerInstance
	}

	routerInstance = &Router{
		get:     make(map[string]*route, 0),
		post:    make(map[string]*route, 0),
		put:     make(map[string]*route, 0),
		delete:  make(map[string]*route, 0),
		command: make(map[string]*route, 0),
	}

	return routerInstance
}

type route struct {
	name        string
	pattern     string
	regex       *regexp.Regexp
	packageName string
	action      ActionFunc
	keys        []string
}

func (r *route) Name() string {
	return r.name
}

func (r *route) Keys() []string {
	return r.keys
}

func (r *route) Action() ActionFunc {
	return r.action
}

func (r *route) PackageName() string {
	return r.packageName
}

func (r *Router) Add(method routerMethod, name, pattern string, action ActionFunc) {

	pc, _, _, _ := runtime.Caller(1)
	path := runtime.FuncForPC(pc).Name()

	route := &route{
		name:        name,
		pattern:     pattern,
		regex:       nil,
		packageName: r.getPackageName(path),
		action:      action,
		keys:        []string{},
	}

	if method != COMMAND {
		route.keys = r.getKeys(pattern)
		regexPattern := pattern
		for i := 0; i < len(route.keys); i++ {
			regexPattern = string551.Replace(regexPattern, ":"+route.keys[i]+":", ".*")
		}
		route.regex = regexp.MustCompile("^" + regexPattern + "$")
	}

	if method&GET == GET {
		r.addGet(name, route)
	}
	if method&POST == POST {
		r.addPost(name, route)
	}
	if method&PUT == PUT {
		r.addPut(name, route)
	}
	if method&DELETE == DELETE {
		r.addDelete(name, route)
	}
	if method&COMMAND == COMMAND {
		r.addCommand(name, route)
	}
}

func (r *Router) addGet(name string, route *route) {
	r.get[name] = route
}

func (r *Router) addPost(name string, route *route) {
	r.post[name] = route
}

func (r *Router) addPut(name string, route *route) {
	r.put[name] = route
}

func (r *Router) addDelete(name string, route *route) {
	r.delete[name] = route
}

func (r *Router) addCommand(name string, route *route) {
	r.command[name] = route
}

func (r *Router) getKeys(pattern string) []string {
	keys := []string{}

	patternBytes := string551.StringToBytes(pattern)
	coron := false

	keyBytes := []byte{}

	for i := 0; i < len(patternBytes); i++ {
		if patternBytes[i] == 0x3A {
			// 0x3A => ":"
			if !coron {
				keyBytes = []byte{}
				coron = true
			} else {
				keys = append(keys, string551.BytesToString(keyBytes))
				coron = false
			}
		} else {
			if coron {
				keyBytes = append(keyBytes, patternBytes[i])
			}
		}
	}

	return keys
}

var regexpControllerPattern *regexp.Regexp

func (r *Router) getPackageName(path string) string {
	if regexpControllerPattern == nil {
		regexpControllerPattern = regexp.MustCompile(`\/\w+\.`)
	}

	packageName := regexpControllerPattern.FindString(path)

	return packageName[1 : len(packageName)-1]
}

func (r *Router) FindRouteByName(method, name string) *route {
	if method == GET.String() {
		return r.get[name]
	}
	if method == POST.String() {
		return r.post[name]
	}
	if method == PUT.String() {
		return r.put[name]
	}
	if method == DELETE.String() {
		return r.delete[name]
	}
	if method == COMMAND.String() {
		return r.command[name]
	}

	return nil
}

func (r *Router) FindRouteByPathMatch(method, path string) *route {
	routes := r.getRoutes(method)

	for _, route := range routes {
		if route.pattern == path {
			return route
		}
	}

	for _, route := range routes {
		if route.pattern == "/" {
			continue
		}
		if route.regex.MatchString(path) {
			return route
		}
	}

	return nil
}

func (r *Router) getRoutes(method string) map[string]*route {
	switch method {
	case GET.String():
		return r.get
	case POST.String():
		return r.post
	case PUT.String():
		return r.put
	case DELETE.String():
		return r.delete
	case COMMAND.String():
		return r.command
	}

	return make(map[string]*route)
}

func (r *Router) Url(name string, parameter ...string) string {

	var route *route = nil

	if r.get[name] != nil {
		route = r.get[name]
	} else if r.post[name] != nil {
		route = r.post[name]
	} else if r.put[name] != nil {
		route = r.put[name]
	} else if r.delete[name] != nil {
		route = r.delete[name]
	}

	if route == nil {
		// Not Found
		return "#"
	}

	if len(parameter) != 0 && len(parameter) != len(route.keys) {
		// No Match
		return "#"
	}

	//----------------------------------------
	// Match
	//----------------------------------------
	if len(parameter) == 0 {
		// No paramter
		return route.pattern
	}

	url := route.pattern
	keys := route.keys
	for i := 0; i < len(parameter); i++ {
		url = string551.Replace(url, ":"+keys[i]+":", parameter[i])

	}

	return url
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"log"
	"time"

	"github.com/hashicorp/aws-sdk-go/aws"
	"github.com/hashicorp/aws-sdk-go/gen/ec2"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsVpc() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsVpcCreate,
		Read:   resourceAwsVpcRead,
		Update: resourceAwsVpcUpdate,
		Delete: resourceAwsVpcDelete,

		Schema: map[string]*schema.Schema{
			"cidr_block": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"instance_tenancy": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},

			"enable_dns_hostnames": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},

			"enable_dns_support": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},

			"main_route_table_id": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"default_network_acl_id": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"default_security_group_id": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"tags": tagsSchema(),
		},
	}
}

func resourceAwsVpcCreate(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).awsEC2conn
	instance_tenancy := "default"
	if v, ok := d.GetOk("instance_tenancy"); ok {
		instance_tenancy = v.(string)
	}
	// Create the VPC
	createOpts := &ec2.CreateVPCRequest{
		CIDRBlock:       aws.String(d.Get("cidr_block").(string)),
		InstanceTenancy: &instance_tenancy,
	}
	log.Printf("[DEBUG] VPC create config: %#v", *createOpts)
	vpcResp, err := ec2conn.CreateVPC(createOpts)
	if err != nil {
		return fmt.Errorf("Error creating VPC: %s : %s", err)
	}

	// Get the ID and store it
	vpc := vpcResp.VPC
	d.SetId(*vpc.VPCID)
	log.Printf("[INFO] VPC ID: %s", d.Id())

	// Set partial mode and say that we setup the cidr block
	d.Partial(true)
	d.SetPartial("cidr_block")

	// Wait for the VPC to become available
	log.Printf(
		"[DEBUG] Waiting for VPC (%s) to become available",
		d.Id())
	stateConf := &resource.StateChangeConf{
		Pending: []string{"pending"},
		Target:  "available",
		Refresh: VPCStateRefreshFunc(ec2conn, d.Id()),
		Timeout: 10 * time.Minute,
	}
	if _, err := stateConf.WaitForState(); err != nil {
		return fmt.Errorf(
			"Error waiting for VPC (%s) to become available: %s",
			d.Id(), err)
	}

	// Update our attributes and return
	return resourceAwsVpcUpdate(d, meta)
}

func resourceAwsVpcRead(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).awsEC2conn

	// Refresh the VPC state
	vpcRaw, _, err := VPCStateRefreshFunc(ec2conn, d.Id())()
	if err != nil {
		return err
	}
	if vpcRaw == nil {
		d.SetId("")
		return nil
	}

	// VPC stuff
	vpc := vpcRaw.(*ec2.VPC)
	vpcid := d.Id()
	d.Set("cidr_block", vpc.CIDRBlock)

	// Tags
	d.Set("tags", tagsToMapSDK(vpc.Tags))

	// Attributes
	attribute := "enableDnsSupport"
	DescribeAttrOpts := &ec2.DescribeVPCAttributeRequest{
		Attribute: &attribute,
		VPCID:     &vpcid,
	}
	resp, err := ec2conn.DescribeVPCAttribute(DescribeAttrOpts)
	if err != nil {
		return err
	}
	d.Set("enable_dns_support", *resp.EnableDNSSupport)
	attribute = "enableDnsHostnames"
	DescribeAttrOpts = &ec2.DescribeVPCAttributeRequest{
		Attribute: &attribute,
		VPCID:     &vpcid,
	}
	resp, err = ec2conn.DescribeVPCAttribute(DescribeAttrOpts)
	if err != nil {
		return err
	}
	d.Set("enable_dns_hostnames", *resp.EnableDNSHostnames)

	// Get the main routing table for this VPC
	// Really Ugly need to make this better - rmenn
	filter1 := &ec2.Filter{
		Name:   aws.String("association.main"),
		Values: []string{("true")},
	}
	filter2 := &ec2.Filter{
		Name:   aws.String("vpc-id"),
		Values: []string{(d.Id())},
	}
	DescribeRouteOpts := &ec2.DescribeRouteTablesRequest{
		Filters: []ec2.Filter{*filter1, *filter2},
	}
	routeResp, err := ec2conn.DescribeRouteTables(DescribeRouteOpts)
	if err != nil {
		return err
	}
	if v := routeResp.RouteTables; len(v) > 0 {
		d.Set("main_route_table_id", *v[0].RouteTableID)
	}

	resourceAwsVpcSetDefaultNetworkAcl(ec2conn, d)
	resourceAwsVpcSetDefaultSecurityGroup(ec2conn, d)

	return nil
}

func resourceAwsVpcUpdate(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).awsEC2conn

	// Turn on partial mode
	d.Partial(true)
	vpcid := d.Id()
	modifyOpts := &ec2.ModifyVPCAttributeRequest{
		VPCID: &vpcid,
	}
	if d.HasChange("enable_dns_hostnames") {
		val := d.Get("enable_dns_hostnames").(bool)
		modifyOpts.EnableDNSHostnames = &ec2.AttributeBooleanValue{
			Value: &val,
		}

		log.Printf(
			"[INFO] Modifying enable_dns_hostnames vpc attribute for %s: %#v",
			d.Id(), modifyOpts)
		if err := ec2conn.ModifyVPCAttribute(modifyOpts); err != nil {
			return err
		}

		d.SetPartial("enable_dns_hostnames")
	}

	if d.HasChange("enable_dns_support") {
		val := d.Get("enable_dns_hostnames").(bool)
		modifyOpts.EnableDNSSupport = &ec2.AttributeBooleanValue{
			Value: &val,
		}

		log.Printf(
			"[INFO] Modifying enable_dns_support vpc attribute for %s: %#v",
			d.Id(), modifyOpts)
		if err := ec2conn.ModifyVPCAttribute(modifyOpts); err != nil {
			return err
		}

		d.SetPartial("enable_dns_support")
	}

	if err := setTagsSDK(ec2conn, d); err != nil {
		return err
	} else {
		d.SetPartial("tags")
	}

	d.Partial(false)
	return resourceAwsVpcRead(d, meta)
}

func resourceAwsVpcDelete(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).awsEC2conn
	vpcID := d.Id()
	DeleteVpcOpts := &ec2.DeleteVPCRequest{
		VPCID: &vpcID,
	}
	log.Printf("[INFO] Deleting VPC: %s", d.Id())
	if err := ec2conn.DeleteVPC(DeleteVpcOpts); err != nil {
		ec2err, ok := err.(*aws.APIError)
		if ok && ec2err.Code == "InvalidVpcID.NotFound" {
			return nil
		}

		return fmt.Errorf("Error deleting VPC: %s", err)
	}

	return nil
}

// VPCStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// a VPC.
func VPCStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		DescribeVpcOpts := &ec2.DescribeVPCsRequest{
			VPCIDs: []string{id},
		}
		resp, err := conn.DescribeVPCs(DescribeVpcOpts)
		if err != nil {
			if ec2err, ok := err.(*aws.APIError); ok && ec2err.Code == "InvalidVpcID.NotFound" {
				resp = nil
			} else {
				log.Printf("Error on VPCStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		vpc := &resp.VPCs[0]
		return vpc, *vpc.State, nil
	}
}

func resourceAwsVpcSetDefaultNetworkAcl(conn *ec2.EC2, d *schema.ResourceData) error {
	filter1 := &ec2.Filter{
		Name:   aws.String("default"),
		Values: []string{("true")},
	}
	filter2 := &ec2.Filter{
		Name:   aws.String("vpc-id"),
		Values: []string{(d.Id())},
	}
	DescribeNetworkACLOpts := &ec2.DescribeNetworkACLsRequest{
		Filters: []ec2.Filter{*filter1, *filter2},
	}
	networkAclResp, err := conn.DescribeNetworkACLs(DescribeNetworkACLOpts)

	if err != nil {
		return err
	}
	if v := networkAclResp.NetworkACLs; len(v) > 0 {
		d.Set("default_network_acl_id", v[0].NetworkACLID)
	}

	return nil
}

func resourceAwsVpcSetDefaultSecurityGroup(conn *ec2.EC2, d *schema.ResourceData) error {
	filter1 := &ec2.Filter{
		Name:   aws.String("group-name"),
		Values: []string{("default")},
	}
	filter2 := &ec2.Filter{
		Name:   aws.String("vpc-id"),
		Values: []string{(d.Id())},
	}
	DescribeSgOpts := &ec2.DescribeSecurityGroupsRequest{
		Filters: []ec2.Filter{*filter1, *filter2},
	}
	securityGroupResp, err := conn.DescribeSecurityGroups(DescribeSgOpts)

	if err != nil {
		return err
	}
	if v := securityGroupResp.SecurityGroups; len(v) > 0 {
		d.Set("default_security_group_id", v[0].GroupID)
	}

	return nil
}
<commit_msg>Fixed Merge conflicts<commit_after>package aws

import (
	"fmt"
	"log"
	"time"

	"github.com/hashicorp/aws-sdk-go/aws"
	"github.com/hashicorp/aws-sdk-go/gen/ec2"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsVpc() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsVpcCreate,
		Read:   resourceAwsVpcRead,
		Update: resourceAwsVpcUpdate,
		Delete: resourceAwsVpcDelete,

		Schema: map[string]*schema.Schema{
			"cidr_block": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"instance_tenancy": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},

			"enable_dns_hostnames": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},

			"enable_dns_support": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},

			"main_route_table_id": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"default_network_acl_id": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"default_security_group_id": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			//			"tags": tagsSchema(),
		},
	}
}

func resourceAwsVpcCreate(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).awsEC2conn
	instance_tenancy := "default"
	if v, ok := d.GetOk("instance_tenancy"); ok {
		instance_tenancy = v.(string)
	}
	// Create the VPC
	createOpts := &ec2.CreateVPCRequest{
		CIDRBlock:       aws.String(d.Get("cidr_block").(string)),
		InstanceTenancy: &instance_tenancy,
	}
	log.Printf("[DEBUG] VPC create config: %#v", *createOpts)
	vpcResp, err := ec2conn.CreateVPC(createOpts)
	if err != nil {
		return fmt.Errorf("Error creating VPC: %s : %s", err)
	}

	// Get the ID and store it
	vpc := vpcResp.VPC
	d.SetId(*vpc.VPCID)
	log.Printf("[INFO] VPC ID: %s", d.Id())

	// Set partial mode and say that we setup the cidr block
	d.Partial(true)
	d.SetPartial("cidr_block")

	// Wait for the VPC to become available
	log.Printf(
		"[DEBUG] Waiting for VPC (%s) to become available",
		d.Id())
	stateConf := &resource.StateChangeConf{
		Pending: []string{"pending"},
		Target:  "available",
		Refresh: VPCStateRefreshFunc(ec2conn, d.Id()),
		Timeout: 10 * time.Minute,
	}
	if _, err := stateConf.WaitForState(); err != nil {
		return fmt.Errorf(
			"Error waiting for VPC (%s) to become available: %s",
			d.Id(), err)
	}

	// Update our attributes and return
	return resourceAwsVpcUpdate(d, meta)
}

func resourceAwsVpcRead(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).awsEC2conn

	// Refresh the VPC state
	vpcRaw, _, err := VPCStateRefreshFunc(ec2conn, d.Id())()
	if err != nil {
		return err
	}
	if vpcRaw == nil {
		d.SetId("")
		return nil
	}

	// VPC stuff
	vpc := vpcRaw.(*ec2.VPC)
	vpcid := d.Id()
	d.Set("cidr_block", vpc.CIDRBlock)

	// Tags
	d.Set("tags", tagsToMapSDK(vpc.Tags))

	// Attributes
	attribute := "enableDnsSupport"
	DescribeAttrOpts := &ec2.DescribeVPCAttributeRequest{
		Attribute: &attribute,
		VPCID:     &vpcid,
	}
	resp, err := ec2conn.DescribeVPCAttribute(DescribeAttrOpts)
	if err != nil {
		return err
	}
	d.Set("enable_dns_support", *resp.EnableDNSSupport)
	attribute = "enableDnsHostnames"
	DescribeAttrOpts = &ec2.DescribeVPCAttributeRequest{
		Attribute: &attribute,
		VPCID:     &vpcid,
	}
	resp, err = ec2conn.DescribeVPCAttribute(DescribeAttrOpts)
	if err != nil {
		return err
	}
	d.Set("enable_dns_hostnames", *resp.EnableDNSHostnames)

	// Get the main routing table for this VPC
	// Really Ugly need to make this better - rmenn
	filter1 := &ec2.Filter{
		Name:   aws.String("association.main"),
		Values: []string{("true")},
	}
	filter2 := &ec2.Filter{
		Name:   aws.String("vpc-id"),
		Values: []string{(d.Id())},
	}
	DescribeRouteOpts := &ec2.DescribeRouteTablesRequest{
		Filters: []ec2.Filter{*filter1, *filter2},
	}
	routeResp, err := ec2conn.DescribeRouteTables(DescribeRouteOpts)
	if err != nil {
		return err
	}
	if v := routeResp.RouteTables; len(v) > 0 {
		d.Set("main_route_table_id", *v[0].RouteTableID)
	}

	resourceAwsVpcSetDefaultNetworkAcl(ec2conn, d)
	resourceAwsVpcSetDefaultSecurityGroup(ec2conn, d)

	return nil
}

func resourceAwsVpcUpdate(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).awsEC2conn

	// Turn on partial mode
	d.Partial(true)
	vpcid := d.Id()
	modifyOpts := &ec2.ModifyVPCAttributeRequest{
		VPCID: &vpcid,
	}
	if d.HasChange("enable_dns_hostnames") {
		val := d.Get("enable_dns_hostnames").(bool)
		modifyOpts.EnableDNSHostnames = &ec2.AttributeBooleanValue{
			Value: &val,
		}

		log.Printf(
			"[INFO] Modifying enable_dns_hostnames vpc attribute for %s: %#v",
			d.Id(), modifyOpts)
		if err := ec2conn.ModifyVPCAttribute(modifyOpts); err != nil {
			return err
		}

		d.SetPartial("enable_dns_hostnames")
	}

	if d.HasChange("enable_dns_support") {
		val := d.Get("enable_dns_hostnames").(bool)
		modifyOpts.EnableDNSSupport = &ec2.AttributeBooleanValue{
			Value: &val,
		}

		log.Printf(
			"[INFO] Modifying enable_dns_support vpc attribute for %s: %#v",
			d.Id(), modifyOpts)
		if err := ec2conn.ModifyVPCAttribute(modifyOpts); err != nil {
			return err
		}

		d.SetPartial("enable_dns_support")
	}

	if err := setTagsSDK(ec2conn, d); err != nil {
		return err
	} else {
		d.SetPartial("tags")
	}

	d.Partial(false)
	return resourceAwsVpcRead(d, meta)
}

func resourceAwsVpcDelete(d *schema.ResourceData, meta interface{}) error {
	ec2conn := meta.(*AWSClient).awsEC2conn
	vpcID := d.Id()
	DeleteVpcOpts := &ec2.DeleteVPCRequest{
		VPCID: &vpcID,
	}
	log.Printf("[INFO] Deleting VPC: %s", d.Id())
	if err := ec2conn.DeleteVPC(DeleteVpcOpts); err != nil {
		ec2err, ok := err.(*aws.APIError)
		if ok && ec2err.Code == "InvalidVpcID.NotFound" {
			return nil
		}

		return fmt.Errorf("Error deleting VPC: %s", err)
	}

	return nil
}

// VPCStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// a VPC.
func VPCStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		DescribeVpcOpts := &ec2.DescribeVPCsRequest{
			VPCIDs: []string{id},
		}
		resp, err := conn.DescribeVPCs(DescribeVpcOpts)
		if err != nil {
			if ec2err, ok := err.(*aws.APIError); ok && ec2err.Code == "InvalidVpcID.NotFound" {
				resp = nil
			} else {
				log.Printf("Error on VPCStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		vpc := &resp.VPCs[0]
		return vpc, *vpc.State, nil
	}
}

func resourceAwsVpcSetDefaultNetworkAcl(conn *ec2.EC2, d *schema.ResourceData) error {
	filter1 := &ec2.Filter{
		Name:   aws.String("default"),
		Values: []string{("true")},
	}
	filter2 := &ec2.Filter{
		Name:   aws.String("vpc-id"),
		Values: []string{(d.Id())},
	}
	DescribeNetworkACLOpts := &ec2.DescribeNetworkACLsRequest{
		Filters: []ec2.Filter{*filter1, *filter2},
	}
	networkAclResp, err := conn.DescribeNetworkACLs(DescribeNetworkACLOpts)

	if err != nil {
		return err
	}
	if v := networkAclResp.NetworkACLs; len(v) > 0 {
		d.Set("default_network_acl_id", v[0].NetworkACLID)
	}

	return nil
}

func resourceAwsVpcSetDefaultSecurityGroup(conn *ec2.EC2, d *schema.ResourceData) error {
	filter1 := &ec2.Filter{
		Name:   aws.String("group-name"),
		Values: []string{("default")},
	}
	filter2 := &ec2.Filter{
		Name:   aws.String("vpc-id"),
		Values: []string{(d.Id())},
	}
	DescribeSgOpts := &ec2.DescribeSecurityGroupsRequest{
		Filters: []ec2.Filter{*filter1, *filter2},
	}
	securityGroupResp, err := conn.DescribeSecurityGroups(DescribeSgOpts)

	if err != nil {
		return err
	}
	if v := securityGroupResp.SecurityGroups; len(v) > 0 {
		d.Set("default_security_group_id", v[0].GroupID)
	}

	return nil
}
<|endoftext|>


<commit_before>package re2

import (
	"testing"
)

func BenchmarkCompile(b *testing.B) {
	expr := `.*name\s+is\s+(.+)\.`

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		re, closer := MustCompile(expr)
		defer closer.Close(re)
	}
}

func BenchmarkExpand(b *testing.B) {
	expr := `.*name\s+is\s+(.+)\.`
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	src := []byte(`
		my name is tom.
		my favorite food is sushi.
		hello, my name is bob.
		he name is hiroshi.
	`)
	dst := []byte("prefix ")
	template := []byte("name = $1")
	indexes := re.FindAllSubmatchIndex(src, -1)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for _, x := range indexes {
			_ = re.RE2Expand(dst, template, src, x)
		}
	}
}

func BenchmarkExpandString(b *testing.B) {
	expr := `.*name\s+is\s+(.+)\.`
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	src := `
		my name is tom.
		my favorite food is sushi.
		hello, my name is bob.
		he name is hiroshi.
	`
	dst := []byte("prefix ")
	template := "name = $1"
	indexes := re.FindAllSubmatchIndex([]byte(src), -1)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for _, x := range indexes {
			_ = re.RE2ExpandString(dst, template, src, x)
		}
	}
}

func BenchmarkFind(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.Find(bytes)
	}
}

func BenchmarkFindAll(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAll(bytes, -1)
	}
}

func BenchmarkFindAllIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllIndex(bytes, -1)
	}
}

func BenchmarkFindAllString(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllString(s, -1)
	}
}

func BenchmarkFindAllStringIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllStringIndex(s, -1)
	}
}

func BenchmarkFindAllStringSubmatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllStringSubmatch(s, -1)
	}
}

func BenchmarkFindAllStringSubmatchIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllStringSubmatchIndex(s, -1)
	}
}

func BenchmarkFindAllSubmatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllSubmatch(bytes, -1)
	}
}

func BenchmarkFindAllSubmatchIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllSubmatchIndex(bytes, -1)
	}
}

func BenchmarkFindIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindIndex(bytes)
	}
}

func BenchmarkFindString(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindString(s)
	}
}

func BenchmarkFindStringIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindStringIndex(s)
	}
}

func BenchmarkFindStringSubmatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindStringSubmatch(s)
	}
}

func BenchmarkFindStringSubmatchIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindStringSubmatchIndex(s)
	}
}

func BenchmarkFindSubmatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindSubmatch(bytes)
	}
}

func BenchmarkFindSubmatchIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindSubmatchIndex(bytes)
	}
}

func BenchmarkLongest(b *testing.B) {

	for i := 0; i < b.N; i++ {
		b.StopTimer()

		re, closer := MustCompile("hoge")
		defer closer.Close(re)

		b.StartTimer()

		re.Longest()

		b.StopTimer()
	}
}

func BenchmarkMatchStatic(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_, _ = Match(expr, bytes)
	}
}

func BenchmarkMatchStringStatic(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_, _ = MatchString(expr, s)
	}
}

func BenchmarkMatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.Match(bytes)
	}
}

func BenchmarkMatchString(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.MatchString(s)
	}
}

func BenchmarkNumSubexp(b *testing.B) {
	expr := "([a-z])"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.NumSubexp()
	}
}

func BenchmarkReplaceAll(b *testing.B) {
	expr := "a(x*)b"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("-ab-axxb-")
	repl := []byte("$1")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.RE2ReplaceAll(bytes, repl)
	}
}

func BenchmarkReplaceAllLiteral(b *testing.B) {
	expr := "a(x*)b"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	bytes := []byte("-ab-axxb-")
	repl := []byte("@$1@")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.ReplaceAllLiteral(bytes, repl)
	}
}

func BenchmarkReplaceAllLiteralString(b *testing.B) {
	expr := "a(x*)b"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "-ab-axxb-"
	repl := "@$1@"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.ReplaceAllLiteralString(s, repl)
	}
}

func BenchmarkReplaceAllString(b *testing.B) {
	expr := "a(x*)b"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "-ab-axxb-"
	repl := "$1"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.RE2ReplaceAllString(s, repl)
	}
}

func BenchmarkSplit(b *testing.B) {
	expr := "[0-9](;)"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	s := "abc;123;ABC;45;"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.Split(s, -1)
	}
}

func BenchmarkString(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re, closer := MustCompile(expr)
	defer closer.Close(re)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.String()
	}
}

func BenchmarkQuoteMeta(b *testing.B) {
	expr := "[foo]"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = RE2QuoteMeta(expr)
	}
}
<commit_msg>ベンチマーク処理をregexp版の使用に戻した<commit_after>package re2

import (
	"regexp"
	"testing"
)

func BenchmarkCompile(b *testing.B) {
	expr := `.*name\s+is\s+(.+)\.`

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = regexp.MustCompile(expr)
	}
}

func BenchmarkExpand(b *testing.B) {
	expr := `.*name\s+is\s+(.+)\.`
	re := regexp.MustCompile(expr)

	src := []byte(`
		my name is tom.
		my favorite food is sushi.
		hello, my name is bob.
		he name is hiroshi.
	`)
	dst := []byte("prefix ")
	template := []byte("name = $1")
	indexes := re.FindAllSubmatchIndex(src, -1)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for _, x := range indexes {
			_ = re.Expand(dst, template, src, x)
		}
	}
}

func BenchmarkExpandString(b *testing.B) {
	expr := `.*name\s+is\s+(.+)\.`
	re := regexp.MustCompile(expr)

	src := `
		my name is tom.
		my favorite food is sushi.
		hello, my name is bob.
		he name is hiroshi.
	`
	dst := []byte("prefix ")
	template := "name = $1"
	indexes := re.FindAllSubmatchIndex([]byte(src), -1)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for _, x := range indexes {
			_ = re.ExpandString(dst, template, src, x)
		}
	}
}

func BenchmarkFind(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.Find(bytes)
	}
}

func BenchmarkFindAll(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAll(bytes, -1)
	}
}

func BenchmarkFindAllIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllIndex(bytes, -1)
	}
}

func BenchmarkFindAllString(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllString(s, -1)
	}
}

func BenchmarkFindAllStringIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllStringIndex(s, -1)
	}
}

func BenchmarkFindAllStringSubmatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllStringSubmatch(s, -1)
	}
}

func BenchmarkFindAllStringSubmatchIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllStringSubmatchIndex(s, -1)
	}
}

func BenchmarkFindAllSubmatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllSubmatch(bytes, -1)
	}
}

func BenchmarkFindAllSubmatchIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindAllSubmatchIndex(bytes, -1)
	}
}

func BenchmarkFindIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindIndex(bytes)
	}
}

func BenchmarkFindString(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindString(s)
	}
}

func BenchmarkFindStringIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindStringIndex(s)
	}
}

func BenchmarkFindStringSubmatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindStringSubmatch(s)
	}
}

func BenchmarkFindStringSubmatchIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindStringSubmatchIndex(s)
	}
}

func BenchmarkFindSubmatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindSubmatch(bytes)
	}
}

func BenchmarkFindSubmatchIndex(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.FindSubmatchIndex(bytes)
	}
}

func BenchmarkLongest(b *testing.B) {

	for i := 0; i < b.N; i++ {
		b.StopTimer()

		re := regexp.MustCompile("hoge")

		b.StartTimer()

		re.Longest()

		b.StopTimer()
	}
}

func BenchmarkMatchStatic(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_, _ = regexp.Match(expr, bytes)
	}
}

func BenchmarkMatchStringStatic(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_, _ = regexp.MatchString(expr, s)
	}
}

func BenchmarkMatch(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	bytes := []byte("abc :super tom: abc :hyper bob: :tom: abc")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.Match(bytes)
	}
}

func BenchmarkMatchString(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	s := "abc :super tom: abc :hyper bob: :tom: abc"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.MatchString(s)
	}
}

func BenchmarkNumSubexp(b *testing.B) {
	expr := "([a-z])"
	re := regexp.MustCompile(expr)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.NumSubexp()
	}
}

func BenchmarkReplaceAll(b *testing.B) {
	expr := "a(x*)b"
	re := regexp.MustCompile(expr)

	bytes := []byte("-ab-axxb-")
	repl := []byte("$1")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.ReplaceAll(bytes, repl)
	}
}

func BenchmarkReplaceAllLiteral(b *testing.B) {
	expr := "a(x*)b"
	re := regexp.MustCompile(expr)

	bytes := []byte("-ab-axxb-")
	repl := []byte("@$1@")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.ReplaceAllLiteral(bytes, repl)
	}
}

func BenchmarkReplaceAllLiteralString(b *testing.B) {
	expr := "a(x*)b"
	re := regexp.MustCompile(expr)

	s := "-ab-axxb-"
	repl := "@$1@"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.ReplaceAllLiteralString(s, repl)
	}
}

func BenchmarkReplaceAllString(b *testing.B) {
	expr := "a(x*)b"
	re := regexp.MustCompile(expr)

	s := "-ab-axxb-"
	repl := "$1"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.ReplaceAllString(s, repl)
	}
}

func BenchmarkSplit(b *testing.B) {
	expr := "[0-9](;)"
	re := regexp.MustCompile(expr)

	s := "abc;123;ABC;45;"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.Split(s, -1)
	}
}

func BenchmarkString(b *testing.B) {
	expr := ":([^: ]*)\\s*tom:"
	re := regexp.MustCompile(expr)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = re.String()
	}
}

func BenchmarkQuoteMeta(b *testing.B) {
	expr := "[foo]"

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_ = regexp.QuoteMeta(expr)
	}
}
<|endoftext|>


<commit_before>package fasthttp

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"reflect"
	"sync"
	"time"
	"unsafe"
)

var (
	maxIntChars = func() int {
		switch ^uint(0) {
		case 0xffffffff:
			// 32 bit
			return 9
		case 0xffffffffffffffff:
			// 64 bit
			return 18
		default:
			panic("Unsupported architecture :)")
		}
	}()

	maxHexIntChars = func() int {
		switch ^uint(0) {
		case 0xffffffff:
			// 32 bit
			return 7
		case 0xffffffffffffffff:
			// 64 bit
			return 15
		default:
			panic("Unsupported architecture :)")
		}
	}()

	gmtLocation = func() *time.Location {
		x, err := time.LoadLocation("GMT")
		if err != nil {
			panic(fmt.Sprintf("cannot load GMT location: %s", err))
		}
		return x
	}()
)

// AppendHTTPDate appends HTTP-compliant (RFC1123) representation of date
// to dst and returns dst (which may be newly allocated).
func AppendHTTPDate(dst []byte, date time.Time) []byte {
	return date.In(gmtLocation).AppendFormat(dst, time.RFC1123)
}

// AppendUint appends n to dst and returns dst (which may be newly allocated).
func AppendUint(dst []byte, n int) []byte {
	if n < 0 {
		panic("BUG: int must be positive")
	}

	v := uintBufPool.Get()
	if v == nil {
		v = make([]byte, maxIntChars+8)
	}
	buf := v.([]byte)
	i := len(buf) - 1
	for {
		buf[i] = '0' + byte(n%10)
		n /= 10
		if n == 0 {
			break
		}
		i--
	}

	dst = append(dst, buf[i:]...)
	uintBufPool.Put(v)
	return dst
}

// ParseUint parses uint from buf.
func ParseUint(buf []byte) (int, error) {
	v, n, err := parseUintBuf(buf)
	if n != len(buf) {
		return -1, fmt.Errorf("only %b bytes out of %d bytes exhausted when parsing int %q", n, len(buf), buf)
	}
	return v, err
}

func parseUintBuf(b []byte) (int, int, error) {
	n := len(b)
	if n == 0 {
		return -1, 0, fmt.Errorf("empty integer")
	}
	v := 0
	for i := 0; i < n; i++ {
		c := b[i]
		k := c - '0'
		if k > 9 {
			if i == 0 {
				return -1, i, fmt.Errorf("unexpected first char %c. Expected 0-9", c)
			}
			return v, i, nil
		}
		if i >= maxIntChars {
			return -1, i, fmt.Errorf("too long int %q", b[:i+1])
		}
		v = 10*v + int(k)
	}
	return v, n, nil
}

// ParseUfloat parses unsigned float from buf.
func ParseUfloat(buf []byte) (float64, error) {
	if len(buf) == 0 {
		return -1, fmt.Errorf("empty float number")
	}
	b := buf
	var v uint64
	var offset float64 = 1.0
	var pointFound bool
	for i, c := range b {
		if c < '0' || c > '9' {
			if c == '.' {
				if pointFound {
					return -1, fmt.Errorf("duplicate point found in %q", buf)
				}
				pointFound = true
				continue
			}
			if c == 'e' || c == 'E' {
				if i+1 >= len(b) {
					return -1, fmt.Errorf("unexpected end of float after %c. num=%q", c, buf)
				}
				b = b[i+1:]
				minus := -1
				switch b[0] {
				case '+':
					b = b[1:]
					minus = 1
				case '-':
					b = b[1:]
				default:
					minus = 1
				}
				vv, err := ParseUint(b)
				if err != nil {
					return -1, fmt.Errorf("cannot parse exponent part of %q: %s", buf, err)
				}
				return float64(v) * offset * math.Pow10(minus*int(vv)), nil
			}
			return -1, fmt.Errorf("unexpected char found %c in %q", c, buf)
		}
		v = 10*v + uint64(c-'0')
		if pointFound {
			offset /= 10
		}
	}
	return float64(v) * offset, nil
}

func readHexInt(r *bufio.Reader) (int, error) {
	n := 0
	i := 0
	var k int
	for {
		c, err := r.ReadByte()
		if err != nil {
			if err == io.EOF && i > 0 {
				return n, nil
			}
			return -1, err
		}
		k = hexbyte2int(c)
		if k < 0 {
			if i == 0 {
				return -1, fmt.Errorf("cannot read hex num from empty string")
			}
			r.UnreadByte()
			return n, nil
		}
		if i >= maxHexIntChars {
			return -1, fmt.Errorf("cannot read hex num with more than %d digits", maxHexIntChars)
		}
		n = (n << 4) | k
		i++
	}
}

var uintBufPool sync.Pool

func writeHexInt(w *bufio.Writer, n int) error {
	if n < 0 {
		panic("BUG: int must be positive")
	}

	v := uintBufPool.Get()
	if v == nil {
		v = make([]byte, maxIntChars+8)
	}
	buf := v.([]byte)
	i := len(buf) - 1
	for {
		buf[i] = int2hexbyte(n & 0xf)
		n >>= 4
		if n == 0 {
			break
		}
		i--
	}
	_, err := w.Write(buf[i:])
	uintBufPool.Put(v)
	return err
}

func int2hexbyte(n int) byte {
	if n < 10 {
		return '0' + byte(n)
	}
	return 'a' + byte(n) - 10
}

func hexbyte2int(c byte) int {
	if c >= '0' && c <= '9' {
		return int(c - '0')
	}
	if c >= 'a' && c <= 'f' {
		return int(c - 'a' + 10)
	}
	if c >= 'A' && c <= 'F' {
		return int(c - 'A' + 10)
	}
	return -1
}

const toLower = 'a' - 'A'

func uppercaseByte(p *byte) {
	c := *p
	if c >= 'a' && c <= 'z' {
		*p = c - toLower
	}
}

func lowercaseByte(p *byte) {
	c := *p
	if c >= 'A' && c <= 'Z' {
		*p = c + toLower
	}
}

func lowercaseBytes(b []byte) {
	for i, n := 0, len(b); i < n; i++ {
		lowercaseByte(&b[i])
	}
}

// unsafeBytesToStr converts byte slice to a string without memory allocation.
// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func unsafeBytesToStr(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}

// unsafeStrToBytes converts string to byte slice without memory allocation.
//
// The returned byte slice may be read until references to the original s exist.
func unsafeStrToBytes(s string) []byte {
	sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
	bh := reflect.SliceHeader{
		Data: sh.Data,
		Len:  sh.Len,
		Cap:  sh.Len,
	}
	return *(*[]byte)(unsafe.Pointer(&bh))
}

func unhex(c byte) int {
	if c >= '0' && c <= '9' {
		return int(c - '0')
	}
	if c >= 'a' && c <= 'f' {
		return 10 + int(c-'a')
	}
	if c >= 'A' && c <= 'F' {
		return 10 + int(c-'A')
	}
	return -1
}

func appendQuotedArg(dst, v []byte) []byte {
	for _, c := range v {
		if c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '/' || c == '.' {
			dst = append(dst, c)
		} else {
			dst = append(dst, '%', hexChar(c>>4), hexChar(c&15))
		}
	}
	return dst
}

func hexChar(c byte) byte {
	if c < 10 {
		return '0' + c
	}
	return c - 10 + 'A'
}

// EqualBytesStr returns true if string(b) == s.
//
// This function has no performance benefits comparing to string(b) == s.
// It is left here for backwards compatilbility only.
func EqualBytesStr(b []byte, s string) bool {
	return string(b) == s
}

// AppendBytesStr appends src to dst and returns dst
// (which may be newly allocated).
func AppendBytesStr(dst []byte, src string) []byte {
	// The following code is equivalent to
	//     return append(dst, []byte(src)...)
	// but it is 1.5x faster in Go1.5. I don't know why :)
	return append(dst, unsafeStrToBytes(src)...)
}
<commit_msg>Use the most optimized AppendBytesStr() implementation - append(dst, src..) :)<commit_after>package fasthttp

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"sync"
	"time"
	"unsafe"
)

var (
	maxIntChars = func() int {
		switch ^uint(0) {
		case 0xffffffff:
			// 32 bit
			return 9
		case 0xffffffffffffffff:
			// 64 bit
			return 18
		default:
			panic("Unsupported architecture :)")
		}
	}()

	maxHexIntChars = func() int {
		switch ^uint(0) {
		case 0xffffffff:
			// 32 bit
			return 7
		case 0xffffffffffffffff:
			// 64 bit
			return 15
		default:
			panic("Unsupported architecture :)")
		}
	}()

	gmtLocation = func() *time.Location {
		x, err := time.LoadLocation("GMT")
		if err != nil {
			panic(fmt.Sprintf("cannot load GMT location: %s", err))
		}
		return x
	}()
)

// AppendHTTPDate appends HTTP-compliant (RFC1123) representation of date
// to dst and returns dst (which may be newly allocated).
func AppendHTTPDate(dst []byte, date time.Time) []byte {
	return date.In(gmtLocation).AppendFormat(dst, time.RFC1123)
}

// AppendUint appends n to dst and returns dst (which may be newly allocated).
func AppendUint(dst []byte, n int) []byte {
	if n < 0 {
		panic("BUG: int must be positive")
	}

	v := uintBufPool.Get()
	if v == nil {
		v = make([]byte, maxIntChars+8)
	}
	buf := v.([]byte)
	i := len(buf) - 1
	for {
		buf[i] = '0' + byte(n%10)
		n /= 10
		if n == 0 {
			break
		}
		i--
	}

	dst = append(dst, buf[i:]...)
	uintBufPool.Put(v)
	return dst
}

// ParseUint parses uint from buf.
func ParseUint(buf []byte) (int, error) {
	v, n, err := parseUintBuf(buf)
	if n != len(buf) {
		return -1, fmt.Errorf("only %b bytes out of %d bytes exhausted when parsing int %q", n, len(buf), buf)
	}
	return v, err
}

func parseUintBuf(b []byte) (int, int, error) {
	n := len(b)
	if n == 0 {
		return -1, 0, fmt.Errorf("empty integer")
	}
	v := 0
	for i := 0; i < n; i++ {
		c := b[i]
		k := c - '0'
		if k > 9 {
			if i == 0 {
				return -1, i, fmt.Errorf("unexpected first char %c. Expected 0-9", c)
			}
			return v, i, nil
		}
		if i >= maxIntChars {
			return -1, i, fmt.Errorf("too long int %q", b[:i+1])
		}
		v = 10*v + int(k)
	}
	return v, n, nil
}

// ParseUfloat parses unsigned float from buf.
func ParseUfloat(buf []byte) (float64, error) {
	if len(buf) == 0 {
		return -1, fmt.Errorf("empty float number")
	}
	b := buf
	var v uint64
	var offset float64 = 1.0
	var pointFound bool
	for i, c := range b {
		if c < '0' || c > '9' {
			if c == '.' {
				if pointFound {
					return -1, fmt.Errorf("duplicate point found in %q", buf)
				}
				pointFound = true
				continue
			}
			if c == 'e' || c == 'E' {
				if i+1 >= len(b) {
					return -1, fmt.Errorf("unexpected end of float after %c. num=%q", c, buf)
				}
				b = b[i+1:]
				minus := -1
				switch b[0] {
				case '+':
					b = b[1:]
					minus = 1
				case '-':
					b = b[1:]
				default:
					minus = 1
				}
				vv, err := ParseUint(b)
				if err != nil {
					return -1, fmt.Errorf("cannot parse exponent part of %q: %s", buf, err)
				}
				return float64(v) * offset * math.Pow10(minus*int(vv)), nil
			}
			return -1, fmt.Errorf("unexpected char found %c in %q", c, buf)
		}
		v = 10*v + uint64(c-'0')
		if pointFound {
			offset /= 10
		}
	}
	return float64(v) * offset, nil
}

func readHexInt(r *bufio.Reader) (int, error) {
	n := 0
	i := 0
	var k int
	for {
		c, err := r.ReadByte()
		if err != nil {
			if err == io.EOF && i > 0 {
				return n, nil
			}
			return -1, err
		}
		k = hexbyte2int(c)
		if k < 0 {
			if i == 0 {
				return -1, fmt.Errorf("cannot read hex num from empty string")
			}
			r.UnreadByte()
			return n, nil
		}
		if i >= maxHexIntChars {
			return -1, fmt.Errorf("cannot read hex num with more than %d digits", maxHexIntChars)
		}
		n = (n << 4) | k
		i++
	}
}

var uintBufPool sync.Pool

func writeHexInt(w *bufio.Writer, n int) error {
	if n < 0 {
		panic("BUG: int must be positive")
	}

	v := uintBufPool.Get()
	if v == nil {
		v = make([]byte, maxIntChars+8)
	}
	buf := v.([]byte)
	i := len(buf) - 1
	for {
		buf[i] = int2hexbyte(n & 0xf)
		n >>= 4
		if n == 0 {
			break
		}
		i--
	}
	_, err := w.Write(buf[i:])
	uintBufPool.Put(v)
	return err
}

func int2hexbyte(n int) byte {
	if n < 10 {
		return '0' + byte(n)
	}
	return 'a' + byte(n) - 10
}

func hexbyte2int(c byte) int {
	if c >= '0' && c <= '9' {
		return int(c - '0')
	}
	if c >= 'a' && c <= 'f' {
		return int(c - 'a' + 10)
	}
	if c >= 'A' && c <= 'F' {
		return int(c - 'A' + 10)
	}
	return -1
}

const toLower = 'a' - 'A'

func uppercaseByte(p *byte) {
	c := *p
	if c >= 'a' && c <= 'z' {
		*p = c - toLower
	}
}

func lowercaseByte(p *byte) {
	c := *p
	if c >= 'A' && c <= 'Z' {
		*p = c + toLower
	}
}

func lowercaseBytes(b []byte) {
	for i, n := 0, len(b); i < n; i++ {
		lowercaseByte(&b[i])
	}
}

// unsafeBytesToStr converts byte slice to a string without memory allocation.
// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func unsafeBytesToStr(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}

func unhex(c byte) int {
	if c >= '0' && c <= '9' {
		return int(c - '0')
	}
	if c >= 'a' && c <= 'f' {
		return 10 + int(c-'a')
	}
	if c >= 'A' && c <= 'F' {
		return 10 + int(c-'A')
	}
	return -1
}

func appendQuotedArg(dst, v []byte) []byte {
	for _, c := range v {
		if c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '/' || c == '.' {
			dst = append(dst, c)
		} else {
			dst = append(dst, '%', hexChar(c>>4), hexChar(c&15))
		}
	}
	return dst
}

func hexChar(c byte) byte {
	if c < 10 {
		return '0' + c
	}
	return c - 10 + 'A'
}

// EqualBytesStr returns true if string(b) == s.
//
// This function has no performance benefits comparing to string(b) == s.
// It is left here for backwards compatibility only.
func EqualBytesStr(b []byte, s string) bool {
	return string(b) == s
}

// AppendBytesStr appends src to dst and returns dst
// (which may be newly allocated).
//
// This function has no performance benefits comparint to append(dst, src...).
// It is left here for backwards compatibility only.
func AppendBytesStr(dst []byte, src string) []byte {
	return append(dst, src...)
}
<|endoftext|>