<commit_before>/*
Package cron implements a cron spec parser and job runner.

Installation

To download the specific tagged release, run:

	go get github.com/robfig/cron/v3@v3.0.0

Import it in your program as:

	import "github.com/robfig/cron/v3"

It requires Go 1.11 or later due to usage of Go Modules.

Usage

Callers may register Funcs to be invoked on a given schedule.  Cron will run
them in their own goroutines.

	c := cron.New()
	c.AddFunc("30 * * * *", func() { fmt.Println("Every hour on the half hour") })
	c.AddFunc("30 3-6,20-23 * * *", func() { fmt.Println(".. in the range 3-6am, 8-11pm") })
	c.AddFunc("CRON_TZ=Asia/Tokyo 30 04 * * * *", func() { fmt.Println("Runs at 04:30 Tokyo time every day") })
	c.AddFunc("@hourly",      func() { fmt.Println("Every hour, starting an hour from now") })
	c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty, starting an hour thirty from now") })
	c.Start()
	..
	// Funcs are invoked in their own goroutine, asynchronously.
	...
	// Funcs may also be added to a running Cron
	c.AddFunc("@daily", func() { fmt.Println("Every day") })
	..
	// Inspect the cron job entries' next and previous run times.
	inspect(c.Entries())
	..
	c.Stop()  // Stop the scheduler (does not stop any jobs already running).

CRON Expression Format

A cron expression represents a set of times, using 5 space-separated fields.

	Field name   | Mandatory? | Allowed values  | Allowed special characters
	----------   | ---------- | --------------  | --------------------------
	Minutes      | Yes        | 0-59            | * / , -
	Hours        | Yes        | 0-23            | * / , -
	Day of month | Yes        | 1-31            | * / , - ?
	Month        | Yes        | 1-12 or JAN-DEC | * / , -
	Day of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?

Month and Day-of-week field values are case insensitive.  "SUN", "Sun", and
"sun" are equally accepted.

The specific interpretation of the format is based on the Cron Wikipedia page:
https://en.wikipedia.org/wiki/Cron

Alternative Formats

Alternative Cron expression formats support other fields like seconds. You can
implement that by creating a custom Parser as follows.

	cron.New(
		cron.WithParser(
			cron.NewParser(
				cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)))

Since adding Seconds is the most common modification to the standard cron spec,
cron provides a builtin function to do that, which is equivalent to the custom
parser you saw earlier, except that its seconds field is REQUIRED:

	cron.New(cron.WithSeconds())

That emulates Quartz, the most popular alternative Cron schedule format:
http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html

Special Characters

Asterisk ( * )

The asterisk indicates that the cron expression will match for all values of the
field; e.g., using an asterisk in the 5th field (month) would indicate every
month.

Slash ( / )

Slashes are used to describe increments of ranges. For example 3-59/15 in the
1st field (minutes) would indicate the 3rd minute of the hour and every 15
minutes thereafter. The form "*\/..." is equivalent to the form "first-last/...",
that is, an increment over the largest possible range of the field.  The form
"N/..." is accepted as meaning "N-MAX/...", that is, starting at N, use the
increment until the end of that specific range.  It does not wrap around.

Comma ( , )

Commas are used to separate items of a list. For example, using "MON,WED,FRI" in
the 5th field (day of week) would mean Mondays, Wednesdays and Fridays.

Hyphen ( - )

Hyphens are used to define ranges. For example, 9-17 would indicate every
hour between 9am and 5pm inclusive.

Question mark ( ? )

Question mark may be used instead of '*' for leaving either day-of-month or
day-of-week blank.

Predefined schedules

You may use one of several pre-defined schedules in place of a cron expression.

	Entry                  | Description                                | Equivalent To
	-----                  | -----------                                | -------------
	@yearly (or @annually) | Run once a year, midnight, Jan. 1st        | 0 0 1 1 *
	@monthly               | Run once a month, midnight, first of month | 0 0 1 * *
	@weekly                | Run once a week, midnight between Sat/Sun  | 0 0 * * 0
	@daily (or @midnight)  | Run once a day, midnight                   | 0 0 * * *
	@hourly                | Run once an hour, beginning of hour        | 0 * * * *

Intervals

You may also schedule a job to execute at fixed intervals, starting at the time it's added
or cron is run. This is supported by formatting the cron spec like this:

    @every <duration>

where "duration" is a string accepted by time.ParseDuration
(http://golang.org/pkg/time/#ParseDuration).

For example, "@every 1h30m10s" would indicate a schedule that activates after
1 hour, 30 minutes, 10 seconds, and then every interval after that.

Note: The interval does not take the job runtime into account.  For example,
if a job takes 3 minutes to run, and it is scheduled to run every 5 minutes,
it will have only 2 minutes of idle time between each run.

Time zones

By default, all interpretation and scheduling is done in the machine's local
time zone (time.Local). You can specify a different time zone on construction:

      cron.New(
          cron.WithLocation(time.UTC))

Individual cron schedules may also override the time zone they are to be
interpreted in by providing an additional space-separated field at the beginning
of the cron spec, of the form "CRON_TZ=Asia/Tokyo".

For example:

	# Runs at 6am in time.Local
	cron.New().AddFunc("0 6 * * ?", ...)

	# Runs at 6am in America/New_York
	nyc, _ := time.LoadLocation("America/New_York")
	c := cron.New(cron.WithLocation(nyc))
	c.AddFunc("0 6 * * ?", ...)

	# Runs at 6am in Asia/Tokyo
	cron.New().AddFunc("CRON_TZ=Asia/Tokyo 0 6 * * ?", ...)

	# Runs at 6am in Asia/Tokyo
	c := cron.New(cron.WithLocation(nyc))
	c.SetLocation("America/New_York")
	c.AddFunc("CRON_TZ=Asia/Tokyo 0 6 * * ?", ...)

The prefix "TZ=(TIME ZONE)" is also supported for legacy compatibility.

Be aware that jobs scheduled during daylight-savings leap-ahead transitions will
not be run!

Job Wrappers

A Cron runner may be configured with a chain of job wrappers to add
cross-cutting functionality to all submitted jobs. For example, they may be used
to achieve the following effects:

  - Recover any panics from jobs (activated by default)
  - Delay a job's execution if the previous run hasn't completed yet
  - Skip a job's execution if the previous run hasn't completed yet
  - Log each job's invocations

Install wrappers for all jobs added to a cron using the `cron.WithChain` option:

	cron.New(cron.WithChain(
		cron.SkipIfStillRunning(logger),
	))

Install wrappers for individual jobs by explicitly wrapping them:

	job = cron.NewChain(
		cron.SkipIfStillRunning(logger),
	).Then(job)

Thread safety

Since the Cron service runs concurrently with the calling code, some amount of
care must be taken to ensure proper synchronization.

All cron methods are designed to be correctly synchronized as long as the caller
ensures that invocations have a clear happens-before ordering between them.

Logging

Cron defines a Logger interface that is a subset of the one defined in
github.com/go-logr/logr. It has two logging levels (Info and Error), and
parameters are key/value pairs. This makes it possible for cron logging to plug
into structured logging systems. An adapter, [Verbose]PrintfLogger, is provided
to wrap the standard library *log.Logger.

For additional insight into Cron operations, verbose logging may be activated
which will record job runs, scheduling decisions, and added or removed jobs.
Activate it with a one-off logger as follows:

	cron.New(
		cron.WithLogger(
			cron.VerbosePrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags))))

Implementation

Cron entries are stored in an array, sorted by their next activation time.  Cron
sleeps until the next job is due to be run.

Upon waking:
 - it runs each entry that is active on that second
 - it calculates the next run times for the jobs that were run
 - it re-sorts the array of entries by next activation time.
 - it goes to sleep until the soonest job.
*/
package cron
<commit_msg>docs: remove redundant asterisk in example<commit_after>/*
Package cron implements a cron spec parser and job runner.

Installation

To download the specific tagged release, run:

	go get github.com/robfig/cron/v3@v3.0.0

Import it in your program as:

	import "github.com/robfig/cron/v3"

It requires Go 1.11 or later due to usage of Go Modules.

Usage

Callers may register Funcs to be invoked on a given schedule.  Cron will run
them in their own goroutines.

	c := cron.New()
	c.AddFunc("30 * * * *", func() { fmt.Println("Every hour on the half hour") })
	c.AddFunc("30 3-6,20-23 * * *", func() { fmt.Println(".. in the range 3-6am, 8-11pm") })
	c.AddFunc("CRON_TZ=Asia/Tokyo 30 04 * * *", func() { fmt.Println("Runs at 04:30 Tokyo time every day") })
	c.AddFunc("@hourly",      func() { fmt.Println("Every hour, starting an hour from now") })
	c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty, starting an hour thirty from now") })
	c.Start()
	..
	// Funcs are invoked in their own goroutine, asynchronously.
	...
	// Funcs may also be added to a running Cron
	c.AddFunc("@daily", func() { fmt.Println("Every day") })
	..
	// Inspect the cron job entries' next and previous run times.
	inspect(c.Entries())
	..
	c.Stop()  // Stop the scheduler (does not stop any jobs already running).

CRON Expression Format

A cron expression represents a set of times, using 5 space-separated fields.

	Field name   | Mandatory? | Allowed values  | Allowed special characters
	----------   | ---------- | --------------  | --------------------------
	Minutes      | Yes        | 0-59            | * / , -
	Hours        | Yes        | 0-23            | * / , -
	Day of month | Yes        | 1-31            | * / , - ?
	Month        | Yes        | 1-12 or JAN-DEC | * / , -
	Day of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?

Month and Day-of-week field values are case insensitive.  "SUN", "Sun", and
"sun" are equally accepted.

The specific interpretation of the format is based on the Cron Wikipedia page:
https://en.wikipedia.org/wiki/Cron

Alternative Formats

Alternative Cron expression formats support other fields like seconds. You can
implement that by creating a custom Parser as follows.

	cron.New(
		cron.WithParser(
			cron.NewParser(
				cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)))

Since adding Seconds is the most common modification to the standard cron spec,
cron provides a builtin function to do that, which is equivalent to the custom
parser you saw earlier, except that its seconds field is REQUIRED:

	cron.New(cron.WithSeconds())

That emulates Quartz, the most popular alternative Cron schedule format:
http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html

Special Characters

Asterisk ( * )

The asterisk indicates that the cron expression will match for all values of the
field; e.g., using an asterisk in the 5th field (month) would indicate every
month.

Slash ( / )

Slashes are used to describe increments of ranges. For example 3-59/15 in the
1st field (minutes) would indicate the 3rd minute of the hour and every 15
minutes thereafter. The form "*\/..." is equivalent to the form "first-last/...",
that is, an increment over the largest possible range of the field.  The form
"N/..." is accepted as meaning "N-MAX/...", that is, starting at N, use the
increment until the end of that specific range.  It does not wrap around.

Comma ( , )

Commas are used to separate items of a list. For example, using "MON,WED,FRI" in
the 5th field (day of week) would mean Mondays, Wednesdays and Fridays.

Hyphen ( - )

Hyphens are used to define ranges. For example, 9-17 would indicate every
hour between 9am and 5pm inclusive.

Question mark ( ? )

Question mark may be used instead of '*' for leaving either day-of-month or
day-of-week blank.

Predefined schedules

You may use one of several pre-defined schedules in place of a cron expression.

	Entry                  | Description                                | Equivalent To
	-----                  | -----------                                | -------------
	@yearly (or @annually) | Run once a year, midnight, Jan. 1st        | 0 0 1 1 *
	@monthly               | Run once a month, midnight, first of month | 0 0 1 * *
	@weekly                | Run once a week, midnight between Sat/Sun  | 0 0 * * 0
	@daily (or @midnight)  | Run once a day, midnight                   | 0 0 * * *
	@hourly                | Run once an hour, beginning of hour        | 0 * * * *

Intervals

You may also schedule a job to execute at fixed intervals, starting at the time it's added
or cron is run. This is supported by formatting the cron spec like this:

    @every <duration>

where "duration" is a string accepted by time.ParseDuration
(http://golang.org/pkg/time/#ParseDuration).

For example, "@every 1h30m10s" would indicate a schedule that activates after
1 hour, 30 minutes, 10 seconds, and then every interval after that.

Note: The interval does not take the job runtime into account.  For example,
if a job takes 3 minutes to run, and it is scheduled to run every 5 minutes,
it will have only 2 minutes of idle time between each run.

Time zones

By default, all interpretation and scheduling is done in the machine's local
time zone (time.Local). You can specify a different time zone on construction:

      cron.New(
          cron.WithLocation(time.UTC))

Individual cron schedules may also override the time zone they are to be
interpreted in by providing an additional space-separated field at the beginning
of the cron spec, of the form "CRON_TZ=Asia/Tokyo".

For example:

	# Runs at 6am in time.Local
	cron.New().AddFunc("0 6 * * ?", ...)

	# Runs at 6am in America/New_York
	nyc, _ := time.LoadLocation("America/New_York")
	c := cron.New(cron.WithLocation(nyc))
	c.AddFunc("0 6 * * ?", ...)

	# Runs at 6am in Asia/Tokyo
	cron.New().AddFunc("CRON_TZ=Asia/Tokyo 0 6 * * ?", ...)

	# Runs at 6am in Asia/Tokyo
	c := cron.New(cron.WithLocation(nyc))
	c.SetLocation("America/New_York")
	c.AddFunc("CRON_TZ=Asia/Tokyo 0 6 * * ?", ...)

The prefix "TZ=(TIME ZONE)" is also supported for legacy compatibility.

Be aware that jobs scheduled during daylight-savings leap-ahead transitions will
not be run!

Job Wrappers

A Cron runner may be configured with a chain of job wrappers to add
cross-cutting functionality to all submitted jobs. For example, they may be used
to achieve the following effects:

  - Recover any panics from jobs (activated by default)
  - Delay a job's execution if the previous run hasn't completed yet
  - Skip a job's execution if the previous run hasn't completed yet
  - Log each job's invocations

Install wrappers for all jobs added to a cron using the `cron.WithChain` option:

	cron.New(cron.WithChain(
		cron.SkipIfStillRunning(logger),
	))

Install wrappers for individual jobs by explicitly wrapping them:

	job = cron.NewChain(
		cron.SkipIfStillRunning(logger),
	).Then(job)

Thread safety

Since the Cron service runs concurrently with the calling code, some amount of
care must be taken to ensure proper synchronization.

All cron methods are designed to be correctly synchronized as long as the caller
ensures that invocations have a clear happens-before ordering between them.

Logging

Cron defines a Logger interface that is a subset of the one defined in
github.com/go-logr/logr. It has two logging levels (Info and Error), and
parameters are key/value pairs. This makes it possible for cron logging to plug
into structured logging systems. An adapter, [Verbose]PrintfLogger, is provided
to wrap the standard library *log.Logger.

For additional insight into Cron operations, verbose logging may be activated
which will record job runs, scheduling decisions, and added or removed jobs.
Activate it with a one-off logger as follows:

	cron.New(
		cron.WithLogger(
			cron.VerbosePrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags))))

Implementation

Cron entries are stored in an array, sorted by their next activation time.  Cron
sleeps until the next job is due to be run.

Upon waking:
 - it runs each entry that is active on that second
 - it calculates the next run times for the jobs that were run
 - it re-sorts the array of entries by next activation time.
 - it goes to sleep until the soonest job.
*/
package cron
<|endoftext|>


<commit_before>/*
Package gorocksdb provides the ability to create and access RocksDB databases.

gorocksdb.OpenDb opens and creates databases.

	opts := gorocksdb.NewDefaultOptions()
	opts.SetBlockCache(gorocksdb.NewLRUCache(3<<30))
	opts.SetCreateIfMissing(true)
	db, err := gorocksdb.OpenDb(opts, "/path/to/db")

The DB struct returned by OpenDb provides DB.Get, DB.Put, DB.Merge and DB.Delete to modify
and query the database.

	ro := gorocksdb.NewDefaultReadOptions()
	wo := gorocksdb.NewDefaultWriteOptions()
	// if ro and wo are not used again, be sure to Close them.
	err = db.Put(wo, []byte("foo"), []byte("bar"))
	...
	value, err := db.Get(ro, []byte("foo"))
	defer value.Free()
	...
	err = db.Delete(wo, []byte("foo"))

For bulk reads, use an Iterator. If you want to avoid disturbing your live
traffic while doing the bulk read, be sure to call SetFillCache(false) on the
ReadOptions you use when creating the Iterator.

	ro := gorocksdb.NewDefaultReadOptions()
	ro.SetFillCache(false)
	it := db.NewIterator(ro)
	defer it.Close()
	it.Seek([]byte("foo"))
	for it = it; it.Valid(); it.Next() {
		key := it.Key()
		value := it.Value()
		fmt.Printf("Key: %v Value: %v\n", key.Data(), value.Data())
		key.Free()
		value.Free()
	}
	if err := it.Err(); err != nil {
		...
	}

Batched, atomic writes can be performed with a WriteBatch and
DB.Write.

	wb := gorocksdb.NewWriteBatch()
	// defer wb.Close or use wb.Clear and reuse.
	wb.Delete([]byte("foo"))
	wb.Put([]byte("foo"), []byte("bar"))
	wb.Put([]byte("bar"), []byte("foo"))
	err := db.Write(wo, wb)

If your working dataset does not fit in memory, you'll want to add a bloom
filter to your database. NewBloomFilter and Options.SetFilterPolicy is what
you want. NewBloomFilter is amount of bits in the filter to use per key in
your database.

	filter := gorocksdb.NewBloomFilter(10)
	opts.SetFilterPolicy(filter)
	db, err := gorocksdb.OpenDb(opts, "/path/to/db")

If you're using a custom comparator in your code, be aware you may have to
make your own filter policy object.

This documentation is not a complete discussion of RocksDB. Please read the
RocksDB documentation <http://rocksdb.org/> for information on its
operation. You'll find lots of goodies there.
*/
package rdb
<commit_msg>Update docs<commit_after>/*
Package gorocksdb provides the ability to create and access RocksDB databases.

gorocksdb.OpenDb opens and creates databases.

	bbto := gorocksdb.NewDefaultBlockBasedTableOptions()
	bbto.SetBlockCache(gorocksdb.NewLRUCache(3 << 30))
	opts := gorocksdb.NewDefaultOptions()
	opts.SetBlockBasedTableFactory(bbto)
	opts.SetCreateIfMissing(true)
	db, err := gorocksdb.OpenDb(opts, "/path/to/db")

The DB struct returned by OpenDb provides DB.Get, DB.Put, DB.Merge and DB.Delete to modify
and query the database.

	ro := gorocksdb.NewDefaultReadOptions()
	wo := gorocksdb.NewDefaultWriteOptions()
	// if ro and wo are not used again, be sure to Close them.
	err = db.Put(wo, []byte("foo"), []byte("bar"))
	...
	value, err := db.Get(ro, []byte("foo"))
	defer value.Free()
	...
	err = db.Delete(wo, []byte("foo"))

For bulk reads, use an Iterator. If you want to avoid disturbing your live
traffic while doing the bulk read, be sure to call SetFillCache(false) on the
ReadOptions you use when creating the Iterator.

	ro := gorocksdb.NewDefaultReadOptions()
	ro.SetFillCache(false)
	it := db.NewIterator(ro)
	defer it.Close()
	it.Seek([]byte("foo"))
	for it = it; it.Valid(); it.Next() {
		key := it.Key()
		value := it.Value()
		fmt.Printf("Key: %v Value: %v\n", key.Data(), value.Data())
		key.Free()
		value.Free()
	}
	if err := it.Err(); err != nil {
		...
	}

Batched, atomic writes can be performed with a WriteBatch and
DB.Write.

	wb := gorocksdb.NewWriteBatch()
	// defer wb.Close or use wb.Clear and reuse.
	wb.Delete([]byte("foo"))
	wb.Put([]byte("foo"), []byte("bar"))
	wb.Put([]byte("bar"), []byte("foo"))
	err := db.Write(wo, wb)

If your working dataset does not fit in memory, you'll want to add a bloom
filter to your database. NewBloomFilter and Options.SetFilterPolicy is what
you want. NewBloomFilter is amount of bits in the filter to use per key in
your database.

	filter := gorocksdb.NewBloomFilter(10)
	bbto := gorocksdb.NewDefaultBlockBasedTableOptions()
	bbto.SetFilterPolicy(filter)
	opts.SetBlockBasedTableFactory(bbto)
	db, err := gorocksdb.OpenDb(opts, "/path/to/db")

If you're using a custom comparator in your code, be aware you may have to
make your own filter policy object.

This documentation is not a complete discussion of RocksDB. Please read the
RocksDB documentation <http://rocksdb.org/> for information on its
operation. You'll find lots of goodies there.
*/
package rdb
<|endoftext|>


<commit_before>/*
Package spdy provides a full-featured SPDY library for the Go language (still under very active development).

So far, servers and clients are ready, but the client API is not completely stable.

Note that this implementation currently supports SPDY drafts 2 and 3.

Servers
-------

Adding SPDY support to an existing Go server doesn't take much work.

Modifying a simple example server like the following:

		package main

		import (
			"net/http"
		)

		func ServeHTTP(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("Hello, HTTP!"))
		}

		func main() {

			// Register handler.
			http.HandleFunc("/", ServeHTTP)

			err := http.ListenAndServeTLS("localhost:443", "cert.pem", "key.pem", nil)
			if err != nil {
				// handle error.
			}
		}

Simply requires the following changes:

		package main

		import (
			"github.com/SlyMarbo/spdy" // Import SPDY.
			"net/http"
		)

		// This handler will now serve HTTP, HTTPS, and SPDY requests.
		func ServeHTTP(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("Hello, HTTP!"))
		}

		func main() {

			http.HandleFunc("/", ServeHTTP)

			// Use spdy's ListenAndServe.
			err := spdy.ListenAndServeTLS("localhost:443", "cert.pem", "key.pem", nil)
			if err != nil {
				// handle error.
			}
		}

SPDY now supports reuse of HTTP handlers, as demonstrated above. Although this allows you to use just one set of
handlers, it means there is no way to use the SPDY-specific capabilities provided by `spdy.ResponseWriter`, such as
server pushes, or to know which protocol is being used.

Making full use of the SPDY protocol simple requires adding an extra handler:

		package main

		import (
			"github.com/SlyMarbo/spdy"
			"net/http"
		)

		// This now only serves HTTP/HTTPS requests.
		func ServeHTTP(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("Hello, HTTP!"))
		}

		// Add a SPDY handler.
		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {
			w.Write([]byte("Hello, SPDY!"))
		}

		func main() {

			// Register handlers.
			http.HandleFunc("/", ServeHTTP)
			spdy.HandleFunc("/", ServeSPDY)

			err := spdy.ListenAndServeTLS("localhost:443", "cert.pem", "key.pem", nil)
			if err != nil {
				// handle error.
			}
		}

A very simple file server for both SPDY and HTTPS:

		package main

		import (
			"github.com/SlyMarbo/spdy"
			"net/http"
		)

		func ServeHTTP(w http.ResponseWriter, r *http.Request) {
			http.ServeFile(w, r, "." + r.RequestURI)
		}

		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {
			spdy.ServeFile(w, r, "." + r.RequestURI)
		}

		func main() {

			// Register handlers.
			http.HandleFunc("/", ServeHTTP)
			spdy.HandleFunc("/", ServeSPDY)

			err := spdy.ListenAndServeTLS("localhost:443", "cert.pem", "key.pem", nil)
			if err != nil {
				// handle error.
			}
		}

The following examples use features specific to SPDY, so just the SPDY handler is shown.

Use SPDY's pinging features to test the connection:

		package main

		import (
			"github.com/SlyMarbo/spdy"
			"time"
		)

		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {
			// Ping returns a channel which will send a bool.
			ping := w.Ping()

			select {
			case success := <- ping:
				if success {
					// Connection is fine.
				} else {
					// Something went wrong.
				}

			case <-time.After(timeout):
				// Ping took too long.

			}

			// ...
		}

Sending a server push:

		package main

		import "github.com/SlyMarbo/spdy"

		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {

			// Push a whole file automatically.
			spdy.PushFile(w, r, otherFile)

			// or

			// Push returns a PushWriter (similar to a ResponseWriter) and an error.
			push, err := w.Push()
			if err != nil {
				// Handle the error.
			}
			push.Write([]byte("Some stuff."))   // Push data manually.

			// ...
		}

Sending SPDY settings:

		package main

		import "github.com/SlyMarbo/spdy"

		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {

			setting := new(spdy.Setting)
			setting.Flags = spdy.FLAG_SETTINGS_PERSIST_VALUE
			setting.ID = spdy.SETTINGS_MAX_CONCURRENT_STREAMS
			setting.Value = 500

			w.WriteSettings(setting)

			// ...
		}

Clients
-------

The basic client API seems to work well in general, but gets a redirect loop when requesting https://twitter.com/, so
I'm not happy with it. Since I can't see Twitter's servers' SPDY logs, I don't know what's wrong yet, but I'm working
hard at it.

Here's a simple example that will fetch the requested page over HTTP, HTTPS, or SPDY, as necessary.

		package main

		import (
			"fmt"
			"github.com/SlyMarbo/spdy"
			"io/ioutil"
		)

		func main() {
			res, err := spdy.Get("https://example.com/")
			if err != nil {
				// handle the error.
			}

			bytes, err := ioutil.ReadAll(res.Body)
			if err != nil {
				// handle the error.
			}
			res.Body.Close()

			fmt.Printf("Received: %s\n", bytes)
		}

*/
package spdy<commit_msg>Doc update<commit_after>/*
Package spdy provides a full-featured SPDY library for the Go language (still under very active development).

So far, servers and clients are ready, but the client API is not completely stable.

Note that this implementation currently supports SPDY drafts 2 and 3.

		Servers

Adding SPDY support to an existing Go server doesn't take much work.

Modifying a simple example server like the following:

		package main

		import (
			"net/http"
		)

		func ServeHTTP(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("Hello, HTTP!"))
		}

		func main() {

			// Register handler.
			http.HandleFunc("/", ServeHTTP)

			err := http.ListenAndServeTLS("localhost:443", "cert.pem", "key.pem", nil)
			if err != nil {
				// handle error.
			}
		}

Simply requires the following changes:

		package main

		import (
			"github.com/SlyMarbo/spdy" // Import SPDY.
			"net/http"
		)

		// This handler will now serve HTTP, HTTPS, and SPDY requests.
		func ServeHTTP(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("Hello, HTTP!"))
		}

		func main() {

			http.HandleFunc("/", ServeHTTP)

			// Use spdy's ListenAndServe.
			err := spdy.ListenAndServeTLS("localhost:443", "cert.pem", "key.pem", nil)
			if err != nil {
				// handle error.
			}
		}

SPDY now supports reuse of HTTP handlers, as demonstrated above. Although this allows you to use just one set of
handlers, it means there is no way to use the SPDY-specific capabilities provided by `spdy.ResponseWriter`, such as
server pushes, or to know which protocol is being used.

Making full use of the SPDY protocol simple requires adding an extra handler:

		package main

		import (
			"github.com/SlyMarbo/spdy"
			"net/http"
		)

		// This now only serves HTTP/HTTPS requests.
		func ServeHTTP(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("Hello, HTTP!"))
		}

		// Add a SPDY handler.
		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {
			w.Write([]byte("Hello, SPDY!"))
		}

		func main() {

			// Register handlers.
			http.HandleFunc("/", ServeHTTP)
			spdy.HandleFunc("/", ServeSPDY)

			err := spdy.ListenAndServeTLS("localhost:443", "cert.pem", "key.pem", nil)
			if err != nil {
				// handle error.
			}
		}

A very simple file server for both SPDY and HTTPS:

		package main

		import (
			"github.com/SlyMarbo/spdy"
			"net/http"
		)

		func ServeHTTP(w http.ResponseWriter, r *http.Request) {
			http.ServeFile(w, r, "." + r.RequestURI)
		}

		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {
			spdy.ServeFile(w, r, "." + r.RequestURI)
		}

		func main() {

			// Register handlers.
			http.HandleFunc("/", ServeHTTP)
			spdy.HandleFunc("/", ServeSPDY)

			err := spdy.ListenAndServeTLS("localhost:443", "cert.pem", "key.pem", nil)
			if err != nil {
				// handle error.
			}
		}

The following examples use features specific to SPDY, so just the SPDY handler is shown.

Use SPDY's pinging features to test the connection:

		package main

		import (
			"github.com/SlyMarbo/spdy"
			"time"
		)

		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {
			// Ping returns a channel which will send a bool.
			ping := w.Ping()

			select {
			case success := <- ping:
				if success {
					// Connection is fine.
				} else {
					// Something went wrong.
				}

			case <-time.After(timeout):
				// Ping took too long.

			}

			// ...
		}

Sending a server push:

		package main

		import "github.com/SlyMarbo/spdy"

		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {

			// Push a whole file automatically.
			spdy.PushFile(w, r, otherFile)

			// or

			// Push returns a PushWriter (similar to a ResponseWriter) and an error.
			push, err := w.Push()
			if err != nil {
				// Handle the error.
			}
			push.Write([]byte("Some stuff."))   // Push data manually.

			// ...
		}

Sending SPDY settings:

		package main

		import "github.com/SlyMarbo/spdy"

		func ServeSPDY(w spdy.ResponseWriter, r *spdy.Request) {

			setting := new(spdy.Setting)
			setting.Flags = spdy.FLAG_SETTINGS_PERSIST_VALUE
			setting.ID = spdy.SETTINGS_MAX_CONCURRENT_STREAMS
			setting.Value = 500

			w.WriteSettings(setting)

			// ...
		}

		Clients

The basic client API seems to work well in general, but gets a redirect loop when requesting https://twitter.com/, so
I'm not happy with it. Since I can't see Twitter's servers' SPDY logs, I don't know what's wrong yet, but I'm working
hard at it.

Here's a simple example that will fetch the requested page over HTTP, HTTPS, or SPDY, as necessary.

		package main

		import (
			"fmt"
			"github.com/SlyMarbo/spdy"
			"io/ioutil"
		)

		func main() {
			res, err := spdy.Get("https://example.com/")
			if err != nil {
				// handle the error.
			}

			bytes, err := ioutil.ReadAll(res.Body)
			if err != nil {
				// handle the error.
			}
			res.Body.Close()

			fmt.Printf("Received: %s\n", bytes)
		}

*/
package spdy<|endoftext|>


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

/*
Package dec is a Go wrapper around the decNumber library (arbitrary precision decimal arithmetic).

For more information about the decNumber library, and detailed documentation,
see http://speleotrove.com/decimal/dec.html

It implements the General Decimal Arithmetic Specification in ANSI C. This specification defines a
decimal arithmetic which meets the requirements of commercial, financial, and human-oriented
applications. It also matches the decimal arithmetic in the IEEE 754 Standard for Floating Point
Arithmetic.

The library fully implements the specification, and hence supports integer, fixed-point, and
floating- point decimal numbers directly, including infinite, NaN (Not a Number), and subnormal
values. Both arbitrary-precision and fixed-size representations are supported.

Go implementation details:

Contexts are created with a immutable precision (i.e. number of digits). If one needs to change
precision on the fly, discard the existing context and create a new one with the required precision.

From a programming standpoint, any initialized Number is a valid operand in arithmetic operations,
regardless of the settings or existence of its creator Context (not to be confused with having a
valid value in a given arithmetic operation).

Arithmetic functions are Number methods. The value of the receiver of the method will be set to the
result of the operation. For example:

	n.Add(x, y, context) // n = x + y

Arithmetic methods always return the receiver in order to allow chain calling:

	n.Add(x, y, context).Multiply(n, z, context) // n = (x + y) * z

Using the same Number as operand and result, like in n.Multiply(n, n, ctx), is legal and will not
produce unexpected results.

The package provides facilities for managing free-lists of Numbers in order to relieve pressure on
the garbage collector in computation intensive applications. NumberPool is in fact a simple wrapper
around a *Context and a sync.Pool, or the lighter dec.Pool, which will automatically cast the return
value of Get() to the desired type.

For example:

	ctx := dec.NewContext(dec.InitDecimal128, 0)
	// idomatic code for NumberPool creation
	pool := &dec.NumberPool{
		&sync.Pool{
			New: func() interface{} { return dec.NewNumber(ctx.Digits()) },
		},
		ctx,                             // same context as the one used in New()
	}
	number := pool.Get()                 // with no need to type cast to *Number
	defer pool.Put(number)               // idiomatic code for short lived numbers
	number.FromString("1243", pool.Context)

Note the use of pool.Context on the last statement.

The provided dec.Pool implementation is not thread safe and is only provided as a lightweight
alternative to sync.Pool.

If an application needs to change its arithmetic precision on the fly, any NumberPool built on top
of the affected Context's will need to be discarded and recreated along with the Context. This will
not affect existing numbers that can still be used as valid operands in arithmetic functions.

*/
package dec
<commit_msg>Updated docs<commit_after>// Copyright 2014 Denis Bernard. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package dec is a Go wrapper around the decNumber library (arbitrary precision decimal arithmetic).

For more information about the decNumber library, and detailed documentation,
see http://speleotrove.com/decimal/dec.html

It implements the General Decimal Arithmetic Specification in ANSI C. This specification defines a
decimal arithmetic which meets the requirements of commercial, financial, and human-oriented
applications. It also matches the decimal arithmetic in the IEEE 754 Standard for Floating Point
Arithmetic.

The library fully implements the specification, and hence supports integer, fixed-point, and
floating-point decimal numbers directly, including infinite, NaN (Not a Number), and subnormal
values. Both arbitrary-precision and fixed-size representations are supported.

General usage notes:

The Number format is optimized for efficient processing of relatively short numbers; It does,
however, support arbitrary precision (up to 999,999,999 digits) and arbitrary exponent range (Emax
in the range 0 through 999,999,999 and Emin in the range -999,999,999 through 0).  Mathematical
functions (for example Exp()) as identified below are restricted more tightly: digits, emax, and
-emin in the context must be <= MaxMath (999999), and their operand(s) must be within these bounds.

Logical functions are further restricted; their operands must be finite, positive, have an exponent
of zero, and all digits must be either 0 or 1.  The result will only contain digits which are 0 or 1
(and will have exponent=0 and a sign of 0).

Operands to operator functions are never modified unless they are also specified to be the result
number (which is always permitted).  Other than that case, operands must not overlap.

Go implementation details:

The decimal32, decimal64 and decimal128 types are merged into Single, Double and Quad, respectively.

Contexts are created with a immutable precision (i.e. number of digits). If one needs to change
precision on the fly, discard the existing context and create a new one with the required precision.

From a programming standpoint, any initialized Number is a valid operand in arithmetic operations,
regardless of the settings or existence of its creator Context (not to be confused with having a
valid value in a given arithmetic operation).

Arithmetic functions are Number methods. The value of the receiver of the method will be set to the
result of the operation. For example:

	n.Add(x, y, context) // n = x + y

Arithmetic methods always return the receiver in order to allow chain calling:

	n.Add(x, y, context).Multiply(n, z, context) // n = (x + y) * z

Using the same Number as operand and result, like in n.Multiply(n, n, ctx), is legal and will not
produce unexpected results.

Error handling: although most arithmetic functions can cause errors, the standard Go error handling
is not used in its idiomatic form. That is, arithmetic functions do not return errors. Instead, the
type of the error is ORed into the status flags in the current context (Context type). It is the
responsibility of the caller to clear the status flags as required. The result of any routine which
returns a number will always be a valid number (which may be a special value, such as an Infinity or
NaN). This permits the use of much fewer error checks; a single check for a whole computation is
often enough.

To check for errors, get the Context's status with the Status() function (see the Status
type), or use the Context's ErrorStatus() function.

The package provides facilities for managing free-lists of Numbers in order to relieve pressure on
the garbage collector in computation intensive applications. NumberPool is in fact a simple wrapper
around a *Context and a sync.Pool, or the lighter dec.Pool, which will automatically cast the return
value of Get() to the desired type.

For example:

	ctx := dec.NewContext(dec.InitDecimal128, 0)
	// idomatic code for NumberPool creation
	pool := &dec.NumberPool{
		&sync.Pool{
			New: func() interface{} { return dec.NewNumber(ctx.Digits()) },
		},
		ctx,                             // same context as the one used in New()
	}
	number := pool.Get()                 // with no need to type cast to *Number
	defer pool.Put(number)               // idiomatic code for short lived numbers
	number.FromString("1243", pool.Context)

Note the use of pool.Context on the last statement.

If a particular implementation needs always-initialized numbers (like any new Go variable being initialize
to the 0 value of its type), the pool's New function can be set for example to:

	func() interface{} { return dec.NewNumber(ctx.Digits()).Zero() }

The provided dec.Pool implementation is not thread safe and is only provided as a lightweight
alternative to sync.Pool.

If an application needs to change its arithmetic precision on the fly, any NumberPool built on top
of the affected Context's will need to be discarded and recreated along with the Context. This will
not affect existing numbers that can still be used as valid operands in arithmetic functions.

*/
package dec
<|endoftext|>


<commit_before>// Package cdl provides a configuration definition language for Go
//
// There are several ways to import configuration files into Go, from
// unmarshalling your own JSON using `encoding/json` to projects such as
// Viper (http://spf13.com/project/viper) which will read the configuration
// in JSON, YAML, TOML or from etcd, the command line, or possibly other
// sources. All of these have in common that in the end they produce
// something that looks in Go like
//
//     map[string]interface{}
//
// However, these have the issue that they don't validate the configuration.
// If the supplied configuration omits mandatory keys, or puts in extra
// ones, or does both by misspelling one key, or puts the right bit of
// configuration at the wrong level, or any other error is made that
// doesn't actually prevent the JSON, YAML etc. parsing, then it's left
// for you to detect that manually in your program.
//
// cdl makes this all much easier. Simply supply a cdl template, compile
// it (once) using
//     ct := cdl.Compile(...)
// then validate using
//     err := ct.Validate(object, nil)
//
// If the validation fails, you will get an `error` return with a context
// that will allow a user to discover the error in his file.
//
// So what was that `nil` parameter to `cdt.Validate` about? cdl also
// permits you to pass a configurator in, so that you can store the values
// retrieved in appropriate places.
//
// Templates
//
// cdl templates are themselves a
//     map[string]interface{}
//
// but are flat (i.e. only one level deep). The key represents a point in
// in the hierarchy to parse, and the value specifies what may appear at
// that point. The value is normally a `string`, but may be a pointer
// to a validation function you supply.
//
// For example:
//     template := cdl.Template{
// 		"/":     "{}apple peach? lemon",
// 		"apple": "float64",
// 		"peach": isOneOrTwo,
// 	}
//
// Here:
//  * The root level is specified to be a map ('`{}`'), which may consist of the elements
//    `apple`, `peach` and `lemon`.
//
//  * There must be an `apple` element and `lemon` element, but the `peach` element
//    is optional.
//
//  * The `apple` element must be a `float64`
//
//  * In order to validate the `peach` element, your own validator function (`isOneOrTwo`)
//     is called. If this returns a `cdl.CdlError`, that error will be passed to the user
//     (as an `error`). If it returns `nil`, then validation will continue.
//
//  * There is no validation at all on `peach`
//
// Let's take a more complicated example:
// 	template := cdl.Template{
// 		"/":          "{}apple peach? pear* plum+ raspberry{1,3} strawberry! kiwi{1,4}? guava!{1,2} orange?{2,31}",
// 		"apple":      "float64",
// 		"peach":      isOneOrTwo,
// 		"strawberry": "[nectarine]{1,3}",
// 		"nectarine":  "string",
// 		"raspberry":  "string"
// 	}
//
// Here we have allowed in the root level:
//  * `strawberry`: The `!` indicates it is mandatory; this is the default, so the `!`
//     is unnecessary. Each `strawberry` must be an array of `nectarine` with between
//      1 and 3 components, and each `nectarine` must be a `string`.
//
//  * `rasbperry`: This is a shorthand for writing the same thing as above, i.e. an
//     array of between 1 and 3 `raspberry`, each of which must be a string.
//
//  * `pear`: An array of zero or more items. Note the empty array must be there (if
//     the array itself is optional, write `pear?*`).
//
//  * `plum`: An array of one or more entries.
//
//  * `kiwi`: An optionally present array of between 1 and 4 entries
//
//  * `guava`: A mandatory array of between 1 and 2 entries
//
// Template syntax in detail
//
// 1. Each key must either be `/` (for the root key) or consist of word characters
// (i.e. matching `\w+` in regexp terms)
//
// 2. Each key must have a value, which may be either a validator function, or
// a validation instruction in the form of a `string`
//
// 3. A validator function is a function with the signature
//    func(obj interface{}) (err *CdlError)`
//
// 4. Each validation instruction may be either
//   * The Go name of a type (not a slice), e.g. `bool`, `string` etc. (in quotes as
//     it's a `string`)
//   * The word `number` which indicates any numerical type (not `bool`)
//   * The word `integer` which indicates any numerical type where the value is an
//     integer (useful for parsing JSON with `json/encoding` which presents these as
//     `float64`)
//   * An array specifier, having a form beginning `[]`
//   * A map specifier, having a form beginning `{}`
//
// 5. An array specifier has the form `[]key` optionally followed by a range specifier
//   * The key (`key` above) consists of word characters.
//   * The key need not be specified within the template (if it isn't, no validation
//     will be done on it).
//
// 6. A range specifier takes the form
//   * `{n,m}` (meaning between `n` and `m`) or
//   * `{n,}` (meaning at least `n`).
//
// 7. A map specifier has the form `{}` followed by zero or more space-separated
//    map elements
//
// 8. A map element consists of a key (`key`) followed by zero or more modifiers
//   * The key consists of word characters.
//   * The key need not be specified within the template (if it isn't, no validation
//     will be done on it).
//
// 9. Permitted modifiers are:
//   * `?` means the key is optional
//   * `!` means the key is mandatory (the default)
//   * `*` means the key is an array of 0 or more elements
//   * `+` means the key is an array of 1 or more elements
//   * A range specifier (see above), i.e.
//     * `{n,m}` (meaning between `n` and `m`) or
//     * `{n,}` (meaning at least `n`)
//
// Validator Functions
//
// Where the validator is passed, it is a function with signature:
//     func (o interface{}) *cdl.CdlError
//
// Here's an example showing how it can return an error and send supplementary data back to the user.
// Note that cdl itself will add the appropriate context.
//
//     func isOneOrTwo(o interface{}) *cdl.CdlError {
//     	if v, ok := o.(float64); !ok {
//     		return cdl.NewError(cdl.ErrBadValue).SetSupplementary("is not a float64")
//     	} else {
//     		if v != 1 && v != 2 {
//     			return cdl.NewError(cdl.ErrBadValue).SetSupplementary("is not 1 or 2")
//     		}
//     	}
//     	return nil
//     }
//
// Configurators
//
// A cdl configurator may optionally be passed to the `Validate` function. The
// configurator allows you to consume the configuration in your program now
// you know that is validated.
//
// The configurator consists of a map of keys to the `ConfiguratorFunc` type (or a
// function with a similar signature), which looks like this:
//
//     type ConfiguratorFunc func(obj interface{}, path Path) (err *CdlError)
//
// This function is guaranteed to be called for each item in the tree
// (if it's key is present in the configurator) after it and all of
// its children have been validated. It may return an error (just like
// a validator function).
//
// The object passed will be the validated object from the configuration
// tree. It is guaranteed to be of the correct type, which means the type
// you asked for save for the following exceptions:
//
// 1. If you asked for the pseudo-type `number`, you will always be given a `float64`.
//
// 2. If you asked for the pseudo-type `integer`, you will always be given an `int`.
//
//  As a trivial example:
//
//     var i int
//     err := ct.Validate(object, cdl.Configurator{
//         "i": func(o interface{}, p cdl.Path) *cdl.CdlError {
// 		        i = o.(int)
// 		        return nil
// 	        },
//     })
//
// Here the parameter named `"i"` in the template will be stored in
// variable `i`.
package cdl
<commit_msg>Formatting fix in documentation<commit_after>// Package cdl provides a configuration definition language for Go
//
// There are several ways to import configuration files into Go, from
// unmarshalling your own JSON using `encoding/json` to projects such as
// Viper (http://spf13.com/project/viper) which will read the configuration
// in JSON, YAML, TOML or from etcd, the command line, or possibly other
// sources. All of these have in common that in the end they produce
// something that looks in Go like
//
//     map[string]interface{}
//
// However, these have the issue that they don't validate the configuration.
// If the supplied configuration omits mandatory keys, or puts in extra
// ones, or does both by misspelling one key, or puts the right bit of
// configuration at the wrong level, or any other error is made that
// doesn't actually prevent the JSON, YAML etc. parsing, then it's left
// for you to detect that manually in your program.
//
// cdl makes this all much easier. Simply supply a cdl template, compile
// it (once) using
//     ct := cdl.Compile(...)
// then validate using
//     err := ct.Validate(object, nil)
//
// If the validation fails, you will get an `error` return with a context
// that will allow a user to discover the error in his file.
//
// So what was that `nil` parameter to `cdt.Validate` about? cdl also
// permits you to pass a configurator in, so that you can store the values
// retrieved in appropriate places.
//
// Templates
//
// cdl templates are themselves a
//     map[string]interface{}
//
// but are flat (i.e. only one level deep). The key represents a point in
// in the hierarchy to parse, and the value specifies what may appear at
// that point. The value is normally a `string`, but may be a pointer
// to a validation function you supply.
//
// For example:
//     template := cdl.Template{
// 		"/":     "{}apple peach? lemon",
// 		"apple": "float64",
// 		"peach": isOneOrTwo,
// 	}
//
// Here:
//  * The root level is specified to be a map ('`{}`'), which may consist of the elements
//    `apple`, `peach` and `lemon`.
//
//  * There must be an `apple` element and `lemon` element, but the `peach` element
//    is optional.
//
//  * The `apple` element must be a `float64`
//
//  * In order to validate the `peach` element, your own validator function (`isOneOrTwo`)
//     is called. If this returns a `cdl.CdlError`, that error will be passed to the user
//     (as an `error`). If it returns `nil`, then validation will continue.
//
//  * There is no validation at all on `peach`
//
// Let's take a more complicated example:
// 	template := cdl.Template{
// 		"/":          "{}apple peach? pear* plum+ raspberry{1,3} strawberry! kiwi{1,4}? guava!{1,2} orange?{2,31}",
// 		"apple":      "float64",
// 		"peach":      isOneOrTwo,
// 		"strawberry": "[nectarine]{1,3}",
// 		"nectarine":  "string",
// 		"raspberry":  "string"
// 	}
//
// Here we have allowed in the root level:
//  * `strawberry`: The `!` indicates it is mandatory; this is the default, so the `!`
//     is unnecessary. Each `strawberry` must be an array of `nectarine` with between
//      1 and 3 components, and each `nectarine` must be a `string`.
//
//  * `rasbperry`: This is a shorthand for writing the same thing as above, i.e. an
//     array of between 1 and 3 `raspberry`, each of which must be a string.
//
//  * `pear`: An array of zero or more items. Note the empty array must be there (if
//     the array itself is optional, write `pear?*`).
//
//  * `plum`: An array of one or more entries.
//
//  * `kiwi`: An optionally present array of between 1 and 4 entries
//
//  * `guava`: A mandatory array of between 1 and 2 entries
//
// Template syntax in detail
//
// 1. Each key must either be `/` (for the root key) or consist of word characters
// (i.e. matching `\w+` in regexp terms)
//
// 2. Each key must have a value, which may be either a validator function, or
// a validation instruction in the form of a `string`
//
// 3. A validator function is a function with the signature
//    func(obj interface{}) (err *CdlError)`
//
// 4. Each validation instruction may be either
//   * The Go name of a type (not a slice), e.g. `bool`, `string` etc. (in quotes as
//     it's a `string`)
//   * The word `number` which indicates any numerical type (not `bool`)
//   * The word `integer` which indicates any numerical type where the value is an
//     integer (useful for parsing JSON with `json/encoding` which presents these as
//     `float64`)
//   * An array specifier, having a form beginning `[]`
//   * A map specifier, having a form beginning `{}`
//
// 5. An array specifier has the form `[]key` optionally followed by a range specifier
//   * The key (`key` above) consists of word characters.
//   * The key need not be specified within the template (if it isn't, no validation
//     will be done on it).
//
// 6. A range specifier takes the form
//   * `{n,m}` (meaning between `n` and `m`) or
//   * `{n,}` (meaning at least `n`).
//
// 7. A map specifier has the form `{}` followed by zero or more space-separated
//    map elements
//
// 8. A map element consists of a key (`key`) followed by zero or more modifiers
//   * The key consists of word characters.
//   * The key need not be specified within the template (if it isn't, no validation
//     will be done on it).
//
// 9. Permitted modifiers are:
//   * `?` means the key is optional
//   * `!` means the key is mandatory (the default)
//   * `*` means the key is an array of 0 or more elements
//   * `+` means the key is an array of 1 or more elements
//   * A range specifier (see above), i.e.
//     * `{n,m}` (meaning between `n` and `m`) or
//     * `{n,}` (meaning at least `n`)
//
// Validator Functions
//
// Where the validator is passed, it is a function with signature:
//     func (o interface{}) *cdl.CdlError
//
// Here's an example showing how it can return an error and send supplementary data back to the user.
// Note that cdl itself will add the appropriate context.
//
//     func isOneOrTwo(o interface{}) *cdl.CdlError {
//     	if v, ok := o.(float64); !ok {
//     		return cdl.NewError(cdl.ErrBadValue).SetSupplementary("is not a float64")
//     	} else {
//     		if v != 1 && v != 2 {
//     			return cdl.NewError(cdl.ErrBadValue).SetSupplementary("is not 1 or 2")
//     		}
//     	}
//     	return nil
//     }
//
// Configurators
//
// A cdl configurator may optionally be passed to the `Validate` function. The
// configurator allows you to consume the configuration in your program now
// you know that is validated.
//
// The configurator consists of a map of keys to the `ConfiguratorFunc` type (or a
// function with a similar signature), which looks like this:
//
//     type ConfiguratorFunc func(obj interface{}, path Path) (err *CdlError)
//
// This function is guaranteed to be called for each item in the tree
// (if it's key is present in the configurator) after it and all of
// its children have been validated. It may return an error (just like
// a validator function).
//
// The object passed will be the validated object from the configuration
// tree. It is guaranteed to be of the correct type, which means the type
// you asked for save for the following exceptions:
//
// 1. If you asked for the pseudo-type `number`, you will always be given a `float64`.
//
// 2. If you asked for the pseudo-type `integer`, you will always be given an `int`.
//
// As a trivial example:
//
//     var i int
//     err := ct.Validate(object, cdl.Configurator{
//         "i": func(o interface{}, p cdl.Path) *cdl.CdlError {
// 		        i = o.(int)
// 		        return nil
// 	        },
//     })
//
// Here the parameter named `"i"` in the template will be stored in
// variable `i`.
package cdl
<|endoftext|>


<commit_before>/*

WSDL to Go

Generates Go code from a WSDL file. This project is originally intended to generate Go clients for WS-* services.

Features
  * Supports only Document/Literal wrapped services, which are [WS-I](http://ws-i.org/) compliant
  * Attempts to generate idiomatic Go code as much as possible
  * Generates Go code in parallel: types, operations and soap proxy
  * Supports:
	  * WSDL 1.1
	  * XML Schema 1.0
	  * SOAP 1.1
  * Resolves external XML Schemas recursively, up to 5 recursions.
  * Supports providing WSDL HTTP URL as well as a local WSDL file

Not supported
  * Setting SOAP headers
  * SOAP 1.2 and HTTP port bindings
  * WS-Security

Usage

  gowsdl [OPTIONS]

  Application Options:
	  -v, --version     Shows gowsdl version
	  -p, --package=    Package under which code will be generated (myservice)
	  -o, --output=     File where the generated code will be saved (myservice.go)
	  -i, --ignore-tls  Ignores invalid TLS certificates. It is not recomended for production. Use at your own risk
										(false)

  Help Options:
	  -h, --help        Show this help message

TODO

  * Add support for filters to allow the user to change the generated code
  * If WSDL file is local, resolve external XML schemas locally too instead of failing due to not having a URL to download them from.
  * Resolve XSD element references
  * Support for generating namespaces
  * Make code generation agnostic so generating code to other programming languages is feasible through plugins

License

  Copyright 2014 Cloudescape

  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
<commit_msg>Formatting<commit_after>/*
WSDL to Go
Generates Go code from a WSDL file. This project is originally intended to generate Go clients for WS-* services.

Features

  * Supports only Document/Literal wrapped services, which are [WS-I](http://ws-i.org/) compliant
  * Attempts to generate idiomatic Go code as much as possible
  * Generates Go code in parallel: types, operations and soap proxy
  * Supports:
	  * WSDL 1.1
	  * XML Schema 1.0
	  * SOAP 1.1
  * Resolves external XML Schemas recursively, up to 5 recursions.
  * Supports providing WSDL HTTP URL as well as a local WSDL file

Not supported

  * Setting SOAP headers
  * SOAP 1.2 and HTTP port bindings
  * WS-Security

Usage

  gowsdl [OPTIONS]

  Application Options:
	  -v, --version     Shows gowsdl version
	  -p, --package=    Package under which code will be generated (myservice)
	  -o, --output=     File where the generated code will be saved (myservice.go)
	  -i, --ignore-tls  Ignores invalid TLS certificates. It is not recomended for production. Use at your own risk
										(false)

  Help Options:
	  -h, --help        Show this help message

TODO

  * Add support for filters to allow the user to change the generated code
  * If WSDL file is local, resolve external XML schemas locally too instead of failing due to not having a URL to download them from.
  * Resolve XSD element references
  * Support for generating namespaces
  * Make code generation agnostic so generating code to other programming languages is feasible through plugins

License

  Copyright 2014 Cloudescape

  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
<|endoftext|>


<commit_before>/*
Package capnp is a Cap'n Proto library for Go.

see https://capnproto.org/

capnpc-go provides the compiler backend for capnp
after installing to $PATH capnp files can be compiled with

	capnp compile -ogo *.capnp

capnpc-go requires two annotations for all types. This is the package and
import found in go.capnp. Package is needed to know what package to place at
the head of the generated file and what go name to use when referring to the
type from another package. Import should be the fully qualified import path
and is used to generate import statement from other packages and to detect
when two types are in the same package. Typically these are added as file
annotations. For example:

	using Go = import "zombiezen.com/go/capnproto/go.capnp";
	$Go.package("main");
	$Go.import("zombiezen.com/go/capnproto/example");

In capnproto, the unit of communication is a message. A message
consists of one or more of segments to allow easier allocation, but
ideally and typically you just make one segment per message.

Logically, a message organized in a tree of objects, with the root
always being a struct (as opposed to a list or primitive).

Here is an example of writing a new message. We use the demo schema
aircraft.capnp from the aircraftlib directory. You may wish to read
the schema before reading this example.

<< Example moved to its own file: See the file, write_test.go >>

In summary, when you make a new message, you should first make new segment,
and then create the root struct in that segment. Then add your non-child
(contained) objects. This is because, as the spec says:

   The first word of the first segment of the message
   is always a pointer pointing to the message's root
   struct.

All objects are values with pointer semantics that point into the data
in a message or segment. Messages can be read/written from a stream
uncompressed or using the capnproto compression.

In this library a *Segment is taken to refer to both a specific segment as
well as the containing message. This is to reduce the number of types generic
code needs to deal with and allows objects to be created in the same segment
as their outer object (thus reducing the number of far pointers).

Most getters/setters in the library don't return an error. Instead a get that
fails due to an invalid pointer, out of bounds, etc will return the default
value. A invalid set will be noop'ed. If you really need to know whether a set
succeeds then errors are provided by the lower level Object methods.

Since go doesn't have any templating, lists are created for the basic types
and one level of named types. The list of basic types (e.g. List(UInt8),
List(Text), etc) are all provided in this library. Lists of user named types
are created with the user types (e.g. user struct Foo will create a Foo_List
type). capnp schemas that use deeper lists (e.g. List(List(UInt8))) will use
PointerList and the user will have to use the Object.ToList* functions to cast
to the correct type.

For adding documentation comments to the generated code, there's the doc
annotation. This annotation adds the comment to a struct, enum or field so
that godoc will pick it up. For Example:

	struct Zdate $Go.doc("Zdate represents an instance in time") {
	  year  @0   :Int16;
	  month @1   :UInt8;
	  day   @2   :UInt8 ;
	}

Structs

capnpc-go will generate the following for structs:

	// Foo is a value with pointer semantics referencing the data in a
	// segment. Member functions are provided to get/set members in the
	// struct. Getters/setters of an outer struct will use values of type
	// Foo to set/get pointers.
	type Foo capnp.Struct

	// NewFoo creates a new orphaned Foo struct. This can then be added to
	// a message by using a Set function which takes a Foo argument.
	func NewFoo(s *capnp.Segment) Foo

	// NewRootFoo creates a new root of type Foo in the next unused space in the
	// provided segment. This is distinct from NewFoo as this always
	// creates a root tag. Typically the provided segment should be empty.
	// Remember that a message is a tree of objects with a single root, and
	// you usually have to create the root before any other object in a
	// segment. The only exception would be for a multi-segment message.
	func NewRootFoo(s *capnp.Segment) Foo

	// ReadRootFoo reads the root tag at the beginning of the provided
	// segment and returns it as a Foo struct.
	func ReadRootFoo(s *capnp.Segment) Foo

	// Foo_List is a value with pointer semantics. It is created for all
	// structs, and is used for List(Foo) in the capnp file.
	type Foo_List capnp.List

	// NewFoo_List creates a new orphaned List(Foo). This can then be added
	// to a message by using a Set function which takes a Foo_List. sz
	// specifies the list size. Due to the list using memory directly in
	// the outgoing buffer (i.e. arena style memory management), the size
	// can not be changed after creation.
	func NewFoo_List(s *capnp.Segment, sz int) Foo_List

	// Len returns the list length. For composite lists this is the number
	// of list elements.
	func (s Foo_List) Len() int

	// At returns a pointer to the i'th element. If i is an invalid index,
	// this will return a null Foo (all getters will return default
	// values, setters will fail). For a composite list the returned value
	// will be a list member. Setting another value to point to list
	// members forces a copy of the data. For pointer lists, the pointer
	// value will be auto-derefenced.
	func (s Foo_List) At(i int) Foo

	// Foo_Promise is a promise for a Foo.  Methods are provided to get
	// promises of struct and interface fields.
	type Foo_Promise capnp.Pipeline

	// Get waits until the promise is resolved and returns the result.
	func (p Foo_Promise) Get() (Foo, error)

Groups

For each group a typedef is created with a different method set for just the
groups fields:

	struct Foo {
		group :Group {
			field @0 :Bool;
		}
	}

	type Foo capnp.Struct
	type Foo_group Foo

	func (s Foo) Group() Foo_group
	func (s Foo_group) Field() bool

That way the following may be used to access a field in a group:

	var f Foo
	value := f.Group().Field()

Note that Group accessors just cast the type and so have no overhead

	func (s Foo) Group() Foo_group {return Foo_group(s)}

Unions

Named unions are treated as a group with an inner unnamed union. Unnamed
unions generate an enum Type_Which and a corresponding Which() function:

	struct Foo {
		union {
			a @0 :Bool;
			b @1 :Bool;
		}
	}

	type Foo_Which uint16

	const (
		Foo_Which_a Foo_Which = 0
		Foo_Which_b Foo_Which = 1
	)

	func (s Foo) A() bool
	func (s Foo) B() bool
	func (s Foo) SetA(v bool)
	func (s Foo) SetB(v bool)
	func (s Foo) Which() Foo_Which

Which() should be checked before using the getters, and the default case must
always be handled.

Setters for single values will set the union discriminator as well as set the
value.

For voids in unions, there is a void setter that just sets the discriminator.
For example:

	struct Foo {
		union {
			a @0 :Void;
			b @1 :Void;
		}
	}

	f.SetA() // Set that we are using A
	f.SetB() // Set that we are using B

For groups in unions, there is a group setter that just sets the
discriminator. This must be called before the group getter can be used to set
values. For example:

	struct Foo {
		union {
			a :group {
				v :Bool
			}
			b :group {
				v :Bool
			}
		}
	}

	f.SetA()         // Set that we are using group A
	f.A().SetV(true) // then we can use the group A getter to set the inner values

Enums

capnpc-go generates enum values as constants. For example in the capnp file:

	enum ElementSize {
	  empty @0;
	  bit @1;
	  byte @2;
	  twoBytes @3;
	  fourBytes @4;
	  eightBytes @5;
	  pointer @6;
	  inlineComposite @7;
	}

In the generated capnp.go file:

	type ElementSize uint16

	const (
		ElementSize_empty           ElementSize = 0
		ElementSize_bit             ElementSize = 1
		ElementSize_byte            ElementSize = 2
		ElementSize_twoBytes        ElementSize = 3
		ElementSize_fourBytes       ElementSize = 4
		ElementSize_eightBytes      ElementSize = 5
		ElementSize_pointer         ElementSize = 6
		ElementSize_inlineComposite ElementSize = 7
	)

In addition an enum.String() function is generated that will convert the constants to a string
for debugging or logging purposes. By default, the enum name is used as the tag value,
but the tags can be customized with a $Go.tag or $Go.notag annotation.

For example:

	enum ElementSize {
		empty @0           $Go.tag("void");
		bit @1             $Go.tag("1 bit");
		byte @2            $Go.tag("8 bits");
		inlineComposite @7 $Go.notag;
	}

In the generated go file:

	func (c ElementSize) String() string {
		switch c {
		case ElementSize_empty:
			return "void"
		case ElementSize_bit:
			return "1 bit"
		case ElementSize_byte:
			return "8 bits"
		default:
			return ""
		}
	}

Interfaces

capnpc-go generates type-safe Client wrappers for interfaces. For parameter
lists and result lists, structs are generated as described above with the names
Interface_method_Params and Interface_method_Results, unless a single struct
type is used. For example, for this interface:

	interface Calculator {
		evaluate @0 (expression :Expression) -> (value :Value);
	}

capnpc-go generates the following Go code (along with the structs
Calculator_evaluate_Params and Calculator_evaluate_Results):

	// Calculator is a client to a Calculator interface.
	type Calculator struct { c capnp.Client }

	// NewCalculator creates a Calculator from a generic promise.
	func NewCalculator(c capnp.Client) Calculator

	// GenericClient returns the underlying generic client.
	func (c Calculator) GenericClient() capnp.Client

	// IsNull returns whether the underlying client is nil.
	func (c Calculator) IsNull() bool

	// Evaluate calls `evaluate` on the client.  params is called on a newly
	// allocated Calculator_evaluate_Params to fill in the parameters.
	func (c Calculator) Evaluate(
		ctx context.Context,
		params func(Calculator_evaluate_Params),
		opts ...capnp.CallOption) *Calculator_evaluate_Results_Promise

capnpc-go also generates code to implement the interface:

	// A Calculator_Server implements the Calculator interface.
	type Calculator_Server interface {
		Evaluate(Calculator_evaluate_Call) error
	}

	// Calculator_evaluate_Call holds the arguments for a Calculator.evaluate server call.
	type Calculator_evaluate_Call struct {
		Ctx     context.Context
		Options capnp.CallOptions
		Params  Calculator_evaluate_Params
		Results Calculator_evaluate_Results
	}

	// Calculator_ServerToClient is equivalent to calling:
	// NewCalculator(capnp.NewServer(Calculator_Methods(nil, s), s))
	// If s does not implement the Close method, then nil is used.
	func Calculator_ServerToClient(s Calculator_Server) Calculator

	// Calculator_Methods appends methods from Calculator that call to server and
	// returns the methods.  If methods is nil or the capacity of the underlying
	// slice is too small, a new slice is returned.
	func Calculator_Methods(methods []ServerMethod, server Calculator_Server) []ServerMethod

Since a single capability may want to implement many interfaces, you can
use multiple *_Methods functions to build a single slice to send to
NewServer.

An example of combining the client/server code to communicate with a locally
implemented Calculator:

	var srv Calculator_Server
	calc := Calculator_ServerToClient(srv)
	result := calc.Evaluate(ctx, func(params Calculator_evaluate_Params) {
		params.SetExpression(expr)
	})
	val := result.Value().Get()

A note about message ordering: when implementing a server method, you
are responsible for acknowledging delivery of a method call.  Failure to
do so can cause deadlocks.  See the Ack function for more details.
*/
package capnp // import "zombiezen.com/go/capnproto"
<commit_msg>capnp: fix docs about interface servers<commit_after>/*
Package capnp is a Cap'n Proto library for Go.

see https://capnproto.org/

capnpc-go provides the compiler backend for capnp
after installing to $PATH capnp files can be compiled with

	capnp compile -ogo *.capnp

capnpc-go requires two annotations for all types. This is the package and
import found in go.capnp. Package is needed to know what package to place at
the head of the generated file and what go name to use when referring to the
type from another package. Import should be the fully qualified import path
and is used to generate import statement from other packages and to detect
when two types are in the same package. Typically these are added as file
annotations. For example:

	using Go = import "zombiezen.com/go/capnproto/go.capnp";
	$Go.package("main");
	$Go.import("zombiezen.com/go/capnproto/example");

In capnproto, the unit of communication is a message. A message
consists of one or more of segments to allow easier allocation, but
ideally and typically you just make one segment per message.

Logically, a message organized in a tree of objects, with the root
always being a struct (as opposed to a list or primitive).

Here is an example of writing a new message. We use the demo schema
aircraft.capnp from the aircraftlib directory. You may wish to read
the schema before reading this example.

<< Example moved to its own file: See the file, write_test.go >>

In summary, when you make a new message, you should first make new segment,
and then create the root struct in that segment. Then add your non-child
(contained) objects. This is because, as the spec says:

   The first word of the first segment of the message
   is always a pointer pointing to the message's root
   struct.

All objects are values with pointer semantics that point into the data
in a message or segment. Messages can be read/written from a stream
uncompressed or using the capnproto compression.

In this library a *Segment is taken to refer to both a specific segment as
well as the containing message. This is to reduce the number of types generic
code needs to deal with and allows objects to be created in the same segment
as their outer object (thus reducing the number of far pointers).

Most getters/setters in the library don't return an error. Instead a get that
fails due to an invalid pointer, out of bounds, etc will return the default
value. A invalid set will be noop'ed. If you really need to know whether a set
succeeds then errors are provided by the lower level Object methods.

Since go doesn't have any templating, lists are created for the basic types
and one level of named types. The list of basic types (e.g. List(UInt8),
List(Text), etc) are all provided in this library. Lists of user named types
are created with the user types (e.g. user struct Foo will create a Foo_List
type). capnp schemas that use deeper lists (e.g. List(List(UInt8))) will use
PointerList and the user will have to use the Object.ToList* functions to cast
to the correct type.

For adding documentation comments to the generated code, there's the doc
annotation. This annotation adds the comment to a struct, enum or field so
that godoc will pick it up. For Example:

	struct Zdate $Go.doc("Zdate represents an instance in time") {
	  year  @0   :Int16;
	  month @1   :UInt8;
	  day   @2   :UInt8 ;
	}

Structs

capnpc-go will generate the following for structs:

	// Foo is a value with pointer semantics referencing the data in a
	// segment. Member functions are provided to get/set members in the
	// struct. Getters/setters of an outer struct will use values of type
	// Foo to set/get pointers.
	type Foo capnp.Struct

	// NewFoo creates a new orphaned Foo struct. This can then be added to
	// a message by using a Set function which takes a Foo argument.
	func NewFoo(s *capnp.Segment) Foo

	// NewRootFoo creates a new root of type Foo in the next unused space in the
	// provided segment. This is distinct from NewFoo as this always
	// creates a root tag. Typically the provided segment should be empty.
	// Remember that a message is a tree of objects with a single root, and
	// you usually have to create the root before any other object in a
	// segment. The only exception would be for a multi-segment message.
	func NewRootFoo(s *capnp.Segment) Foo

	// ReadRootFoo reads the root tag at the beginning of the provided
	// segment and returns it as a Foo struct.
	func ReadRootFoo(s *capnp.Segment) Foo

	// Foo_List is a value with pointer semantics. It is created for all
	// structs, and is used for List(Foo) in the capnp file.
	type Foo_List capnp.List

	// NewFoo_List creates a new orphaned List(Foo). This can then be added
	// to a message by using a Set function which takes a Foo_List. sz
	// specifies the list size. Due to the list using memory directly in
	// the outgoing buffer (i.e. arena style memory management), the size
	// can not be changed after creation.
	func NewFoo_List(s *capnp.Segment, sz int) Foo_List

	// Len returns the list length. For composite lists this is the number
	// of list elements.
	func (s Foo_List) Len() int

	// At returns a pointer to the i'th element. If i is an invalid index,
	// this will return a null Foo (all getters will return default
	// values, setters will fail). For a composite list the returned value
	// will be a list member. Setting another value to point to list
	// members forces a copy of the data. For pointer lists, the pointer
	// value will be auto-derefenced.
	func (s Foo_List) At(i int) Foo

	// Foo_Promise is a promise for a Foo.  Methods are provided to get
	// promises of struct and interface fields.
	type Foo_Promise capnp.Pipeline

	// Get waits until the promise is resolved and returns the result.
	func (p Foo_Promise) Get() (Foo, error)

Groups

For each group a typedef is created with a different method set for just the
groups fields:

	struct Foo {
		group :Group {
			field @0 :Bool;
		}
	}

	type Foo capnp.Struct
	type Foo_group Foo

	func (s Foo) Group() Foo_group
	func (s Foo_group) Field() bool

That way the following may be used to access a field in a group:

	var f Foo
	value := f.Group().Field()

Note that Group accessors just cast the type and so have no overhead

	func (s Foo) Group() Foo_group {return Foo_group(s)}

Unions

Named unions are treated as a group with an inner unnamed union. Unnamed
unions generate an enum Type_Which and a corresponding Which() function:

	struct Foo {
		union {
			a @0 :Bool;
			b @1 :Bool;
		}
	}

	type Foo_Which uint16

	const (
		Foo_Which_a Foo_Which = 0
		Foo_Which_b Foo_Which = 1
	)

	func (s Foo) A() bool
	func (s Foo) B() bool
	func (s Foo) SetA(v bool)
	func (s Foo) SetB(v bool)
	func (s Foo) Which() Foo_Which

Which() should be checked before using the getters, and the default case must
always be handled.

Setters for single values will set the union discriminator as well as set the
value.

For voids in unions, there is a void setter that just sets the discriminator.
For example:

	struct Foo {
		union {
			a @0 :Void;
			b @1 :Void;
		}
	}

	f.SetA() // Set that we are using A
	f.SetB() // Set that we are using B

For groups in unions, there is a group setter that just sets the
discriminator. This must be called before the group getter can be used to set
values. For example:

	struct Foo {
		union {
			a :group {
				v :Bool
			}
			b :group {
				v :Bool
			}
		}
	}

	f.SetA()         // Set that we are using group A
	f.A().SetV(true) // then we can use the group A getter to set the inner values

Enums

capnpc-go generates enum values as constants. For example in the capnp file:

	enum ElementSize {
	  empty @0;
	  bit @1;
	  byte @2;
	  twoBytes @3;
	  fourBytes @4;
	  eightBytes @5;
	  pointer @6;
	  inlineComposite @7;
	}

In the generated capnp.go file:

	type ElementSize uint16

	const (
		ElementSize_empty           ElementSize = 0
		ElementSize_bit             ElementSize = 1
		ElementSize_byte            ElementSize = 2
		ElementSize_twoBytes        ElementSize = 3
		ElementSize_fourBytes       ElementSize = 4
		ElementSize_eightBytes      ElementSize = 5
		ElementSize_pointer         ElementSize = 6
		ElementSize_inlineComposite ElementSize = 7
	)

In addition an enum.String() function is generated that will convert the constants to a string
for debugging or logging purposes. By default, the enum name is used as the tag value,
but the tags can be customized with a $Go.tag or $Go.notag annotation.

For example:

	enum ElementSize {
		empty @0           $Go.tag("void");
		bit @1             $Go.tag("1 bit");
		byte @2            $Go.tag("8 bits");
		inlineComposite @7 $Go.notag;
	}

In the generated go file:

	func (c ElementSize) String() string {
		switch c {
		case ElementSize_empty:
			return "void"
		case ElementSize_bit:
			return "1 bit"
		case ElementSize_byte:
			return "8 bits"
		default:
			return ""
		}
	}

Interfaces

capnpc-go generates type-safe Client wrappers for interfaces. For parameter
lists and result lists, structs are generated as described above with the names
Interface_method_Params and Interface_method_Results, unless a single struct
type is used. For example, for this interface:

	interface Calculator {
		evaluate @0 (expression :Expression) -> (value :Value);
	}

capnpc-go generates the following Go code (along with the structs
Calculator_evaluate_Params and Calculator_evaluate_Results):

	// Calculator is a client to a Calculator interface.
	type Calculator struct { c capnp.Client }

	// NewCalculator creates a Calculator from a generic promise.
	func NewCalculator(c capnp.Client) Calculator

	// GenericClient returns the underlying generic client.
	func (c Calculator) GenericClient() capnp.Client

	// IsNull returns whether the underlying client is nil.
	func (c Calculator) IsNull() bool

	// Evaluate calls `evaluate` on the client.  params is called on a newly
	// allocated Calculator_evaluate_Params to fill in the parameters.
	func (c Calculator) Evaluate(
		ctx context.Context,
		params func(Calculator_evaluate_Params),
		opts ...capnp.CallOption) *Calculator_evaluate_Results_Promise

capnpc-go also generates code to implement the interface:

	// A Calculator_Server implements the Calculator interface.
	type Calculator_Server interface {
		Evaluate(Calculator_evaluate_Call) error
	}

	// Calculator_evaluate_Call holds the arguments for a Calculator.evaluate server call.
	type Calculator_evaluate_Call struct {
		Ctx     context.Context
		Options capnp.CallOptions
		Params  Calculator_evaluate_Params
		Results Calculator_evaluate_Results
	}

	// Calculator_ServerToClient is equivalent to calling:
	// NewCalculator(capnp.NewServer(Calculator_Methods(nil, s), s))
	// If s does not implement the Close method, then nil is used.
	func Calculator_ServerToClient(s Calculator_Server) Calculator

	// Calculator_Methods appends methods from Calculator that call to server and
	// returns the methods.  If methods is nil or the capacity of the underlying
	// slice is too small, a new slice is returned.
	func Calculator_Methods(methods []server.Method, s Calculator_Server) []server.Method

Since a single capability may want to implement many interfaces, you can
use multiple *_Methods functions to build a single slice to send to
NewServer.

An example of combining the client/server code to communicate with a locally
implemented Calculator:

	var srv Calculator_Server
	calc := Calculator_ServerToClient(srv)
	result := calc.Evaluate(ctx, func(params Calculator_evaluate_Params) {
		params.SetExpression(expr)
	})
	val := result.Value().Get()

A note about message ordering: when implementing a server method, you
are responsible for acknowledging delivery of a method call.  Failure to
do so can cause deadlocks.  See the server.Ack function for more details.
*/
package capnp // import "zombiezen.com/go/capnproto"
<|endoftext|>


<commit_before>/*
Package goics is a toolkit for encoding and decoding ics/Ical/icalendar files.

This is a work in progress project, that will try to incorporate as many exceptions and variants of the format.

This is a toolkit because user has to define the way it needs the data. The idea is builded with something similar to the consumer/provider pattern.

We want to decode a stream of vevents from a .ics file into a custom type Events

type Event struct {
	Start, End  time.Time
	Id, Summary string
}

type Events []Event

func (e *Events) ConsumeICal(c *goics.Calendar, err error) error {
	for _, el := range c.Events {
		node := el.Data
		dtstart, err := node["DTSTART"].DateDecode()
		if err != nil {
			return err
		}
		dtend, err := node["DTEND"].DateDecode()
		if err != nil {
			return err
		}
		d := Event{
			Start:   dtstart,
			End:     dtend,
			Id:      node["UID"].Val,
			Summary: node["SUMMARY"].Val,
		}
		*e = append(*e, d)
	}
	return nil
}

Our custom type, will need to implement ICalConsumer interface, where,
the type will pick up data from the format.
The decoding process will be somthing like this:

d := goics.NewDecoder(strings.NewReader(testConsumer))
consumer := Events{}
err := d.Decode(&consumer)

I have choosed this model, because, this format is a pain and also I don't like a lot the reflect package.

For encoding objects to iCal format, something similar has to be done:

The object emitting elements for the encoder, will have to implement the ICalEmiter
type EventTest struct {
	component goics.Componenter
}

func (evt *EventTest) EmitICal() goics.Componenter {
	return evt.component
}

The Componenter, is an interface that every Component that can be encoded to ical implements.

c := goics.NewComponent()
c.SetType("VCALENDAR")
c.AddProperty("CALSCAL", "GREGORIAN")
c.AddProperty("PRODID", "-//tmpo.io/src/goics")

m := goics.NewComponent()
m.SetType("VEVENT")
m.AddProperty("UID", "testing")
c.AddComponent(m)

*/
package goics<commit_msg>correct some format for doc.go<commit_after>/*
Package goics is a toolkit for encoding and decoding ics/Ical/icalendar files.

This is a work in progress project, that will try to incorporate as many exceptions and variants of the format.

This is a toolkit because user has to define the way it needs the data. The idea is builded with something similar to the consumer/provider pattern.

We want to decode a stream of vevents from a .ics file into a custom type Events

	type Event struct {
		Start, End  time.Time
		Id, Summary string
	}

	type Events []Event

	func (e *Events) ConsumeICal(c *goics.Calendar, err error) error {
		for _, el := range c.Events {
			node := el.Data
			dtstart, err := node["DTSTART"].DateDecode()
			if err != nil {
				return err
			}
			dtend, err := node["DTEND"].DateDecode()
			if err != nil {
				return err
			}
			d := Event{
				Start:   dtstart,
				End:     dtend,
				Id:      node["UID"].Val,
				Summary: node["SUMMARY"].Val,
			}
			*e = append(*e, d)
		}
		return nil
	}

Our custom type, will need to implement ICalConsumer interface, where,
the type will pick up data from the format.
The decoding process will be somthing like this:

	d := goics.NewDecoder(strings.NewReader(testConsumer))
	consumer := Events{}
	err := d.Decode(&consumer)

I have choosed this model, because, this format is a pain and also I don't like a lot the reflect package.

For encoding objects to iCal format, something similar has to be done:

The object emitting elements for the encoder, will have to implement the ICalEmiter

	type EventTest struct {
		component goics.Componenter
	}

	func (evt *EventTest) EmitICal() goics.Componenter {
		return evt.component
	}

The Componenter, is an interface that every Component that can be encoded to ical implements.

	c := goics.NewComponent()
	c.SetType("VCALENDAR")
	c.AddProperty("CALSCAL", "GREGORIAN")
	c.AddProperty("PRODID", "-//tmpo.io/src/goics")

	m := goics.NewComponent()
	m.SetType("VEVENT")
	m.AddProperty("UID", "testing")
	c.AddComponent(m)

A simple example not functional used for testing:

	c := goics.NewComponent()
	c.SetType("VCALENDAR")
	c.AddProperty("CALSCAL", "GREGORIAN")

	ins := &EventTest{
		component: c,
	}

	w := &bytes.Buffer{}
	enc := goics.NewICalEncode(w)
	enc.Encode(ins)

*/
package goics<|endoftext|>


<commit_before>package ec2fzf

import (
	"bytes"
	"fmt"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"
)

func (e *Ec2fzf) ListInstances() ([]*ec2.Instance, error) {
	instances := make([]*ec2.Instance, 0, 0)
	filters := make([]*ec2.Filter, 0, 0)
	for _, filter := range e.options.Filters {
		split := strings.SplitN(filter, "=", 2)
		if len(split) < 2 {
			return nil, fmt.Errorf("Filters can only contain one '='. Filter \"%s\" has %d", filter, len(split))
		}

		filters = append(filters, &ec2.Filter{
			Name:   aws.String(split[0]),
			Values: []*string{aws.String(split[1])},
		})
	}
	params := &ec2.DescribeInstancesInput{
		Filters: filters,
	}

	err := e.ec2.DescribeInstancesPages(
		params,
		func(p *ec2.DescribeInstancesOutput, lastPage bool) bool {
			for _, r := range p.Reservations {
				for _, i := range r.Instances {
					instances = append(instances, i)
				}
			}
			return !lastPage
		},
	)

	return instances, err
}

func (e *Ec2fzf) GetConnectionDetails(instanceId string) (string, error) {
	params := &ec2.DescribeInstancesInput{
		InstanceIds: []*string{aws.String(instanceId)},
	}
	resp, err := e.ec2.DescribeInstances(params)
	if err != nil {
		return "", err
	}

	if !(len(resp.Reservations) == 1) || !(len(resp.Reservations[0].Instances) == 1) {
		return "", fmt.Errorf("No instance could be found for %s", instanceId)
	}

	if e.options.UsePrivateIp {
		return *resp.Reservations[0].Instances[0].PrivateIpAddress, nil
	}
	return *resp.Reservations[0].Instances[0].PublicDnsName, nil
}

func (e *Ec2fzf) StringFromInstance(i *ec2.Instance) (string, error) {
	tags := make(map[string]string)

	for _, t := range i.Tags {
		tags[*t.Key] = *t.Value
	}

	buffer := new(bytes.Buffer)
	err := e.template.Execute(
		buffer,
		struct {
			Tags map[string]string
		}{
			Tags: tags,
		},
	)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%19s: %s", *i.InstanceId, buffer.String()), nil
}

func InstanceIdFromString(s string) (string, error) {
	i := strings.Index(s, ":")

	if i < 0 {
		return "", fmt.Errorf("Unable to find instance id")
	}
	return strings.TrimSpace(s[0:i]), nil
}
<commit_msg>Fix an issue where having no filters resulted in a 400 request.<commit_after>package ec2fzf

import (
	"bytes"
	"fmt"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"
)

func (e *Ec2fzf) ListInstances() ([]*ec2.Instance, error) {
	instances := make([]*ec2.Instance, 0, 0)
	filters := make([]*ec2.Filter, 0, 0)
	for _, filter := range e.options.Filters {
		split := strings.SplitN(filter, "=", 2)
		if len(split) < 2 {
			return nil, fmt.Errorf("Filters can only contain one '='. Filter \"%s\" has %d", filter, len(split))
		}

		filters = append(filters, &ec2.Filter{
			Name:   aws.String(split[0]),
			Values: []*string{aws.String(split[1])},
		})
	}
	params := &ec2.DescribeInstancesInput{}

	if len(filters) > 0 {
		params.Filters = filters
	}

	err := e.ec2.DescribeInstancesPages(
		params,
		func(p *ec2.DescribeInstancesOutput, lastPage bool) bool {
			for _, r := range p.Reservations {
				for _, i := range r.Instances {
					instances = append(instances, i)
				}
			}
			return !lastPage
		},
	)

	return instances, err
}

func (e *Ec2fzf) GetConnectionDetails(instanceId string) (string, error) {
	params := &ec2.DescribeInstancesInput{
		InstanceIds: []*string{aws.String(instanceId)},
	}
	resp, err := e.ec2.DescribeInstances(params)
	if err != nil {
		return "", err
	}

	if !(len(resp.Reservations) == 1) || !(len(resp.Reservations[0].Instances) == 1) {
		return "", fmt.Errorf("No instance could be found for %s", instanceId)
	}

	if e.options.UsePrivateIp {
		return *resp.Reservations[0].Instances[0].PrivateIpAddress, nil
	}
	return *resp.Reservations[0].Instances[0].PublicDnsName, nil
}

func (e *Ec2fzf) StringFromInstance(i *ec2.Instance) (string, error) {
	tags := make(map[string]string)

	for _, t := range i.Tags {
		tags[*t.Key] = *t.Value
	}

	buffer := new(bytes.Buffer)
	err := e.template.Execute(
		buffer,
		struct {
			Tags map[string]string
		}{
			Tags: tags,
		},
	)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%19s: %s", *i.InstanceId, buffer.String()), nil
}

func InstanceIdFromString(s string) (string, error) {
	i := strings.Index(s, ":")

	if i < 0 {
		return "", fmt.Errorf("Unable to find instance id")
	}
	return strings.TrimSpace(s[0:i]), nil
}
<|endoftext|>


<commit_before>// Copyright (AT) 2017 Bill
// created 10 Oct, 2017
package foo

import (
    "fmt"
)

const VERSION = "1.0.0"

type Foo struct {}
func (f *Foo) Bar() {
    fmt.Println("bar! " + VERSION)
}

func NewFoo() *Foo {
    return &Foo{}
}
<commit_msg>use log instead of fmt<commit_after>// Copyright (AT) 2017 Bill
// created 10 Oct, 2017
package foo

import (
    "github.com/go-foo/foo/internal/log"
)

const VERSION = "1.0.1"

type Foo struct {}
func (f *Foo) Bar() {
    log.Println("bar!", VERSION)
}

func NewFoo() *Foo {
    return &Foo{}
}
<|endoftext|>


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

package main

import (
	"fmt"
	"go/ast"
	"go/build"
	"go/parser"
	"go/scanner"
	"go/token"
	"os"
	"path/filepath"

	"github.com/go-python/py/bind"
	"golang.org/x/tools/go/loader"
)

var (
	fset = token.NewFileSet()
)

func genPkg(odir string, pkg *build.Package) error {
	var err error
	var o *os.File

	files, err := parseFiles(pkg.Dir, pkg.GoFiles)
	if err != nil {
		return err
	}

	conf := loader.Config{
		SourceImports: true,
		Fset:          fset,
	}
	conf.TypeChecker.Error = func(e error) {
		errorf("%v\n", e)
		err = e
	}

	conf.CreateFromFiles(pkg.ImportPath, files...)
	program, err := conf.Load()
	if err != nil {
		errorf("%v\n", err)
		return err
	}
	p := program.Created[0].Pkg

	switch *lang {
	case "python", "py":
		o, err = os.Create(filepath.Join(odir, p.Name()+".c"))
		if err != nil {
			return err
		}
		err = bind.GenCPython(o, fset, p)
	case "go":
		o, err = os.Create(filepath.Join(odir, p.Name()+".go"))
		if err != nil {
			return err
		}
		err = bind.GenGo(o, fset, p)
	default:
		return fmt.Errorf("unknown target language: %q\n", *lang)
	}

	if err != nil {
		if list, _ := err.(bind.ErrorList); len(list) > 0 {
			for _, err := range list {
				errorf("%v\n", err)
			}
		} else {
			errorf("%v\n", err)
		}
	}

	if err != nil {
		return err
	}

	err = o.Close()
	if err != nil {
		return err
	}

	return err
}

func parseFiles(dir string, fnames []string) ([]*ast.File, error) {
	var (
		files []*ast.File
		err   error
	)

	for _, fname := range fnames {
		path := filepath.Join(dir, fname)
		file, errf := parser.ParseFile(fset, path, nil, parser.AllErrors)
		if errf != nil {
			err = errf
			if list, _ := err.(scanner.ErrorList); len(list) > 0 {
				for _, err := range list {

					errorf("%v\n", err)
				}
			} else {
				errorf("%v\n", err)
			}
		}
		files = append(files, file)
	}

	return files, err
}
<commit_msg>gopy-gen: bridge in go/doc.Package<commit_after>// Copyright 2015 The go-python Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"go/ast"
	"go/build"
	"go/doc"
	"go/parser"
	"go/scanner"
	"go/token"
	"os"
	"path/filepath"

	"github.com/go-python/py/bind"
	"golang.org/x/tools/go/loader"
)

var (
	fset = token.NewFileSet()
)

func genPkg(odir string, pkg *build.Package) error {
	var err error
	var o *os.File

	files, err := parseFiles(pkg.Dir, pkg.GoFiles)
	if err != nil {
		return err
	}

	conf := loader.Config{
		SourceImports: true,
		Fset:          fset,
	}
	conf.TypeChecker.Error = func(e error) {
		errorf("%v\n", e)
		err = e
	}

	p, err := newPackage(files, &conf, pkg)
	if err != nil {
		errorf("%v\n", err)
		return err
	}

	switch *lang {
	case "python", "py":
		o, err = os.Create(filepath.Join(odir, p.Name()+".c"))
		if err != nil {
			return err
		}
		err = bind.GenCPython(o, fset, p)
	case "go":
		o, err = os.Create(filepath.Join(odir, p.Name()+".go"))
		if err != nil {
			return err
		}
		err = bind.GenGo(o, fset, p)
	default:
		return fmt.Errorf("unknown target language: %q\n", *lang)
	}

	if err != nil {
		if list, _ := err.(bind.ErrorList); len(list) > 0 {
			for _, err := range list {
				errorf("%v\n", err)
			}
		} else {
			errorf("%v\n", err)
		}
	}

	if err != nil {
		return err
	}

	err = o.Close()
	if err != nil {
		return err
	}

	return err
}

func parseFiles(dir string, fnames []string) ([]*ast.File, error) {
	var (
		files []*ast.File
		err   error
	)

	for _, fname := range fnames {
		path := filepath.Join(dir, fname)
		file, errf := parser.ParseFile(fset, path, nil, parser.AllErrors)
		if errf != nil {
			err = errf
			if list, _ := err.(scanner.ErrorList); len(list) > 0 {
				for _, err := range list {

					errorf("%v\n", err)
				}
			} else {
				errorf("%v\n", err)
			}
		}
		files = append(files, file)
	}

	return files, err
}

func newPackage(files []*ast.File, conf *loader.Config, pkg *build.Package) (*bind.Package, error) {

	conf.CreateFromFiles(pkg.ImportPath, files...)
	program, err := conf.Load()
	if err != nil {
		return nil, err
	}
	p := program.Created[0].Pkg

	var pkgast *ast.Package
	pkgs, err := parser.ParseDir(fset, pkg.Dir, nil, parser.ParseComments)
	if err != nil {
		return nil, err
	}
	pkgast = pkgs[p.Name()]

	pkgdoc := doc.New(pkgast, pkg.ImportPath, 0)

	return bind.NewPackage(p, pkgdoc), err
}
<|endoftext|>