func (file *GridFile) SetName(name string) {
	file.assertMode(gfsWriting)
	file.m.Lock()
	file.doc.Filename = name
	file.m.Unlock()
}

func ( file * GridFile ) SetName ( name string ) { file . assertMode ( gfsWriting ) file . m . Lock ( ) file . doc . Filename = name file . m . Unlock ( ) }

// SetName changes the optional file name.  An empty string may be used to
// unset it.
//
// It is a runtime error to call this function when the file is not open
// for writing.

SetName changes the optional file name . An empty string may be used to unset it . It is a runtime error to call this function when the file is not open for writing .


func (file *GridFile) SetContentType(ctype string) {
	file.assertMode(gfsWriting)
	file.m.Lock()
	file.doc.ContentType = ctype
	file.m.Unlock()
}

func ( file * GridFile ) SetContentType ( ctype string ) { file . assertMode ( gfsWriting ) file . m . Lock ( ) file . doc . ContentType = ctype file . m . Unlock ( ) }

// ContentType changes the optional file content type.  An empty string may be
// used to unset it.
//
// It is a runtime error to call this function when the file is not open
// for writing.

ContentType changes the optional file content type . An empty string may be used to unset it . It is a runtime error to call this function when the file is not open for writing .


func (file *GridFile) Size() (bytes int64) {
	file.m.Lock()
	bytes = file.doc.Length
	file.m.Unlock()
	return
}

func ( file * GridFile ) Size ( ) ( bytes int64 ) { file . m . Lock ( ) bytes = file . doc . Length file . m . Unlock ( ) return }


func (file *GridFile) SetUploadDate(t time.Time) {
	file.assertMode(gfsWriting)
	file.m.Lock()
	file.doc.UploadDate = t
	file.m.Unlock()
}

func ( file * GridFile ) SetUploadDate ( t time . Time ) { file . assertMode ( gfsWriting ) file . m . Lock ( ) file . doc . UploadDate = t file . m . Unlock ( ) }

// SetUploadDate changes the file upload time.
//
// It is a runtime error to call this function when the file is not open
// for writing.

SetUploadDate changes the file upload time . It is a runtime error to call this function when the file is not open for writing .


func (file *GridFile) Abort() {
	if file.mode != gfsWriting {
		panic("file.Abort must be called on file opened for writing")
	}
	file.err = errors.New("write aborted")
}

func ( file * GridFile ) Abort ( ) { if file . mode != gfsWriting { panic ( " " ) } file . err = errors . New ( " " ) }

// Abort cancels an in-progress write, preventing the file from being
// automically created and ensuring previously written chunks are
// removed when the file is closed.
//
// It is a runtime error to call Abort when the file was not opened
// for writing.

Abort cancels an in - progress write preventing the file from being automically created and ensuring previously written chunks are removed when the file is closed . It is a runtime error to call Abort when the file was not opened for writing .


func (file *GridFile) Write(data []byte) (n int, err error) {
	file.assertMode(gfsWriting)
	file.m.Lock()
	debugf("GridFile %p: writing %d bytes", file, len(data))
	defer file.m.Unlock()

	if file.err != nil {
		return 0, file.err
	}

	n = len(data)
	file.doc.Length += int64(n)
	chunkSize := file.doc.ChunkSize

	if len(file.wbuf)+len(data) < chunkSize {
		file.wbuf = append(file.wbuf, data...)
		return
	}

	// First, flush file.wbuf complementing with data.
	if len(file.wbuf) > 0 {
		missing := chunkSize - len(file.wbuf)
		if missing > len(data) {
			missing = len(data)
		}
		file.wbuf = append(file.wbuf, data[:missing]...)
		data = data[missing:]
		file.insertChunk(file.wbuf)
		file.wbuf = file.wbuf[0:0]
	}

	// Then, flush all chunks from data without copying.
	for len(data) > chunkSize {
		size := chunkSize
		if size > len(data) {
			size = len(data)
		}
		file.insertChunk(data[:size])
		data = data[size:]
	}

	// And append the rest for a future call.
	file.wbuf = append(file.wbuf, data...)

	return n, file.err
}

// Write writes the provided data to the file and returns the
// number of bytes written and an error in case something
// wrong happened.
//
// The file will internally cache the data so that all but the last
// chunk sent to the database have the size defined by SetChunkSize.
// This also means that errors may be deferred until a future call
// to Write or Close.
//
// The parameters and behavior of this function turn the file
// into an io.Writer.

Write writes the provided data to the file and returns the number of bytes written and an error in case something wrong happened . The file will internally cache the data so that all but the last chunk sent to the database have the size defined by SetChunkSize . This also means that errors may be deferred until a future call to Write or Close . The parameters and behavior of this function turn the file into an io . Writer .


func (file *GridFile) Read(b []byte) (n int, err error) {
	file.assertMode(gfsReading)
	file.m.Lock()
	debugf("GridFile %p: reading at offset %d into buffer of length %d", file, file.offset, len(b))
	defer file.m.Unlock()
	if file.offset == file.doc.Length {
		return 0, io.EOF
	}
	for err == nil {
		i := copy(b, file.rbuf)
		n += i
		file.offset += int64(i)
		file.rbuf = file.rbuf[i:]
		if i == len(b) || file.offset == file.doc.Length {
			break
		}
		b = b[i:]
		file.rbuf, err = file.getChunk()
	}
	return n, err
}

func ( file * GridFile ) Read ( b [ ] byte ) ( n int , err error ) { file . assertMode ( gfsReading ) file . m . Lock ( ) debugf ( " " , file , file . offset , len ( b ) ) defer file . m . Unlock ( ) if file . offset == file . doc . Length { return 0 , io . EOF } for err == nil { i := copy ( b , file . rbuf ) n += i file . offset += int64 ( i ) file . rbuf = file . rbuf [ i : ] if i == len ( b ) || file . offset == file . doc . Length { break } b = b [ i : ] file . rbuf , err = file . getChunk ( ) } return n , err }

// Read reads into b the next available data from the file and
// returns the number of bytes written and an error in case
// something wrong happened.  At the end of the file, n will
// be zero and err will be set to os.EOF.
//
// The parameters and behavior of this function turn the file
// into an io.Reader.

Read reads into b the next available data from the file and returns the number of bytes written and an error in case something wrong happened . At the end of the file n will be zero and err will be set to os . EOF . The parameters and behavior of this function turn the file into an io . Reader .


func (h *windowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error {
	position.X = ensureInRange(position.X, window.Left, window.Right)
	position.Y = ensureInRange(position.Y, window.Top, window.Bottom)
	err := SetConsoleCursorPosition(h.fd, position)
	if err != nil {
		return err
	}
	h.logf("Cursor position set: (%d, %d)", position.X, position.Y)
	return err
}

func ( h * windowsAnsiEventHandler ) setCursorPosition ( position COORD , window SMALL_RECT ) error { position . X = ensureInRange ( position . X , window . Left , window . Right ) position . Y = ensureInRange ( position . Y , window . Top , window . Bottom ) err := SetConsoleCursorPosition ( h . fd , position ) if err != nil { return err } h . logf ( " " , position . X , position . Y ) return err }

// setCursorPosition sets the cursor to the specified position, bounded to the screen size

setCursorPosition sets the cursor to the specified position bounded to the screen size


func collectAnsiIntoWindowsAttributes(windowsMode uint16, inverted bool, baseMode uint16, ansiMode int16) (uint16, bool) {
	switch ansiMode {

	// Mode styles
	case ansiterm.ANSI_SGR_BOLD:
		windowsMode = windowsMode | FOREGROUND_INTENSITY

	case ansiterm.ANSI_SGR_DIM, ansiterm.ANSI_SGR_BOLD_DIM_OFF:
		windowsMode &^= FOREGROUND_INTENSITY

	case ansiterm.ANSI_SGR_UNDERLINE:
		windowsMode = windowsMode | COMMON_LVB_UNDERSCORE

	case ansiterm.ANSI_SGR_REVERSE:
		inverted = true

	case ansiterm.ANSI_SGR_REVERSE_OFF:
		inverted = false

	case ansiterm.ANSI_SGR_UNDERLINE_OFF:
		windowsMode &^= COMMON_LVB_UNDERSCORE

		// Foreground colors
	case ansiterm.ANSI_SGR_FOREGROUND_DEFAULT:
		windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK)

	case ansiterm.ANSI_SGR_FOREGROUND_BLACK:
		windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK)

	case ansiterm.ANSI_SGR_FOREGROUND_RED:
		windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED

	case ansiterm.ANSI_SGR_FOREGROUND_GREEN:
		windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN

	case ansiterm.ANSI_SGR_FOREGROUND_YELLOW:
		windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN

	case ansiterm.ANSI_SGR_FOREGROUND_BLUE:
		windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE

	case ansiterm.ANSI_SGR_FOREGROUND_MAGENTA:
		windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE

	case ansiterm.ANSI_SGR_FOREGROUND_CYAN:
		windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE

	case ansiterm.ANSI_SGR_FOREGROUND_WHITE:
		windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE

		// Background colors
	case ansiterm.ANSI_SGR_BACKGROUND_DEFAULT:
		// Black with no intensity
		windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK)

	case ansiterm.ANSI_SGR_BACKGROUND_BLACK:
		windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK)

	case ansiterm.ANSI_SGR_BACKGROUND_RED:
		windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED

	case ansiterm.ANSI_SGR_BACKGROUND_GREEN:
		windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN

	case ansiterm.ANSI_SGR_BACKGROUND_YELLOW:
		windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN

	case ansiterm.ANSI_SGR_BACKGROUND_BLUE:
		windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE

	case ansiterm.ANSI_SGR_BACKGROUND_MAGENTA:
		windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE

	case ansiterm.ANSI_SGR_BACKGROUND_CYAN:
		windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE

	case ansiterm.ANSI_SGR_BACKGROUND_WHITE:
		windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
	}

	return windowsMode, inverted
}

func
collectAnsiIntoWindowsAttributes
(
windowsMode
uint16
,
inverted
bool
,
baseMode
uint16
,
ansiMode
int16
)
(
uint16
,
bool
)
{
switch
ansiMode
{
// Mode styles
case
ansiterm
.
ANSI_SGR_BOLD
:
windowsMode
=
windowsMode
|
FOREGROUND_INTENSITY
case
ansiterm
.
ANSI_SGR_DIM
,
ansiterm
.
ANSI_SGR_BOLD_DIM_OFF
:
windowsMode
&^=
FOREGROUND_INTENSITY
case
ansiterm
.
ANSI_SGR_UNDERLINE
:
windowsMode
=
windowsMode
|
COMMON_LVB_UNDERSCORE
case
ansiterm
.
ANSI_SGR_REVERSE
:
inverted
=
true
case
ansiterm
.
ANSI_SGR_REVERSE_OFF
:
inverted
=
false
case
ansiterm
.
ANSI_SGR_UNDERLINE_OFF
:
windowsMode
&^=
COMMON_LVB_UNDERSCORE
// Foreground colors
case
ansiterm
.
ANSI_SGR_FOREGROUND_DEFAULT
:
windowsMode
=
(
windowsMode
&^
FOREGROUND_MASK
)
|
(
baseMode
&
FOREGROUND_MASK
)
case
ansiterm
.
ANSI_SGR_FOREGROUND_BLACK
:
windowsMode
=
(
windowsMode
&^
FOREGROUND_COLOR_MASK
)
case
ansiterm
.
ANSI_SGR_FOREGROUND_RED
:
windowsMode
=
(
windowsMode
&^
FOREGROUND_COLOR_MASK
)
|
FOREGROUND_RED
case
ansiterm
.
ANSI_SGR_FOREGROUND_GREEN
:
windowsMode
=
(
windowsMode
&^
FOREGROUND_COLOR_MASK
)
|
FOREGROUND_GREEN
case
ansiterm
.
ANSI_SGR_FOREGROUND_YELLOW
:
windowsMode
=
(
windowsMode
&^
FOREGROUND_COLOR_MASK
)
|
FOREGROUND_RED
|
FOREGROUND_GREEN
case
ansiterm
.
ANSI_SGR_FOREGROUND_BLUE
:
windowsMode
=
(
windowsMode
&^
FOREGROUND_COLOR_MASK
)
|
FOREGROUND_BLUE
case
ansiterm
.
ANSI_SGR_FOREGROUND_MAGENTA
:
windowsMode
=
(
windowsMode
&^
FOREGROUND_COLOR_MASK
)
|
FOREGROUND_RED
|
FOREGROUND_BLUE
case
ansiterm
.
ANSI_SGR_FOREGROUND_CYAN
:
windowsMode
=
(
windowsMode
&^
FOREGROUND_COLOR_MASK
)
|
FOREGROUND_GREEN
|
FOREGROUND_BLUE
case
ansiterm
.
ANSI_SGR_FOREGROUND_WHITE
:
windowsMode
=
(
windowsMode
&^
FOREGROUND_COLOR_MASK
)
|
FOREGROUND_RED
|
FOREGROUND_GREEN
|
FOREGROUND_BLUE
// Background colors
case
ansiterm
.
ANSI_SGR_BACKGROUND_DEFAULT
:
// Black with no intensity
windowsMode
=
(
windowsMode
&^
BACKGROUND_MASK
)
|
(
baseMode
&
BACKGROUND_MASK
)
case
ansiterm
.
ANSI_SGR_BACKGROUND_BLACK
:
windowsMode
=
(
windowsMode
&^
BACKGROUND_COLOR_MASK
)
case
ansiterm
.
ANSI_SGR_BACKGROUND_RED
:
windowsMode
=
(
windowsMode
&^
BACKGROUND_COLOR_MASK
)
|
BACKGROUND_RED
case
ansiterm
.
ANSI_SGR_BACKGROUND_GREEN
:
windowsMode
=
(
windowsMode
&^
BACKGROUND_COLOR_MASK
)
|
BACKGROUND_GREEN
case
ansiterm
.
ANSI_SGR_BACKGROUND_YELLOW
:
windowsMode
=
(
windowsMode
&^
BACKGROUND_COLOR_MASK
)
|
BACKGROUND_RED
|
BACKGROUND_GREEN
case
ansiterm
.
ANSI_SGR_BACKGROUND_BLUE
:
windowsMode
=
(
windowsMode
&^
BACKGROUND_COLOR_MASK
)
|
BACKGROUND_BLUE
case
ansiterm
.
ANSI_SGR_BACKGROUND_MAGENTA
:
windowsMode
=
(
windowsMode
&^
BACKGROUND_COLOR_MASK
)
|
BACKGROUND_RED
|
BACKGROUND_BLUE
case
ansiterm
.
ANSI_SGR_BACKGROUND_CYAN
:
windowsMode
=
(
windowsMode
&^
BACKGROUND_COLOR_MASK
)
|
BACKGROUND_GREEN
|
BACKGROUND_BLUE
case
ansiterm
.
ANSI_SGR_BACKGROUND_WHITE
:
windowsMode
=
(
windowsMode
&^
BACKGROUND_COLOR_MASK
)
|
BACKGROUND_RED
|
BACKGROUND_GREEN
|
BACKGROUND_BLUE
}
return
windowsMode
,
inverted
}

// collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the
// request represented by the passed ANSI mode.

collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the request represented by the passed ANSI mode .


func invertAttributes(windowsMode uint16) uint16 {
	return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4)
}

func invertAttributes ( windowsMode uint16 ) uint16 { return ( COMMON_LVB_MASK & windowsMode ) | ( ( FOREGROUND_MASK & windowsMode ) << 4 ) | ( ( BACKGROUND_MASK & windowsMode ) >> 4 ) }

// invertAttributes inverts the foreground and background colors of a Windows attributes value


func (h *windowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) {
	if h.wrapNext {
		if err := h.Flush(); err != nil {
			return false, err
		}
		h.clearWrap()
	}
	pos, info, err := h.getCurrentInfo()
	if err != nil {
		return false, err
	}
	sr := h.effectiveSr(info.Window)
	if pos.Y == sr.bottom {
		// Scrolling is necessary. Let Windows automatically scroll if the scrolling region
		// is the full window.
		if sr.top == info.Window.Top && sr.bottom == info.Window.Bottom {
			if includeCR {
				pos.X = 0
				h.updatePos(pos)
			}
			return false, nil
		}

		// A custom scroll region is active. Scroll the window manually to simulate
		// the LF.
		if err := h.Flush(); err != nil {
			return false, err
		}
		h.logf("Simulating LF inside scroll region")
		if err := h.scrollUp(1); err != nil {
			return false, err
		}
		if includeCR {
			pos.X = 0
			if err := SetConsoleCursorPosition(h.fd, pos); err != nil {
				return false, err
			}
		}
		return true, nil

	} else if pos.Y < info.Window.Bottom {
		// Let Windows handle the LF.
		pos.Y++
		if includeCR {
			pos.X = 0
		}
		h.updatePos(pos)
		return false, nil
	} else {
		// The cursor is at the bottom of the screen but outside the scroll
		// region. Skip the LF.
		h.logf("Simulating LF outside scroll region")
		if includeCR {
			if err := h.Flush(); err != nil {
				return false, err
			}
			pos.X = 0
			if err := SetConsoleCursorPosition(h.fd, pos); err != nil {
				return false, err
			}
		}
		return true, nil
	}
}

// simulateLF simulates a LF or CR+LF by scrolling if necessary to handle the
// current cursor position and scroll region settings, in which case it returns
// true. If no special handling is necessary, then it does nothing and returns
// false.
//
// In the false case, the caller should ensure that a carriage return
// and line feed are inserted or that the text is otherwise wrapped.

simulateLF simulates a LF or CR + LF by scrolling if necessary to handle the current cursor position and scroll region settings in which case it returns true . If no special handling is necessary then it does nothing and returns false . In the false case the caller should ensure that a carriage return and line feed are inserted or that the text is otherwise wrapped .


func (h *windowsAnsiEventHandler) executeLF() error {
	handled, err := h.simulateLF(false)
	if err != nil {
		return err
	}
	if !handled {
		// Windows LF will reset the cursor column position. Write the LF
		// and restore the cursor position.
		pos, _, err := h.getCurrentInfo()
		if err != nil {
			return err
		}
		h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED)
		if pos.X != 0 {
			if err := h.Flush(); err != nil {
				return err
			}
			h.logf("Resetting cursor position for LF without CR")
			if err := SetConsoleCursorPosition(h.fd, pos); err != nil {
				return err
			}
		}
	}
	return nil
}

// executeLF executes a LF without a CR.


func (h *windowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion {
	top := addInRange(window.Top, h.sr.top, window.Top, window.Bottom)
	bottom := addInRange(window.Top, h.sr.bottom, window.Top, window.Bottom)
	if top >= bottom {
		top = window.Top
		bottom = window.Bottom
	}
	return scrollRegion{top: top, bottom: bottom}
}

func ( h * windowsAnsiEventHandler ) effectiveSr ( window SMALL_RECT ) scrollRegion { top := addInRange ( window . Top , h . sr . top , window . Top , window . Bottom ) bottom := addInRange ( window . Top , h . sr . bottom , window . Top , window . Bottom ) if top >= bottom { top = window . Top bottom = window . Bottom } return scrollRegion { top : top , bottom : bottom } }

// effectiveSr gets the current effective scroll region in buffer coordinates


func (h *windowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error {
	h.logf("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom)
	h.logf("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom)

	// Copy from and clip to the scroll region (full buffer width)
	scrollRect := SMALL_RECT{
		Top:    sr.top,
		Bottom: sr.bottom,
		Left:   0,
		Right:  info.Size.X - 1,
	}

	// Origin to which area should be copied
	destOrigin := COORD{
		X: 0,
		Y: sr.top - int16(param),
	}

	char := CHAR_INFO{
		UnicodeChar: ' ',
		Attributes:  h.attributes,
	}

	if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil {
		return err
	}
	return nil
}

// scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates.

scroll scrolls the provided scroll region by param lines . The scroll region is in buffer coordinates .


func (h *windowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error {
	// Copy from and clip to the scroll region (full buffer width)
	scrollRect := SMALL_RECT{
		Top:    position.Y,
		Bottom: position.Y,
		Left:   position.X,
		Right:  info.Size.X - 1,
	}

	// Origin to which area should be copied
	destOrigin := COORD{
		X: position.X - int16(columns),
		Y: position.Y,
	}

	char := CHAR_INFO{
		UnicodeChar: ' ',
		Attributes:  h.attributes,
	}

	if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil {
		return err
	}
	return nil
}

// scrollLine scrolls a line horizontally starting at the provided position by a number of columns.

scrollLine scrolls a line horizontally starting at the provided position by a number of columns .


func bytesToHex(b []byte) string {
	hex := make([]string, len(b))
	for i, ch := range b {
		hex[i] = fmt.Sprintf("%X", ch)
	}
	return strings.Join(hex, "")
}

func bytesToHex ( b [ ] byte ) string { hex := make ( [ ] string , len ( b ) ) for i , ch := range b { hex [ i ] = fmt . Sprintf ( " " , ch ) } return strings . Join ( hex , " " ) }

// bytesToHex converts a slice of bytes to a human-readable string.

bytesToHex converts a slice of bytes to a human - readable string .


func (e *FileCacheEntry) readCloser() (*CachedFile, error) {
	var f *os.File
	var err error

	if e.fileDoesNotExist() {
		f, err = os.Create(e.FilePath)
		if err != nil {
			return nil, err
		}

		err = compressor.WriteTar(e.ExpandedDirectoryPath+"/", f)
		if err != nil {
			return nil, err
		}

		// If the directory is not used remove it
		if e.directoryInUseCount == 0 {
			err = os.RemoveAll(e.ExpandedDirectoryPath)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Unable to remove cached directory", err)
			}
		} else {
			// Double the size to account for both assets
			e.Size = e.Size * 2
		}
	} else {
		f, err = os.Open(e.FilePath)
		if err != nil {
			return nil, err
		}
	}

	e.incrementFileInUseCount()

	if _, err := f.Seek(0, os.SEEK_SET); err != nil {
		return nil, err
	}

	readCloser := NewFileCloser(f, func(filePath string) {
		lock.Lock()
		e.decrementFileInUseCount()
		lock.Unlock()
	})

	return readCloser, nil
}

// Can we change this to be an io.ReadCloser return

Can we change this to be an io . ReadCloser return


func New(
	downloader *Downloader,
	cache *FileCache,
	transformer CacheTransformer,
) *cachedDownloader {
	os.MkdirAll(cache.CachedPath, 0770)
	return &cachedDownloader{
		cache:         cache,
		cacheLocation: filepath.Join(cache.CachedPath, "saved_cache.json"),
		uncachedPath:  createTempCachedDir(cache.CachedPath),
		downloader:    downloader,
		transformer:   transformer,

		lock:       &sync.Mutex{},
		inProgress: map[string]chan struct{}{},
	}
}

func New ( downloader * Downloader , cache * FileCache , transformer CacheTransformer , ) * cachedDownloader { os . MkdirAll ( cache . CachedPath , 0770 ) return & cachedDownloader { cache : cache , cacheLocation : filepath . Join ( cache . CachedPath , " " ) , uncachedPath : createTempCachedDir ( cache . CachedPath ) , downloader : downloader , transformer : transformer , lock : & sync . Mutex { } , inProgress : map [ string ] chan struct { } { } , } }

// A transformer function can be used to do post-download
// processing on the file before it is stored in the cache.

A transformer function can be used to do post - download processing on the file before it is stored in the cache .


func (c *cachedDownloader) populateCache(
	logger lager.Logger,
	url *url.URL,
	name string,
	cachingInfo CachingInfoType,
	checksum ChecksumInfoType,
	transformer CacheTransformer,
	cancelChan <-chan struct{},
) (download, bool, int64, error) {
	filename, cachingInfo, err := c.downloader.Download(logger, url, func() (*os.File, error) {
		return ioutil.TempFile(c.uncachedPath, name+"-")
	}, cachingInfo, checksum, cancelChan)
	if err != nil {
		return download{}, false, 0, err
	}

	if filename == "" {
		return download{}, true, 0, nil
	}

	fileInfo, err := os.Stat(filename)
	if err != nil {
		return download{}, false, 0, err
	}
	defer os.Remove(filename)

	cachedFile, err := ioutil.TempFile(c.uncachedPath, "transformed")
	if err != nil {
		return download{}, false, 0, err
	}

	err = cachedFile.Close()
	if err != nil {
		return download{}, false, 0, err
	}

	cachedSize, err := transformer(filename, cachedFile.Name())
	if err != nil {
		return download{}, false, 0, err
	}

	return download{
		path:        cachedFile.Name(),
		size:        cachedSize,
		cachingInfo: cachingInfo,
	}, false, fileInfo.Size(), nil
}

func ( c * cachedDownloader ) populateCache ( logger lager . Logger , url * url . URL , name string , cachingInfo CachingInfoType , checksum ChecksumInfoType , transformer CacheTransformer , cancelChan <- chan struct { } , ) ( download , bool , int64 , error ) { filename , cachingInfo , err := c . downloader . Download ( logger , url , func ( ) ( * os . File , error ) { return ioutil . TempFile ( c . uncachedPath , name + " " ) } , cachingInfo , checksum , cancelChan ) if err != nil { return download { } , false , 0 , err } if filename == " " { return download { } , true , 0 , nil } fileInfo , err := os . Stat ( filename ) if err != nil { return download { } , false , 0 , err } defer os . Remove ( filename ) cachedFile , err := ioutil . TempFile ( c . uncachedPath , " " ) if err != nil { return download { } , false , 0 , err } err = cachedFile . Close ( ) if err != nil { return download { } , false , 0 , err } cachedSize , err := transformer ( filename , cachedFile . Name ( ) ) if err != nil { return download { } , false , 0 , err } return download { path : cachedFile . Name ( ) , size : cachedSize , cachingInfo : cachingInfo , } , false , fileInfo . Size ( ) , nil }

// Currently populateCache takes a transformer due to the fact that a fetchCachedDirectory
// uses only a TarTransformer, which overwrites what is currently set. This way one transformer
// can be used to call Fetch and FetchAsDirectory

Currently populateCache takes a transformer due to the fact that a fetchCachedDirectory uses only a TarTransformer which overwrites what is currently set . This way one transformer can be used to call Fetch and FetchAsDirectory


func (ui *ColorUI) Log(message string) {
	ct.ChangeColor(ui.LogFGColor.Code, ui.LogFGColor.Bright, ui.LogBGColor.Code, ui.LogBGColor.Bright)
	ui.UI.Log(message)
	ct.ResetColor()
}

func ( ui * ColorUI ) Log ( message string ) { ct . ChangeColor ( ui . LogFGColor . Code , ui . LogFGColor . Bright , ui . LogBGColor . Code , ui . LogBGColor . Bright ) ui . UI . Log ( message ) ct . ResetColor ( ) }

// Log calls UI.Log to write.
// LogFGColor and LogBGColor are used for color.

Log calls UI . Log to write . LogFGColor and LogBGColor are used for color .


func (ui *ColorUI) Output(message string) {
	ct.ChangeColor(ui.OutputFGColor.Code, ui.OutputFGColor.Bright, ui.OutputBGColor.Code, ui.OutputBGColor.Bright)
	ui.UI.Output(message)
	ct.ResetColor()
}

func ( ui * ColorUI ) Output ( message string ) { ct . ChangeColor ( ui . OutputFGColor . Code , ui . OutputFGColor . Bright , ui . OutputBGColor . Code , ui . OutputBGColor . Bright ) ui . UI . Output ( message ) ct . ResetColor ( ) }

// Output calls UI.Output to write.
// OutputFGColor and OutputBGColor are used for color.

Output calls UI . Output to write . OutputFGColor and OutputBGColor are used for color .


func (ui *ColorUI) Success(message string) {
	ct.ChangeColor(ui.SuccessFGColor.Code, ui.SuccessFGColor.Bright, ui.SuccessBGColor.Code, ui.SuccessBGColor.Bright)
	ui.UI.Success(message)
	ct.ResetColor()
}

func ( ui * ColorUI ) Success ( message string ) { ct . ChangeColor ( ui . SuccessFGColor . Code , ui . SuccessFGColor . Bright , ui . SuccessBGColor . Code , ui . SuccessBGColor . Bright ) ui . UI . Success ( message ) ct . ResetColor ( ) }

// Success calls UI.Success to write.
// Useful when you want separate colors or prefixes.
// SuccessFGColor and SuccessBGColor are used for color.

Success calls UI . Success to write . Useful when you want separate colors or prefixes . SuccessFGColor and SuccessBGColor are used for color .


func (ui *ColorUI) Info(message string) {
	ct.ChangeColor(ui.InfoFGColor.Code, ui.InfoFGColor.Bright, ui.InfoBGColor.Code, ui.InfoBGColor.Bright)
	ui.UI.Info(message)
	ct.ResetColor()
}

func ( ui * ColorUI ) Info ( message string ) { ct . ChangeColor ( ui . InfoFGColor . Code , ui . InfoFGColor . Bright , ui . InfoBGColor . Code , ui . InfoBGColor . Bright ) ui . UI . Info ( message ) ct . ResetColor ( ) }

// Info calls UI.Info to write.
// Useful when you want separate colors or prefixes.
// InfoFGColor and InfoBGColor are used for color.

Info calls UI . Info to write . Useful when you want separate colors or prefixes . InfoFGColor and InfoBGColor are used for color .


func (ui *ColorUI) Error(message string) {
	ct.ChangeColor(ui.ErrorFGColor.Code, ui.ErrorFGColor.Bright, ui.ErrorBGColor.Code, ui.ErrorBGColor.Bright)
	ui.UI.Error(message)
	ct.ResetColor()
}

func ( ui * ColorUI ) Error ( message string ) { ct . ChangeColor ( ui . ErrorFGColor . Code , ui . ErrorFGColor . Bright , ui . ErrorBGColor . Code , ui . ErrorBGColor . Bright ) ui . UI . Error ( message ) ct . ResetColor ( ) }

// Error calls UI.Error to write.
// ErrorFGColor and ErrorBGColor are used for color.

Error calls UI . Error to write . ErrorFGColor and ErrorBGColor are used for color .


func (ui *ColorUI) Warn(message string) {
	ct.ChangeColor(ui.WarnFGColor.Code, ui.WarnFGColor.Bright, ui.WarnBGColor.Code, ui.WarnBGColor.Bright)
	ui.UI.Warn(message)
	ct.ResetColor()
}

func ( ui * ColorUI ) Warn ( message string ) { ct . ChangeColor ( ui . WarnFGColor . Code , ui . WarnFGColor . Bright , ui . WarnBGColor . Code , ui . WarnBGColor . Bright ) ui . UI . Warn ( message ) ct . ResetColor ( ) }

// Warn calls UI.Warn to write.
// Useful when you want separate colors or prefixes.
// WarnFGColor and WarnBGColor are used for color.

Warn calls UI . Warn to write . Useful when you want separate colors or prefixes . WarnFGColor and WarnBGColor are used for color .


func (ui *ColorUI) Running(message string) {
	ct.ChangeColor(ui.RunningFGColor.Code, ui.RunningFGColor.Bright, ui.RunningBGColor.Code, ui.RunningBGColor.Bright)
	ui.UI.Running(message)
	ct.ResetColor()
}

func ( ui * ColorUI ) Running ( message string ) { ct . ChangeColor ( ui . RunningFGColor . Code , ui . RunningFGColor . Bright , ui . RunningBGColor . Code , ui . RunningBGColor . Bright ) ui . UI . Running ( message ) ct . ResetColor ( ) }

// Running calls UI.Running to write.
// Useful when you want separate colors or prefixes.
// RunningFGColor and RunningBGColor are used for color.

Running calls UI . Running to write . Useful when you want separate colors or prefixes . RunningFGColor and RunningBGColor are used for color .


func (ui *BasicUI) Log(message string) {
	timeString := time.Now().Format(timeFormat)
	message = timeString + ": " + message
	ui.Output(message)
}

func ( ui * BasicUI ) Log ( message string ) { timeString := time . Now ( ) . Format ( timeFormat ) message = timeString + " " + message ui . Output ( message ) }

// Log prefixes to message before writing to Writer.

Log prefixes to message before writing to Writer .


func (ui *BasicUI) Output(message string) {
	fmt.Fprint(ui.Writer, message)
	fmt.Fprint(ui.Writer, "\n")
}

func ( ui * BasicUI ) Output ( message string ) { fmt . Fprint ( ui . Writer , message ) fmt . Fprint ( ui . Writer , " \n " ) }


func (ui *BasicUI) Error(message string) {
	if ui.ErrorWriter != nil {
		fmt.Fprint(ui.ErrorWriter, message)
		fmt.Fprint(ui.ErrorWriter, "\n")
	} else {
		fmt.Fprint(ui.Writer, message)
		fmt.Fprint(ui.Writer, "\n")
	}
}

func ( ui * BasicUI ) Error ( message string ) { if ui . ErrorWriter != nil { fmt . Fprint ( ui . ErrorWriter , message ) fmt . Fprint ( ui . ErrorWriter , " \n " ) } else { fmt . Fprint ( ui . Writer , message ) fmt . Fprint ( ui . Writer , " \n " ) } }


func (ui *PrefixUI) Log(message string) {
	if ui.LogPrefix == " " { //Lets keep the space if they want one
		message = ui.LogPrefix + message
	} else if ui.LogPrefix != "" {
		message = ui.LogPrefix + " " + message
	}
	ui.UI.Log(message)
}

func
(
ui
*
PrefixUI
)
Log
(
message
string
)
{
if
ui
.
LogPrefix
==
"
"
{
//Lets keep the space if they want one
message
=
ui
.
LogPrefix
+
message
}
else
if
ui
.
LogPrefix
!=
"
"
{
message
=
ui
.
LogPrefix
+
"
"
+
message
}
ui
.
UI
.
Log
(
message
)
}

// Log calls UI.Log to write.
// LogPrefix is used to prefix the message.

Log calls UI . Log to write . LogPrefix is used to prefix the message .


func (ui *PrefixUI) Output(message string) {
	if ui.OutputPrefix == " " { //Lets keep the space if they want one
		message = ui.OutputPrefix + message
	} else if ui.OutputPrefix != "" {
		message = ui.OutputPrefix + " " + message
	}
	ui.UI.Output(message)
}

func
(
ui
*
PrefixUI
)
Output
(
message
string
)
{
if
ui
.
OutputPrefix
==
"
"
{
//Lets keep the space if they want one
message
=
ui
.
OutputPrefix
+
message
}
else
if
ui
.
OutputPrefix
!=
"
"
{
message
=
ui
.
OutputPrefix
+
"
"
+
message
}
ui
.
UI
.
Output
(
message
)
}

// Output calls UI.Output to write.
// OutputPrefix is used to prefix the message.

Output calls UI . Output to write . OutputPrefix is used to prefix the message .


func (ui *PrefixUI) Success(message string) {
	if ui.SuccessPrefix == " " { //Lets keep the space if they want one
		message = ui.SuccessPrefix + message
	} else if ui.SuccessPrefix != "" {
		message = ui.SuccessPrefix + " " + message
	}
	ui.UI.Success(message)
}

func
(
ui
*
PrefixUI
)
Success
(
message
string
)
{
if
ui
.
SuccessPrefix
==
"
"
{
//Lets keep the space if they want one
message
=
ui
.
SuccessPrefix
+
message
}
else
if
ui
.
SuccessPrefix
!=
"
"
{
message
=
ui
.
SuccessPrefix
+
"
"
+
message
}
ui
.
UI
.
Success
(
message
)
}

// Success calls UI.Success to write.
// Useful when you want separate colors or prefixes.
// SuccessPrefix is used to prefix the message.

Success calls UI . Success to write . Useful when you want separate colors or prefixes . SuccessPrefix is used to prefix the message .


func (ui *PrefixUI) Info(message string) {
	if ui.InfoPrefix == " " { //Lets keep the space if they want one
		message = ui.InfoPrefix + message
	} else if ui.InfoPrefix != "" {
		message = ui.InfoPrefix + " " + message
	}
	ui.UI.Info(message)
}

func
(
ui
*
PrefixUI
)
Info
(
message
string
)
{
if
ui
.
InfoPrefix
==
"
"
{
//Lets keep the space if they want one
message
=
ui
.
InfoPrefix
+
message
}
else
if
ui
.
InfoPrefix
!=
"
"
{
message
=
ui
.
InfoPrefix
+
"
"
+
message
}
ui
.
UI
.
Info
(
message
)
}

// Info calls UI.Info to write.
// Useful when you want separate colors or prefixes.
// InfoPrefix is used to prefix the message.

Info calls UI . Info to write . Useful when you want separate colors or prefixes . InfoPrefix is used to prefix the message .


func (ui *PrefixUI) Error(message string) {
	if ui.ErrorPrefix == " " { //Lets keep the space if they want one
		message = ui.ErrorPrefix + message
	} else if ui.ErrorPrefix != "" {
		message = ui.ErrorPrefix + " " + message
	}
	ui.UI.Error(message)
}

func
(
ui
*
PrefixUI
)
Error
(
message
string
)
{
if
ui
.
ErrorPrefix
==
"
"
{
//Lets keep the space if they want one
message
=
ui
.
ErrorPrefix
+
message
}
else
if
ui
.
ErrorPrefix
!=
"
"
{
message
=
ui
.
ErrorPrefix
+
"
"
+
message
}
ui
.
UI
.
Error
(
message
)
}

// Error call UI.Error to write.
// ErrorPrefix is used to prefix the message.

Error call UI . Error to write . ErrorPrefix is used to prefix the message .


func (ui *PrefixUI) Warn(message string) {
	if ui.WarnPrefix == " " { //Lets keep the space if they want one
		message = ui.WarnPrefix + message
	} else if ui.WarnPrefix != "" {
		message = ui.WarnPrefix + " " + message
	}
	ui.UI.Warn(message)
}

func
(
ui
*
PrefixUI
)
Warn
(
message
string
)
{
if
ui
.
WarnPrefix
==
"
"
{
//Lets keep the space if they want one
message
=
ui
.
WarnPrefix
+
message
}
else
if
ui
.
WarnPrefix
!=
"
"
{
message
=
ui
.
WarnPrefix
+
"
"
+
message
}
ui
.
UI
.
Warn
(
message
)
}

// Warn calls UI.Warn to write.
// Useful when you want separate colors or prefixes.
// WarnPrefix is used to prefix message.

Warn calls UI . Warn to write . Useful when you want separate colors or prefixes . WarnPrefix is used to prefix message .


func (ui *PrefixUI) Running(message string) {
	if ui.RunningPrefix == " " { //Lets keep the space if they want one
		message = ui.RunningPrefix + message
	} else if ui.RunningPrefix != "" {
		message = ui.RunningPrefix + " " + message
	}
	ui.UI.Running(message)
}

func
(
ui
*
PrefixUI
)
Running
(
message
string
)
{
if
ui
.
RunningPrefix
==
"
"
{
//Lets keep the space if they want one
message
=
ui
.
RunningPrefix
+
message
}
else
if
ui
.
RunningPrefix
!=
"
"
{
message
=
ui
.
RunningPrefix
+
"
"
+
message
}
ui
.
UI
.
Running
(
message
)
}

// Running calls Output to write.
// Useful when you want separate colors or prefixes.
// RunningPrefix is used to prefix message.

Running calls Output to write . Useful when you want separate colors or prefixes . RunningPrefix is used to prefix message .


func New(reader io.Reader, writer, errorWriter io.Writer) *BasicUI {
	return &BasicUI{
		Reader:      reader,
		Writer:      writer,
		ErrorWriter: errorWriter,
	}
}

func New ( reader io . Reader , writer , errorWriter io . Writer ) * BasicUI { return & BasicUI { Reader : reader , Writer : writer , ErrorWriter : errorWriter , } }

//New creates a BasicUI.
//This should be the first function you call.
//This is not thread safe and should only be used in serial applications.

New creates a BasicUI . This should be the first function you call . This is not thread safe and should only be used in serial applications .


func AddColor(askColor, errorColor, infoColor, logColor, outputColor, responseColor, runningColor, successColor, warnColor Color, ui UI) *ColorUI {
	return &ColorUI{
		LogFGColor:      logColor,
		LogBGColor:      None,
		OutputFGColor:   outputColor,
		OutputBGColor:   None,
		SuccessFGColor:  successColor,
		SuccessBGColor:  None,
		InfoFGColor:     infoColor,
		InfoBGColor:     None,
		ErrorFGColor:    errorColor,
		ErrorBGColor:    None,
		WarnFGColor:     warnColor,
		WarnBGColor:     None,
		RunningFGColor:  runningColor,
		RunningBGColor:  None,
		AskFGColor:      askColor,
		AskBGColor:      None,
		ResponseFGColor: responseColor,
		ResponseBGColor: None,
		UI:              ui,
	}
}

func AddColor ( askColor , errorColor , infoColor , logColor , outputColor , responseColor , runningColor , successColor , warnColor Color , ui UI ) * ColorUI { return & ColorUI { LogFGColor : logColor , LogBGColor : None , OutputFGColor : outputColor , OutputBGColor : None , SuccessFGColor : successColor , SuccessBGColor : None , InfoFGColor : infoColor , InfoBGColor : None , ErrorFGColor : errorColor , ErrorBGColor : None , WarnFGColor : warnColor , WarnBGColor : None , RunningFGColor : runningColor , RunningBGColor : None , AskFGColor : askColor , AskBGColor : None , ResponseFGColor : responseColor , ResponseBGColor : None , UI : ui , } }

//AddColor will wrap a colorful UI on top of ui.
//Use wlog's color variables for the color.
//All background colors are not changed by this function but you are able to change them manually.
//Just create this structure manually and change any of the background colors you want.
//Arguments are in alphabetical order.

AddColor will wrap a colorful UI on top of ui . Use wlog s color variables for the color . All background colors are not changed by this function but you are able to change them manually . Just create this structure manually and change any of the background colors you want . Arguments are in alphabetical order .


func (ui *ConcurrentUI) Log(message string) {
	ui.l.Lock()
	defer ui.l.Unlock()
	ui.UI.Log(message)
}

func ( ui * ConcurrentUI ) Log ( message string ) { ui . l . Lock ( ) defer ui . l . Unlock ( ) ui . UI . Log ( message ) }

// Log calls UI.Log to write.
// This is a thread safe function.

Log calls UI . Log to write . This is a thread safe function .


func NewMongoStore(c *mgo.Collection, maxAge int, ensureTTL bool,
	keyPairs ...[]byte) *MongoStore {
	store := &MongoStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: maxAge,
		},
		Token: &CookieToken{},
		coll:  c,
	}

	store.MaxAge(maxAge)

	if ensureTTL {
		c.EnsureIndex(mgo.Index{
			Key:         []string{"modified"},
			Background:  true,
			Sparse:      true,
			ExpireAfter: time.Duration(maxAge) * time.Second,
		})
	}

	return store
}

func NewMongoStore ( c * mgo . Collection , maxAge int , ensureTTL bool , keyPairs ... [ ] byte ) * MongoStore { store := & MongoStore { Codecs : securecookie . CodecsFromPairs ( keyPairs ... ) , Options : & sessions . Options { Path : " " , MaxAge : maxAge , } , Token : & CookieToken { } , coll : c , } store . MaxAge ( maxAge ) if ensureTTL { c . EnsureIndex ( mgo . Index { Key : [ ] string { " " } , Background : true , Sparse : true , ExpireAfter : time . Duration ( maxAge ) * time . Second , } ) } return store }

// NewMongoStore returns a new MongoStore.
// Set ensureTTL to true let the database auto-remove expired object by maxAge.

NewMongoStore returns a new MongoStore . Set ensureTTL to true let the database auto - remove expired object by maxAge .


func (m *MongoStore) New(r *http.Request, name string) (
	*sessions.Session, error) {
	session := sessions.NewSession(m, name)
	session.Options = &sessions.Options{
		Path:     m.Options.Path,
		MaxAge:   m.Options.MaxAge,
		Domain:   m.Options.Domain,
		Secure:   m.Options.Secure,
		HttpOnly: m.Options.HttpOnly,
	}
	session.IsNew = true
	var err error
	if cook, errToken := m.Token.GetToken(r, name); errToken == nil {
		err = securecookie.DecodeMulti(name, cook, &session.ID, m.Codecs...)
		if err == nil {
			err = m.load(session)
			if err == nil {
				session.IsNew = false
			} else {
				err = nil
			}
		}
	}
	return session, err
}

func ( m * MongoStore ) New ( r * http . Request , name string ) ( * sessions . Session , error ) { session := sessions . NewSession ( m , name ) session . Options = & sessions . Options { Path : m . Options . Path , MaxAge : m . Options . MaxAge , Domain : m . Options . Domain , Secure : m . Options . Secure , HttpOnly : m . Options . HttpOnly , } session . IsNew = true var err error if cook , errToken := m . Token . GetToken ( r , name ) ; errToken == nil { err = securecookie . DecodeMulti ( name , cook , & session . ID , m . Codecs ... ) if err == nil { err = m . load ( session ) if err == nil { session . IsNew = false } else { err = nil } } } return session , err }

// New returns a session for the given name without adding it to the registry.

New returns a session for the given name without adding it to the registry .


func (s *SegmentStack) Push(id int64) {
	s.Lock()
	defer s.Unlock()
	s.s = append(s.s, id)
}

func ( s * SegmentStack ) Push ( id int64 ) { s . Lock ( ) defer s . Unlock ( ) s . s = append ( s . s , id ) }

// Push pushes a segment id onto the segment stack.

Push pushes a segment id onto the segment stack .


func (s *SegmentStack) Pop() (int64, bool) {
	s.Lock()
	defer s.Unlock()
	if s.Len() == 0 {
		return rootSegment, false
	}
	id := s.s[s.Len()-1]
	s.s = s.s[:s.Len()-1]
	return id, true
}

func ( s * SegmentStack ) Pop ( ) ( int64 , bool ) { s . Lock ( ) defer s . Unlock ( ) if s . Len ( ) == 0 { return rootSegment , false } id := s . s [ s . Len ( ) - 1 ] s . s = s . s [ : s . Len ( ) - 1 ] return id , true }

// Pop pops a segment id off of the segment stack. It returns false if the stack is empty.

Pop pops a segment id off of the segment stack . It returns false if the stack is empty .


func (s *SegmentStack) Peek() int64 {
	if s.Len() == 0 {
		return rootSegment
	}
	return s.s[s.Len()-1]
}

func ( s * SegmentStack ) Peek ( ) int64 { if s . Len ( ) == 0 { return rootSegment } return s . s [ s . Len ( ) - 1 ] }

// Peek returns id from the top of the stack. It returns rootSegment if the stack is empty.

Peek returns id from the top of the stack . It returns rootSegment if the stack is empty .


func RecordMetricsWithRecorder(r Recorder) {
	ticker := time.NewTicker(r.Interval())
	go func() {
		for _ = range ticker.C {
			r.Record()
		}
	}()
}

func RecordMetricsWithRecorder ( r Recorder ) { ticker := time . NewTicker ( r . Interval ( ) ) go func ( ) { for _ = range ticker . C { r . Record ( ) } } ( ) }

// RecordMetricsWithRecorder records metrics with the given recorder.

RecordMetricsWithRecorder records metrics with the given recorder .


func Init(app, key string) {
	if _, err := sdk.InitEmbeddedMode(key, app); err != nil {
		panic(err)
	}
}

func Init ( app , key string ) { if _ , err := sdk . InitEmbeddedMode ( key , app ) ; err != nil { panic ( err ) } }

// Init initializes the embedded newrelic agent with the given app name and license key.

Init initializes the embedded newrelic agent with the given app name and license key .


func errNo(i C.int) (int, error) {
	errno := int(i)
	if errno < 0 {
		errMsg := "unknown"
		if e, ok := errNoMap[errno]; ok {
			errMsg = e
		}
		return errno, errors.New(fmt.Sprintf("newrelic[%s]: %s", caller(), errMsg))
	}
	return errno, nil
}

func errNo ( i C . int ) ( int , error ) { errno := int ( i ) if errno < 0 { errMsg := " " if e , ok := errNoMap [ errno ] ; ok { errMsg = e } return errno , errors . New ( fmt . Sprintf ( " " , caller ( ) , errMsg ) ) } return errno , nil }

// errNo returns an error if the errno is < 0


func caller() string {
	name := "unknown"
	if pc, _, _, ok := runtime.Caller(1); ok {
		name = filepath.Base(runtime.FuncForPC(pc).Name())
	}
	return name
}

func caller ( ) string { name := " " if pc , _ , _ , ok := runtime . Caller ( 1 ) ; ok { name = filepath . Base ( runtime . FuncForPC ( pc ) . Name ( ) ) } return name }

// caller returns the name of the function that called the function this function was called from.

caller returns the name of the function that called the function this function was called from .


func doInit(license string, appName string, language string, languageVersion string) (int, error) {
	clicense := C.CString(license)
	defer C.free(unsafe.Pointer(clicense))

	cappName := C.CString(appName)
	defer C.free(unsafe.Pointer(cappName))

	clang := C.CString("Go")
	defer C.free(unsafe.Pointer(clang))

	clangVersion := C.CString(runtime.Version())
	defer C.free(unsafe.Pointer(clangVersion))

	errno := C.newrelic_init(clicense, cappName, clang, clangVersion)
	return errNo(errno)
}

func doInit ( license string , appName string , language string , languageVersion string ) ( int , error ) { clicense := C . CString ( license ) defer C . free ( unsafe . Pointer ( clicense ) ) cappName := C . CString ( appName ) defer C . free ( unsafe . Pointer ( cappName ) ) clang := C . CString ( " " ) defer C . free ( unsafe . Pointer ( clang ) ) clangVersion := C . CString ( runtime . Version ( ) ) defer C . free ( unsafe . Pointer ( clangVersion ) ) errno := C . newrelic_init ( clicense , cappName , clang , clangVersion ) return errNo ( errno ) }

/**
 * Start the CollectorClient and the harvester thread that sends application
 * performance data to New Relic once a minute.
 *
 * @param license  New Relic account license key
 * @param app_name  name of instrumented application
 * @param language  name of application programming language
 * @param language_version  application programming language version
 * @return  segment id on success, error code on error, else warning code
 */

Start the CollectorClient and the harvester thread that sends application performance data to New Relic once a minute .


func RequestShutdown(reason string) (int, error) {
	creason := C.CString(reason)
	defer C.free(unsafe.Pointer(creason))
	return errNo(C.newrelic_request_shutdown(creason))
}

func RequestShutdown ( reason string ) ( int , error ) { creason := C . CString ( reason ) defer C . free ( unsafe . Pointer ( creason ) ) return errNo ( C . newrelic_request_shutdown ( creason ) ) }

/**
 * Tell the CollectorClient to shutdown and stop reporting application
 * performance data to New Relic.
 *
 * @reason reason for shutdown request
 * @return  0 on success, error code on error, else warning code
 */

Tell the CollectorClient to shutdown and stop reporting application performance data to New Relic .


func NewTx(name string) *tx {
	return &tx{
		Tracer:   &NRTxTracer{},
		Reporter: &NRTxReporter{},
		name:     name,
		txnType:  WebTransaction,
		ss:       NewSegmentStack(),
		mtx:      &sync.Mutex{},
	}
}

func NewTx ( name string ) * tx { return & tx { Tracer : & NRTxTracer { } , Reporter : & NRTxReporter { } , name : name , txnType : WebTransaction , ss : NewSegmentStack ( ) , mtx : & sync . Mutex { } , } }


func NewRequestTx(name string, url string) *tx {
	t := NewTx(name)
	t.url = url
	return t
}

func NewRequestTx ( name string , url string ) * tx { t := NewTx ( name ) t . url = url return t }

// NewRequestTx returns a new transaction with a request url.

NewRequestTx returns a new transaction with a request url .


func NewBackgroundTx(name string, category string) *tx {
	t := NewTx(name)
	t.txnType = OtherTransaction
	t.category = category
	return t
}

func NewBackgroundTx ( name string , category string ) * tx { t := NewTx ( name ) t . txnType = OtherTransaction t . category = category return t }

// NewBackgroundTx returns a new background transaction


func (t *tx) Start() (err error) {
	if t.id != 0 {
		return ErrTxAlreadyStarted
	}
	if t.id, err = t.Tracer.BeginTransaction(); err != nil {
		return err
	}
	if err = t.Tracer.SetTransactionName(t.id, t.name); err != nil {
		return err
	}
	if err = t.Tracer.SetTransactionType(t.id, t.txnType); err != nil {
		return err
	}
	if t.url != "" {
		if err = t.Tracer.SetTransactionRequestURL(t.id, t.url); err != nil {

			return err
		}
	}
	if t.category != "" {
		if err = t.Tracer.SetTransactionCategory(t.id, t.category); err != nil {
			return err
		}
	}

	return nil
}

func ( t * tx ) Start ( ) ( err error ) { if t . id != 0 { return ErrTxAlreadyStarted } if t . id , err = t . Tracer . BeginTransaction ( ) ; err != nil { return err } if err = t . Tracer . SetTransactionName ( t . id , t . name ) ; err != nil { return err } if err = t . Tracer . SetTransactionType ( t . id , t . txnType ) ; err != nil { return err } if t . url != " " { if err = t . Tracer . SetTransactionRequestURL ( t . id , t . url ) ; err != nil { return err } } if t . category != " " { if err = t . Tracer . SetTransactionCategory ( t . id , t . category ) ; err != nil { return err } } return nil }

// Start starts a transaction, setting the id.

Start starts a transaction setting the id .


func (t *tx) End() error {
	t.mtx.Lock()
	defer t.mtx.Unlock()

	for t.ss.Peek() != rootSegment {
		t.EndSegment() // discarding errors?
	}
	return t.Tracer.EndTransaction(t.id)
}

func
(
t
*
tx
)
End
(
)
error
{
t
.
mtx
.
Lock
(
)
defer
t
.
mtx
.
Unlock
(
)
for
t
.
ss
.
Peek
(
)
!=
rootSegment
{
t
.
EndSegment
(
)
// discarding errors?
}
return
t
.
Tracer
.
EndTransaction
(
t
.
id
)
}


func (t *tx) StartGeneric(name string) error {
	t.mtx.Lock()
	defer t.mtx.Unlock()

	id, err := t.Tracer.BeginGenericSegment(t.id, t.ss.Peek(), name)
	if err != nil {
		return err
	}
	t.ss.Push(id)
	return nil
}

func ( t * tx ) StartGeneric ( name string ) error { t . mtx . Lock ( ) defer t . mtx . Unlock ( ) id , err := t . Tracer . BeginGenericSegment ( t . id , t . ss . Peek ( ) , name ) if err != nil { return err } t . ss . Push ( id ) return nil }

// StartGeneric starts a generic segment.


func (t *tx) StartDatastore(table, operation, sql, rollupName string) error {
	t.mtx.Lock()
	defer t.mtx.Unlock()

	id, err := t.Tracer.BeginDatastoreSegment(t.id, t.ss.Peek(), table, operation, sql, rollupName)
	if err != nil {
		return err
	}
	t.ss.Push(id)
	return nil
}

func ( t * tx ) StartDatastore ( table , operation , sql , rollupName string ) error { t . mtx . Lock ( ) defer t . mtx . Unlock ( ) id , err := t . Tracer . BeginDatastoreSegment ( t . id , t . ss . Peek ( ) , table , operation , sql , rollupName ) if err != nil { return err } t . ss . Push ( id ) return nil }

// StartDatastore starts a datastore segment.

StartDatastore starts a datastore segment .


func (t *tx) StartExternal(host, name string) error {
	t.mtx.Lock()
	defer t.mtx.Unlock()

	id, err := t.Tracer.BeginExternalSegment(t.id, t.ss.Peek(), host, name)
	if err != nil {
		return err
	}
	t.ss.Push(id)
	return nil
}

func ( t * tx ) StartExternal ( host , name string ) error { t . mtx . Lock ( ) defer t . mtx . Unlock ( ) id , err := t . Tracer . BeginExternalSegment ( t . id , t . ss . Peek ( ) , host , name ) if err != nil { return err } t . ss . Push ( id ) return nil }

// StartExternal starts an external segment.

StartExternal starts an external segment .


func (t *tx) EndSegment() error {
	t.mtx.Lock()
	defer t.mtx.Unlock()

	if id, ok := t.ss.Pop(); ok {
		return t.Tracer.EndSegment(t.id, id)
	}
	return nil
}

func ( t * tx ) EndSegment ( ) error { t . mtx . Lock ( ) defer t . mtx . Unlock ( ) if id , ok := t . ss . Pop ( ) ; ok { return t . Tracer . EndSegment ( t . id , id ) } return nil }

// EndSegment ends the segment at the top of the stack.

EndSegment ends the segment at the top of the stack .


func (t *tx) ReportError(exceptionType, errorMessage, stackTrace, stackFrameDelim string) error {
	t.mtx.Lock()
	defer t.mtx.Unlock()

	_, err := t.Reporter.ReportError(t.id, exceptionType, errorMessage, stackTrace, stackFrameDelim)
	return err
}

func ( t * tx ) ReportError ( exceptionType , errorMessage , stackTrace , stackFrameDelim string ) error { t . mtx . Lock ( ) defer t . mtx . Unlock ( ) _ , err := t . Reporter . ReportError ( t . id , exceptionType , errorMessage , stackTrace , stackFrameDelim ) return err }

// ReportError reports an error that occured during the transaction.

ReportError reports an error that occured during the transaction .


func WithTx(ctx context.Context, t Tx) context.Context {
	return context.WithValue(ctx, txKey, t)
}

func WithTx ( ctx context . Context , t Tx ) context . Context { return context . WithValue ( ctx , txKey , t ) }

// WithTx inserts a newrelic.Tx into the provided context.

WithTx inserts a newrelic . Tx into the provided context .


func FromContext(ctx context.Context) (Tx, bool) {
	t, ok := ctx.Value(txKey).(Tx)
	return t, ok
}

func FromContext ( ctx context . Context ) ( Tx , bool ) { t , ok := ctx . Value ( txKey ) . ( Tx ) return t , ok }

// FromContext returns a newrelic.Tx from the context.

FromContext returns a newrelic . Tx from the context .


func TraceExternal(ctx context.Context, host, name string) *Trace {
	return trace(ctx, name, func(tx Tx) error {
		return tx.StartExternal(host, name)
	})
}

func TraceExternal ( ctx context . Context , host , name string ) * Trace { return trace ( ctx , name , func ( tx Tx ) error { return tx . StartExternal ( host , name ) } ) }

// TraceExternal adds an external segment to the newrelic transaction, if one exists in the context.

TraceExternal adds an external segment to the newrelic transaction if one exists in the context .


func TraceGeneric(ctx context.Context, name string) *Trace {
	return trace(ctx, name, func(tx Tx) error {
		return tx.StartGeneric(name)
	})
}

func TraceGeneric ( ctx context . Context , name string ) * Trace { return trace ( ctx , name , func ( tx Tx ) error { return tx . StartGeneric ( name ) } ) }

// TraceGeneric adds a generic segment to the newrelic transaction, if one exists in the context.

TraceGeneric adds a generic segment to the newrelic transaction if one exists in the context .


func TraceDatastore(ctx context.Context, table, operation, sql, rollupName string) *Trace {
	return trace(ctx, rollupName, func(tx Tx) error {
		return tx.StartDatastore(table, operation, sql, rollupName)
	})
}

func TraceDatastore ( ctx context . Context , table , operation , sql , rollupName string ) * Trace { return trace ( ctx , rollupName , func ( tx Tx ) error { return tx . StartDatastore ( table , operation , sql , rollupName ) } ) }

// TraceDatastore adds a datastore segment to the newrelic transaction, if one exists in the context.

TraceDatastore adds a datastore segment to the newrelic transaction if one exists in the context .


func trace(ctx context.Context, name string, fn func(Tx) error) *Trace {
	if tx, ok := FromContext(ctx); ok {
		err := fn(tx)
		return &Trace{
			err: err,
			done: func() error {
				return tx.EndSegment()
			},
		}
	}
	return &Trace{nil, func() error { return nil }}
}

func trace ( ctx context . Context , name string , fn func ( Tx ) error ) * Trace { if tx , ok := FromContext ( ctx ) ; ok { err := fn ( tx ) return & Trace { err : err , done : func ( ) error { return tx . EndSegment ( ) } , } } return & Trace { nil , func ( ) error { return nil } } }

// trace is a helper function for TraceExternal and TraceGeneric, you probably don't want
// to use it directly.

trace is a helper function for TraceExternal and TraceGeneric you probably don t want to use it directly .


func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
	fileserver := http.FileServer(fs)
	if urlPrefix != "" {
		fileserver = http.StripPrefix(urlPrefix, fileserver)
	}
	return func(c *gin.Context) {
		if fs.Exists(urlPrefix, c.Request.URL.Path) {
			fileserver.ServeHTTP(c.Writer, c.Request)
			c.Abort()
		}
	}
}

func Serve ( urlPrefix string , fs ServeFileSystem ) gin . HandlerFunc { fileserver := http . FileServer ( fs ) if urlPrefix != " " { fileserver = http . StripPrefix ( urlPrefix , fileserver ) } return func ( c * gin . Context ) { if fs . Exists ( urlPrefix , c . Request . URL . Path ) { fileserver . ServeHTTP ( c . Writer , c . Request ) c . Abort ( ) } } }

// Static returns a middleware handler that serves static files in the given directory.

Static returns a middleware handler that serves static files in the given directory .


func (c *LRU) Purge() {
	for k := range c.items {
		delete(c.items, k)
	}
	c.evictList.Init()
}

func ( c * LRU ) Purge ( ) { for k := range c . items { delete ( c . items , k ) } c . evictList . Init ( ) }

// Purge is used to completely clear the cache.

Purge is used to completely clear the cache .


func (c *LRU) RemoveOldest() (key string, value uint64, ok bool) {
	ent := c.evictList.Back()
	if ent != nil {
		c.removeElement(ent)
		kv := ent.Value.(*entry)
		return kv.key, kv.value, true
	}
	return "", 0, false
}

func ( c * LRU ) RemoveOldest ( ) ( key string , value uint64 , ok bool ) { ent := c . evictList . Back ( ) if ent != nil { c . removeElement ( ent ) kv := ent . Value . ( * entry ) return kv . key , kv . value , true } return " " , 0 , false }

// RemoveOldest removes the oldest item from the cache.

RemoveOldest removes the oldest item from the cache .


func (c *LRU) Keys() []string {
	keys := make([]string, len(c.items))
	i := 0
	for ent := c.evictList.Back(); ent != nil; ent = ent.Prev() {
		keys[i] = ent.Value.(*entry).key
		i++
	}
	return keys
}

func ( c * LRU ) Keys ( ) [ ] string { keys := make ( [ ] string , len ( c . items ) ) i := 0 for ent := c . evictList . Back ( ) ; ent != nil ; ent = ent . Prev ( ) { keys [ i ] = ent . Value . ( * entry ) . key i ++ } return keys }

// Keys returns a slice of the keys in the cache, from oldest to newest.

Keys returns a slice of the keys in the cache from oldest to newest .


func (c *LRU) removeElement(e *list.Element) {
	c.evictList.Remove(e)
	kv := e.Value.(*entry)
	delete(c.items, kv.key)
}

func ( c * LRU ) removeElement ( e * list . Element ) { c . evictList . Remove ( e ) kv := e . Value . ( * entry ) delete ( c . items , kv . key ) }

// removeElement is used to remove a given list element from the cache


func DefaultCluster() *Cluster {
	return &Cluster{
		hosts:  make([]*URI, 0),
		okList: make([]bool, 0),
		mutex:  &sync.RWMutex{},
	}
}

func DefaultCluster ( ) * Cluster { return & Cluster { hosts : make ( [ ] * URI , 0 ) , okList : make ( [ ] bool , 0 ) , mutex : & sync . RWMutex { } , } }

// DefaultCluster returns the default Cluster.

DefaultCluster returns the default Cluster .


func NewClusterWithHost(hosts ...*URI) *Cluster {
	cluster := DefaultCluster()
	for _, host := range hosts {
		cluster.AddHost(host)
	}
	return cluster
}

func NewClusterWithHost ( hosts ... * URI ) * Cluster { cluster := DefaultCluster ( ) for _ , host := range hosts { cluster . AddHost ( host ) } return cluster }

// NewClusterWithHost returns a cluster with the given URIs.

NewClusterWithHost returns a cluster with the given URIs .


func (c *Cluster) AddHost(address *URI) {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	c.hosts = append(c.hosts, address)
	c.okList = append(c.okList, true)
}

func ( c * Cluster ) AddHost ( address * URI ) { c . mutex . Lock ( ) defer c . mutex . Unlock ( ) c . hosts = append ( c . hosts , address ) c . okList = append ( c . okList , true ) }


func (c *Cluster) Host() *URI {
	c.mutex.Lock()
	var host *URI
	for i := range c.okList {
		idx := (i + c.lastHostIdx) % len(c.okList)
		ok := c.okList[idx]
		if ok {
			host = c.hosts[idx]
			break
		}
	}
	c.lastHostIdx++
	c.mutex.Unlock()
	if host != nil {
		return host
	}
	c.reset()
	return host
}

func ( c * Cluster ) Host ( ) * URI { c . mutex . Lock ( ) var host * URI for i := range c . okList { idx := ( i + c . lastHostIdx ) % len ( c . okList ) ok := c . okList [ idx ] if ok { host = c . hosts [ idx ] break } } c . lastHostIdx ++ c . mutex . Unlock ( ) if host != nil { return host } c . reset ( ) return host }


func (c *Cluster) RemoveHost(address *URI) {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	for i, uri := range c.hosts {
		if uri.Equals(address) {
			c.okList[i] = false
			break
		}
	}
}

func ( c * Cluster ) RemoveHost ( address * URI ) { c . mutex . Lock ( ) defer c . mutex . Unlock ( ) for i , uri := range c . hosts { if uri . Equals ( address ) { c . okList [ i ] = false break } } }

// RemoveHost black lists the host with the given URI from the cluster.

RemoveHost black lists the host with the given URI from the cluster .


func (c *Cluster) Hosts() []URI {
	hosts := make([]URI, 0, len(c.hosts))
	for i, host := range c.hosts {
		if c.okList[i] {
			hosts = append(hosts, *host)
		}
	}
	return hosts
}

func ( c * Cluster ) Hosts ( ) [ ] URI { hosts := make ( [ ] URI , 0 , len ( c . hosts ) ) for i , host := range c . hosts { if c . okList [ i ] { hosts = append ( hosts , * host ) } } return hosts }

// Hosts returns all available hosts in the cluster.

Hosts returns all available hosts in the cluster .


func (b Column) Less(other Record) bool {
	if ob, ok := other.(Column); ok {
		if b.RowID == ob.RowID {
			return b.ColumnID < ob.ColumnID
		}
		return b.RowID < ob.RowID
	}
	return false
}

func ( b Column ) Less ( other Record ) bool { if ob , ok := other . ( Column ) ; ok { if b . RowID == ob . RowID { return b . ColumnID < ob . ColumnID } return b . RowID < ob . RowID } return false }

// Less returns true if this column sorts before the given Record.

Less returns true if this column sorts before the given Record .


func (v FieldValue) Less(other Record) bool {
	if ov, ok := other.(FieldValue); ok {
		return v.ColumnID < ov.ColumnID
	}
	return false
}

func ( v FieldValue ) Less ( other Record ) bool { if ov , ok := other . ( FieldValue ) ; ok { return v . ColumnID < ov . ColumnID } return false }

// Less returns true if this field value sorts before the given Record.

Less returns true if this field value sorts before the given Record .


func (s *Schema) Index(name string, options ...IndexOption) *Index {
	if index, ok := s.indexes[name]; ok {
		return index
	}
	indexOptions := &IndexOptions{}
	indexOptions.addOptions(options...)
	return s.indexWithOptions(name, 0, indexOptions)
}

func ( s * Schema ) Index ( name string , options ... IndexOption ) * Index { if index , ok := s . indexes [ name ] ; ok { return index } indexOptions := & IndexOptions { } indexOptions . addOptions ( options ... ) return s . indexWithOptions ( name , 0 , indexOptions ) }


func (s *Schema) Indexes() map[string]*Index {
	result := make(map[string]*Index)
	for k, v := range s.indexes {
		result[k] = v.copy()
	}
	return result
}

func ( s * Schema ) Indexes ( ) map [ string ] * Index { result := make ( map [ string ] * Index ) for k , v := range s . indexes { result [ k ] = v . copy ( ) } return result }

// Indexes return a copy of the indexes in this schema


func (s *Schema) HasIndex(indexName string) bool {
	_, ok := s.indexes[indexName]
	return ok
}

func ( s * Schema ) HasIndex ( indexName string ) bool { _ , ok := s . indexes [ indexName ] return ok }

// HasIndex returns true if the given index is in the schema.

HasIndex returns true if the given index is in the schema .


func NewPQLBaseQuery(pql string, index *Index, err error) *PQLBaseQuery {
	return &PQLBaseQuery{
		index:   index,
		pql:     pql,
		err:     err,
		hasKeys: index.options.keys,
	}
}

func NewPQLBaseQuery ( pql string , index * Index , err error ) * PQLBaseQuery { return & PQLBaseQuery { index : index , pql : pql , err : err , hasKeys : index . options . keys , } }

// NewPQLBaseQuery creates a new PQLQuery with the given PQL and index.

NewPQLBaseQuery creates a new PQLQuery with the given PQL and index .


func (q *PQLBatchQuery) Add(query PQLQuery) {
	err := query.Error()
	if err != nil {
		q.err = err
	}
	serializedQuery := query.Serialize()
	q.hasKeys = q.hasKeys || serializedQuery.HasWriteKeys()
	q.queries = append(q.queries, serializedQuery.String())
}

func ( q * PQLBatchQuery ) Add ( query PQLQuery ) { err := query . Error ( ) if err != nil { q . err = err } serializedQuery := query . Serialize ( ) q . hasKeys = q . hasKeys || serializedQuery . HasWriteKeys ( ) q . queries = append ( q . queries , serializedQuery . String ( ) ) }


func NewPQLRowQuery(pql string, index *Index, err error) *PQLRowQuery {
	return &PQLRowQuery{
		index:   index,
		pql:     pql,
		err:     err,
		hasKeys: index.options.keys,
	}
}

func NewPQLRowQuery ( pql string , index * Index , err error ) * PQLRowQuery { return & PQLRowQuery { index : index , pql : pql , err : err , hasKeys : index . options . keys , } }

// NewPQLRowQuery creates a new PqlRowQuery.

NewPQLRowQuery creates a new PqlRowQuery .


func (io IndexOptions) String() string {
	mopt := map[string]interface{}{}
	if io.keysSet {
		mopt["keys"] = io.keys
	}
	if io.trackExistenceSet {
		mopt["trackExistence"] = io.trackExistence
	}
	return fmt.Sprintf(`{"options":%s}`, encodeMap(mopt))
}

func ( io IndexOptions ) String ( ) string { mopt := map [ string ] interface { } { } if io . keysSet { mopt [ " " ] = io . keys } if io . trackExistenceSet { mopt [ " " ] = io . trackExistence } return fmt . Sprintf ( `{"options":%s}` , encodeMap ( mopt ) ) }

// String serializes this index to a JSON string.

String serializes this index to a JSON string .


func OptIndexKeys(keys bool) IndexOption {
	return func(options *IndexOptions) {
		options.keys = keys
		options.keysSet = true
	}
}

func OptIndexKeys ( keys bool ) IndexOption { return func ( options * IndexOptions ) { options . keys = keys options . keysSet = true } }

// OptIndexKeys sets whether index uses string keys.

OptIndexKeys sets whether index uses string keys .


func OptIndexTrackExistence(trackExistence bool) IndexOption {
	return func(options *IndexOptions) {
		options.trackExistence = trackExistence
		options.trackExistenceSet = true
	}
}

func OptIndexTrackExistence ( trackExistence bool ) IndexOption { return func ( options * IndexOptions ) { options . trackExistence = trackExistence options . trackExistenceSet = true } }

// OptIndexTrackExistence enables keeping track of existence of columns.

OptIndexTrackExistence enables keeping track of existence of columns .


func NewIndex(name string) *Index {
	options := &IndexOptions{}
	return &Index{
		name:    name,
		options: options.withDefaults(),
		fields:  map[string]*Field{},
	}
}

func NewIndex ( name string ) * Index { options := & IndexOptions { } return & Index { name : name , options : options . withDefaults ( ) , fields : map [ string ] * Field { } , } }

// NewIndex creates an index with a name.


func (idx *Index) Fields() map[string]*Field {
	result := make(map[string]*Field)
	for k, v := range idx.fields {
		result[k] = v.copy()
	}
	return result
}

func ( idx * Index ) Fields ( ) map [ string ] * Field { result := make ( map [ string ] * Field ) for k , v := range idx . fields { result [ k ] = v . copy ( ) } return result }

// Fields return a copy of the fields in this index


func (idx *Index) HasField(fieldName string) bool {
	_, ok := idx.fields[fieldName]
	return ok
}

func ( idx * Index ) HasField ( fieldName string ) bool { _ , ok := idx . fields [ fieldName ] return ok }

// HasFields returns true if the given field exists in the index.

HasFields returns true if the given field exists in the index .


func (idx *Index) Field(name string, options ...FieldOption) *Field {
	if field, ok := idx.fields[name]; ok {
		return field
	}
	fieldOptions := &FieldOptions{}
	fieldOptions = fieldOptions.withDefaults()
	fieldOptions.addOptions(options...)
	return idx.fieldWithOptions(name, fieldOptions)
}

func ( idx * Index ) Field ( name string , options ... FieldOption ) * Field { if field , ok := idx . fields [ name ] ; ok { return field } fieldOptions := & FieldOptions { } fieldOptions = fieldOptions . withDefaults ( ) fieldOptions . addOptions ( options ... ) return idx . fieldWithOptions ( name , fieldOptions ) }

// Field creates a Field struct with the specified name and defaults.

Field creates a Field struct with the specified name and defaults .


func (idx *Index) BatchQuery(queries ...PQLQuery) *PQLBatchQuery {
	stringQueries := make([]string, 0, len(queries))
	hasKeys := false
	for _, query := range queries {
		serializedQuery := query.Serialize()
		hasKeys = hasKeys || serializedQuery.HasWriteKeys()
		stringQueries = append(stringQueries, serializedQuery.String())
	}
	return &PQLBatchQuery{
		index:   idx,
		queries: stringQueries,
		hasKeys: hasKeys,
	}
}

func ( idx * Index ) BatchQuery ( queries ... PQLQuery ) * PQLBatchQuery { stringQueries := make ( [ ] string , 0 , len ( queries ) ) hasKeys := false for _ , query := range queries { serializedQuery := query . Serialize ( ) hasKeys = hasKeys || serializedQuery . HasWriteKeys ( ) stringQueries = append ( stringQueries , serializedQuery . String ( ) ) } return & PQLBatchQuery { index : idx , queries : stringQueries , hasKeys : hasKeys , } }

// BatchQuery creates a batch query with the given queries.

BatchQuery creates a batch query with the given queries .


func (idx *Index) RawQuery(query string) *PQLBaseQuery {
	q := NewPQLBaseQuery(query, idx, nil)
	// NOTE: raw queries always assumed to have keys set
	q.hasKeys = true
	return q
}

// RawQuery creates a query with the given string.
// Note that the query is not validated before sending to the server.

RawQuery creates a query with the given string . Note that the query is not validated before sending to the server .


func (idx *Index) Intersect(rows ...*PQLRowQuery) *PQLRowQuery {
	if len(rows) < 1 {
		return NewPQLRowQuery("", idx, NewError("Intersect operation requires at least 1 row"))
	}
	return idx.rowOperation("Intersect", rows...)
}

func ( idx * Index ) Intersect ( rows ... * PQLRowQuery ) * PQLRowQuery { if len ( rows ) < 1 { return NewPQLRowQuery ( " " , idx , NewError ( " " ) ) } return idx . rowOperation ( " " , rows ... ) }

// Intersect creates an Intersect query.
// Intersect performs a logical AND on the results of each ROW_CALL query passed to it.

Intersect creates an Intersect query . Intersect performs a logical AND on the results of each ROW_CALL query passed to it .


func (idx *Index) Not(row *PQLRowQuery) *PQLRowQuery {
	return NewPQLRowQuery(fmt.Sprintf("Not(%s)", row.serialize()), idx, row.Error())
}

func ( idx * Index ) Not ( row * PQLRowQuery ) * PQLRowQuery { return NewPQLRowQuery ( fmt . Sprintf ( " " , row . serialize ( ) ) , idx , row . Error ( ) ) }


func (idx *Index) Count(row *PQLRowQuery) *PQLBaseQuery {
	serializedQuery := row.serialize()
	q := NewPQLBaseQuery(fmt.Sprintf("Count(%s)", serializedQuery.String()), idx, nil)
	q.hasKeys = q.hasKeys || serializedQuery.HasWriteKeys()
	return q
}

func ( idx * Index ) Count ( row * PQLRowQuery ) * PQLBaseQuery { serializedQuery := row . serialize ( ) q := NewPQLBaseQuery ( fmt . Sprintf ( " " , serializedQuery . String ( ) ) , idx , nil ) q . hasKeys = q . hasKeys || serializedQuery . HasWriteKeys ( ) return q }

// Count creates a Count query.
// Returns the number of set columns in the ROW_CALL passed in.

Count creates a Count query . Returns the number of set columns in the ROW_CALL passed in .


func (idx *Index) Options(row *PQLRowQuery, opts ...OptionsOption) *PQLBaseQuery {
	oo := &OptionsOptions{}
	for _, opt := range opts {
		opt(oo)
	}
	text := fmt.Sprintf("Options(%s,%s)", row.serialize(), oo.marshal())
	return NewPQLBaseQuery(text, idx, nil)
}

func ( idx * Index ) Options ( row * PQLRowQuery , opts ... OptionsOption ) * PQLBaseQuery { oo := & OptionsOptions { } for _ , opt := range opts { opt ( oo ) } text := fmt . Sprintf ( " " , row . serialize ( ) , oo . marshal ( ) ) return NewPQLBaseQuery ( text , idx , nil ) }


func (idx *Index) GroupBy(rowsQueries ...*PQLRowsQuery) *PQLBaseQuery {
	if len(rowsQueries) < 1 {
		return NewPQLBaseQuery("", idx, errors.New("there should be at least one rows query"))
	}
	text := fmt.Sprintf("GroupBy(%s)", strings.Join(serializeGroupBy(rowsQueries...), ","))
	return NewPQLBaseQuery(text, idx, nil)
}

func ( idx * Index ) GroupBy ( rowsQueries ... * PQLRowsQuery ) * PQLBaseQuery { if len ( rowsQueries ) < 1 { return NewPQLBaseQuery ( " " , idx , errors . New ( " " ) ) } text := fmt . Sprintf ( " " , strings . Join ( serializeGroupBy ( rowsQueries ... ) , " " ) ) return NewPQLBaseQuery ( text , idx , nil ) }

// GroupBy creates a GroupBy query with the given Rows queries


func (idx *Index) GroupByLimit(limit int64, rowsQueries ...*PQLRowsQuery) *PQLBaseQuery {
	if len(rowsQueries) < 1 {
		return NewPQLBaseQuery("", idx, errors.New("there should be at least one rows query"))
	}
	if limit < 0 {
		return NewPQLBaseQuery("", idx, errors.New("limit must be non-negative"))
	}
	text := fmt.Sprintf("GroupBy(%s,limit=%d)", strings.Join(serializeGroupBy(rowsQueries...), ","), limit)
	return NewPQLBaseQuery(text, idx, nil)
}

func ( idx * Index ) GroupByLimit ( limit int64 , rowsQueries ... * PQLRowsQuery ) * PQLBaseQuery { if len ( rowsQueries ) < 1 { return NewPQLBaseQuery ( " " , idx , errors . New ( " " ) ) } if limit < 0 { return NewPQLBaseQuery ( " " , idx , errors . New ( " " ) ) } text := fmt . Sprintf ( " " , strings . Join ( serializeGroupBy ( rowsQueries ... ) , " " ) , limit ) return NewPQLBaseQuery ( text , idx , nil ) }

// GroupByLimit creates a GroupBy query with the given limit and Rows queries


func (idx *Index) GroupByFilter(filterQuery *PQLRowQuery, rowsQueries ...*PQLRowsQuery) *PQLBaseQuery {
	if len(rowsQueries) < 1 {
		return NewPQLBaseQuery("", idx, errors.New("there should be at least one rows query"))
	}
	filterText := filterQuery.serialize().String()
	text := fmt.Sprintf("GroupBy(%s,filter=%s)", strings.Join(serializeGroupBy(rowsQueries...), ","), filterText)
	return NewPQLBaseQuery(text, idx, nil)
}

func ( idx * Index ) GroupByFilter ( filterQuery * PQLRowQuery , rowsQueries ... * PQLRowsQuery ) * PQLBaseQuery { if len ( rowsQueries ) < 1 { return NewPQLBaseQuery ( " " , idx , errors . New ( " " ) ) } filterText := filterQuery . serialize ( ) . String ( ) text := fmt . Sprintf ( " " , strings . Join ( serializeGroupBy ( rowsQueries ... ) , " " ) , filterText ) return NewPQLBaseQuery ( text , idx , nil ) }

// GroupByFilter creates a GroupBy query with the given filter and Rows queries


func OptFieldTypeSet(cacheType CacheType, cacheSize int) FieldOption {
	return func(options *FieldOptions) {
		options.fieldType = FieldTypeSet
		options.cacheType = cacheType
		options.cacheSize = cacheSize
	}
}

func OptFieldTypeSet ( cacheType CacheType , cacheSize int ) FieldOption { return func ( options * FieldOptions ) { options . fieldType = FieldTypeSet options . cacheType = cacheType options . cacheSize = cacheSize } }

// OptFieldTypeSet adds a set field.
// Specify CacheTypeDefault for the default cache type.
// Specify CacheSizeDefault for the default cache size.

OptFieldTypeSet adds a set field . Specify CacheTypeDefault for the default cache type . Specify CacheSizeDefault for the default cache size .


func OptFieldTypeInt(min int64, max int64) FieldOption {
	return func(options *FieldOptions) {
		options.fieldType = FieldTypeInt
		options.min = min
		options.max = max
	}
}

func OptFieldTypeInt ( min int64 , max int64 ) FieldOption { return func ( options * FieldOptions ) { options . fieldType = FieldTypeInt options . min = min options . max = max } }

// OptFieldTypeInt adds an integer field.


func OptFieldTypeTime(quantum TimeQuantum, opts ...bool) FieldOption {
	return func(options *FieldOptions) {
		options.fieldType = FieldTypeTime
		options.timeQuantum = quantum
		if len(opts) > 0 && opts[0] {
			options.noStandardView = true
		}
	}
}

func OptFieldTypeTime ( quantum TimeQuantum , opts ... bool ) FieldOption { return func ( options * FieldOptions ) { options . fieldType = FieldTypeTime options . timeQuantum = quantum if len ( opts ) > 0 && opts [ 0 ] { options . noStandardView = true } } }


func OptFieldTypeMutex(cacheType CacheType, cacheSize int) FieldOption {
	return func(options *FieldOptions) {
		options.fieldType = FieldTypeMutex
		options.cacheType = cacheType
		options.cacheSize = cacheSize
	}
}

func OptFieldTypeMutex ( cacheType CacheType , cacheSize int ) FieldOption { return func ( options * FieldOptions ) { options . fieldType = FieldTypeMutex options . cacheType = cacheType options . cacheSize = cacheSize } }

// OptFieldTypeMutex adds a mutex field.


func (f *Field) Row(rowIDOrKey interface{}) *PQLRowQuery {
	rowStr, err := formatIDKeyBool(rowIDOrKey)
	if err != nil {
		return NewPQLRowQuery("", f.index, err)
	}
	text := fmt.Sprintf("Row(%s=%s)", f.name, rowStr)
	q := NewPQLRowQuery(text, f.index, nil)
	return q
}

func ( f * Field ) Row ( rowIDOrKey interface { } ) * PQLRowQuery { rowStr , err := formatIDKeyBool ( rowIDOrKey ) if err != nil { return NewPQLRowQuery ( " " , f . index , err ) } text := fmt . Sprintf ( " " , f . name , rowStr ) q := NewPQLRowQuery ( text , f . index , nil ) return q }

// Row creates a Row query.
// Row retrieves the indices of all the set columns in a row.
// It also retrieves any attributes set on that row or column.

Row creates a Row query . Row retrieves the indices of all the set columns in a row . It also retrieves any attributes set on that row or column .


func (f *Field) Set(rowIDOrKey, colIDOrKey interface{}) *PQLBaseQuery {
	rowStr, colStr, err := formatRowColIDKey(rowIDOrKey, colIDOrKey)
	if err != nil {
		return NewPQLBaseQuery("", f.index, err)
	}
	text := fmt.Sprintf("Set(%s,%s=%s)", colStr, f.name, rowStr)
	q := NewPQLBaseQuery(text, f.index, nil)
	q.hasKeys = f.options.keys || f.index.options.keys
	return q
}

func ( f * Field ) Set ( rowIDOrKey , colIDOrKey interface { } ) * PQLBaseQuery { rowStr , colStr , err := formatRowColIDKey ( rowIDOrKey , colIDOrKey ) if err != nil { return NewPQLBaseQuery ( " " , f . index , err ) } text := fmt . Sprintf ( " " , colStr , f . name , rowStr ) q := NewPQLBaseQuery ( text , f . index , nil ) q . hasKeys = f . options . keys || f . index . options . keys return q }

// Set creates a Set query.
// Set, assigns a value of 1 to a bit in the binary matrix, thus associating the given row in the given field with the given column.

Set creates a Set query . Set assigns a value of 1 to a bit in the binary matrix thus associating the given row in the given field with the given column .


func (f *Field) SetTimestamp(rowIDOrKey, colIDOrKey interface{}, timestamp time.Time) *PQLBaseQuery {
	rowStr, colStr, err := formatRowColIDKey(rowIDOrKey, colIDOrKey)
	if err != nil {
		return NewPQLBaseQuery("", f.index, err)
	}
	text := fmt.Sprintf("Set(%s,%s=%s,%s)", colStr, f.name, rowStr, timestamp.Format(timeFormat))
	q := NewPQLBaseQuery(text, f.index, nil)
	q.hasKeys = f.options.keys || f.index.options.keys
	return q
}

func ( f * Field ) SetTimestamp ( rowIDOrKey , colIDOrKey interface { } , timestamp time . Time ) * PQLBaseQuery { rowStr , colStr , err := formatRowColIDKey ( rowIDOrKey , colIDOrKey ) if err != nil { return NewPQLBaseQuery ( " " , f . index , err ) } text := fmt . Sprintf ( " " , colStr , f . name , rowStr , timestamp . Format ( timeFormat ) ) q := NewPQLBaseQuery ( text , f . index , nil ) q . hasKeys = f . options . keys || f . index . options . keys return q }

// SetTimestamp creates a Set query with timestamp.
// Set, assigns a value of 1 to a column in the binary matrix,
// thus associating the given row in the given field with the given column.

SetTimestamp creates a Set query with timestamp . Set assigns a value of 1 to a column in the binary matrix thus associating the given row in the given field with the given column .


func (f *Field) ClearRow(rowIDOrKey interface{}) *PQLBaseQuery {
	rowStr, err := formatIDKeyBool(rowIDOrKey)
	if err != nil {
		return NewPQLBaseQuery("", f.index, err)
	}
	text := fmt.Sprintf("ClearRow(%s=%s)", f.name, rowStr)
	q := NewPQLBaseQuery(text, f.index, nil)
	return q
}

func ( f * Field ) ClearRow ( rowIDOrKey interface { } ) * PQLBaseQuery { rowStr , err := formatIDKeyBool ( rowIDOrKey ) if err != nil { return NewPQLBaseQuery ( " " , f . index , err ) } text := fmt . Sprintf ( " " , f . name , rowStr ) q := NewPQLBaseQuery ( text , f . index , nil ) return q }

// ClearRow creates a ClearRow query.
// ClearRow sets all bits to 0 in a given row of the binary matrix, thus disassociating the given row in the given field from all columns.

ClearRow creates a ClearRow query . ClearRow sets all bits to 0 in a given row of the binary matrix thus disassociating the given row in the given field from all columns .


func (f *Field) RowTopN(n uint64, row *PQLRowQuery) *PQLRowQuery {
	q := NewPQLRowQuery(fmt.Sprintf("TopN(%s,%s,n=%d)",
		f.name, row.serialize(), n), f.index, nil)
	return q
}

func ( f * Field ) RowTopN ( n uint64 , row * PQLRowQuery ) * PQLRowQuery { q := NewPQLRowQuery ( fmt . Sprintf ( " " , f . name , row . serialize ( ) , n ) , f . index , nil ) return q }

// RowTopN creates a TopN query with the given item count and row.
// This variant supports customizing the row query.

RowTopN creates a TopN query with the given item count and row . This variant supports customizing the row query .


func (f *Field) FilterAttrTopN(n uint64, row *PQLRowQuery, attrName string, attrValues ...interface{}) *PQLRowQuery {
	return f.filterAttrTopN(n, row, attrName, attrValues...)
}

func ( f * Field ) FilterAttrTopN ( n uint64 , row * PQLRowQuery , attrName string , attrValues ... interface { } ) * PQLRowQuery { return f . filterAttrTopN ( n , row , attrName , attrValues ... ) }

// FilterAttrTopN creates a TopN query with the given item count, row, attribute name and filter values for that field
// The attrName and attrValues arguments work together to only return Rows which have the attribute specified by attrName with one of the values specified in attrValues.

FilterAttrTopN creates a TopN query with the given item count row attribute name and filter values for that field The attrName and attrValues arguments work together to only return Rows which have the attribute specified by attrName with one of the values specified in attrValues .


func (f *Field) Store(row *PQLRowQuery, rowIDOrKey interface{}) *PQLBaseQuery {
	rowStr, err := formatIDKeyBool(rowIDOrKey)
	if err != nil {
		return NewPQLBaseQuery("", f.index, err)
	}
	return NewPQLBaseQuery(fmt.Sprintf("Store(%s,%s=%s)", row.serialize().String(), f.name, rowStr), f.index, nil)
}

func ( f * Field ) Store ( row * PQLRowQuery , rowIDOrKey interface { } ) * PQLBaseQuery { rowStr , err := formatIDKeyBool ( rowIDOrKey ) if err != nil { return NewPQLBaseQuery ( " " , f . index , err ) } return NewPQLBaseQuery ( fmt . Sprintf ( " " , row . serialize ( ) . String ( ) , f . name , rowStr ) , f . index , nil ) }

// Store creates a Store call.
// Store writes the result of the row query to the specified row. If the row already exists, it will be replaced. The destination field must be of field type set.

Store creates a Store call . Store writes the result of the row query to the specified row . If the row already exists it will be replaced . The destination field must be of field type set .


func (f *Field) NotNull() *PQLRowQuery {
	text := fmt.Sprintf("Range(%s != null)", f.name)
	q := NewPQLRowQuery(text, f.index, nil)
	q.hasKeys = f.options.keys || f.index.options.keys
	return q
}

func ( f * Field ) NotNull ( ) * PQLRowQuery { text := fmt . Sprintf ( " " , f . name ) q := NewPQLRowQuery ( text , f . index , nil ) q . hasKeys = f . options . keys || f . index . options . keys return q }

// NotNull creates a not equal to null query.

NotNull creates a not equal to null query .


func (f *Field) Between(a int, b int) *PQLRowQuery {
	text := fmt.Sprintf("Range(%s >< [%d,%d])", f.name, a, b)
	q := NewPQLRowQuery(text, f.index, nil)
	q.hasKeys = f.options.keys || f.index.options.keys
	return q
}

func ( f * Field ) Between ( a int , b int ) * PQLRowQuery { text := fmt . Sprintf ( " " , f . name , a , b ) q := NewPQLRowQuery ( text , f . index , nil ) q . hasKeys = f . options . keys || f . index . options . keys return q }


func (f *Field) SetIntValue(colIDOrKey interface{}, value int) *PQLBaseQuery {
	colStr, err := formatIDKey(colIDOrKey)
	if err != nil {
		return NewPQLBaseQuery("", f.index, err)
	}
	q := fmt.Sprintf("Set(%s, %s=%d)", colStr, f.name, value)
	return NewPQLBaseQuery(q, f.index, nil)
}

func ( f * Field ) SetIntValue ( colIDOrKey interface { } , value int ) * PQLBaseQuery { colStr , err := formatIDKey ( colIDOrKey ) if err != nil { return NewPQLBaseQuery ( " " , f . index , err ) } q := fmt . Sprintf ( " " , colStr , f . name , value ) return NewPQLBaseQuery ( q , f . index , nil ) }


func NewPQLRowsQuery(pql string, index *Index, err error) *PQLRowsQuery {
	return &PQLRowsQuery{
		index: index,
		pql:   pql,
		err:   err,
	}
}

func NewPQLRowsQuery ( pql string , index * Index , err error ) * PQLRowsQuery { return & PQLRowsQuery { index : index , pql : pql , err : err , } }

// NewPQLRowsQuery creates a new PQLRowsQuery.

NewPQLRowsQuery creates a new PQLRowsQuery .


func (f *Field) Rows() *PQLRowsQuery {
	text := fmt.Sprintf("Rows(field='%s')", f.name)
	return NewPQLRowsQuery(text, f.index, nil)
}

func ( f * Field ) Rows ( ) * PQLRowsQuery { text := fmt . Sprintf ( " " , f . name ) return NewPQLRowsQuery ( text , f . index , nil ) }

// Rows creates a Rows query with defaults


func (f *Field) RowsLimit(limit int64) *PQLRowsQuery {
	if limit < 0 {
		return NewPQLRowsQuery("", f.index, errors.New("rows limit must be non-negative"))
	}
	text := fmt.Sprintf("Rows(field='%s',limit=%d)", f.name, limit)
	return NewPQLRowsQuery(text, f.index, nil)
}

func ( f * Field ) RowsLimit ( limit int64 ) * PQLRowsQuery { if limit < 0 { return NewPQLRowsQuery ( " " , f . index , errors . New ( " " ) ) } text := fmt . Sprintf ( " " , f . name , limit ) return NewPQLRowsQuery ( text , f . index , nil ) }

// RowsLimit creates a Rows query with the given limit


func (qr *QueryResponse) Result() QueryResult {
	if len(qr.ResultList) == 0 {
		return nil
	}
	return qr.ResultList[0]
}

func ( qr * QueryResponse ) Result ( ) QueryResult { if len ( qr . ResultList ) == 0 { return nil } return qr . ResultList [ 0 ] }

// Result returns the first result or nil.

Result returns the first result or nil .


func (b RowResult) MarshalJSON() ([]byte, error) {
	columns := b.Columns
	if columns == nil {
		columns = []uint64{}
	}
	keys := b.Keys
	if keys == nil {
		keys = []string{}
	}
	return json.Marshal(struct {
		Attributes map[string]interface{} `json:"attrs"`
		Columns    []uint64               `json:"columns"`
		Keys       []string               `json:"keys"`
	}{
		Attributes: b.Attributes,
		Columns:    columns,
		Keys:       keys,
	})
}

func ( b RowResult ) MarshalJSON ( ) ( [ ] byte , error ) { columns := b . Columns if columns == nil { columns = [ ] uint64 { } } keys := b . Keys if keys == nil { keys = [ ] string { } } return json . Marshal ( struct { Attributes map [ string ] interface { } `json:"attrs"` Columns [ ] uint64 `json:"columns"` Keys [ ] string `json:"keys"` } { Attributes : b . Attributes , Columns : columns , Keys : keys , } ) }

// MarshalJSON serializes this row result.

MarshalJSON serializes this row result .


func NewURIFromHostPort(host string, port uint16) (*URI, error) {
	uri := DefaultURI()
	err := uri.SetHost(host)
	if err != nil {
		return nil, err
	}
	uri.SetPort(port)
	return uri, nil
}

func NewURIFromHostPort ( host string , port uint16 ) ( * URI , error ) { uri := DefaultURI ( ) err := uri . SetHost ( host ) if err != nil { return nil , err } uri . SetPort ( port ) return uri , nil }

// NewURIFromHostPort returns a URI with specified host and port.

NewURIFromHostPort returns a URI with specified host and port .


func NewURIFromAddress(address string) (*URI, error) {
	uri, err := parseAddress(address)
	if err != nil {
		return &URI{error: err}, err
	}
	return uri, err
}

func NewURIFromAddress ( address string ) ( * URI , error ) { uri , err := parseAddress ( address ) if err != nil { return & URI { error : err } , err } return uri , err }

// NewURIFromAddress parses the passed address and returns a URI.

NewURIFromAddress parses the passed address and returns a URI .


func (u *URI) SetScheme(scheme string) error {
	m := schemeRegexp.FindStringSubmatch(scheme)
	if m == nil {
		return errors.New("invalid scheme")
	}
	u.scheme = scheme
	return nil
}

func ( u * URI ) SetScheme ( scheme string ) error { m := schemeRegexp . FindStringSubmatch ( scheme ) if m == nil { return errors . New ( " " ) } u . scheme = scheme return nil }

// SetScheme sets the scheme of this URI.


func (u *URI) SetHost(host string) error {
	m := hostRegexp.FindStringSubmatch(host)
	if m == nil {
		return errors.New("invalid host")
	}
	u.host = host
	return nil
}

func ( u * URI ) SetHost ( host string ) error { m := hostRegexp . FindStringSubmatch ( host ) if m == nil { return errors . New ( " " ) } u . host = host return nil }


func (u *URI) Normalize() string {
	scheme := u.scheme
	index := strings.Index(scheme, "+")
	if index >= 0 {
		scheme = scheme[:index]
	}
	return fmt.Sprintf("%s://%s:%d", scheme, u.host, u.port)
}

func ( u * URI ) Normalize ( ) string { scheme := u . scheme index := strings . Index ( scheme , " " ) if index >= 0 { scheme = scheme [ : index ] } return fmt . Sprintf ( " " , scheme , u . host , u . port ) }

// Normalize returns the address in a form usable by a HTTP client.

Normalize returns the address in a form usable by a HTTP client .


func (u URI) Equals(other *URI) bool {
	if other == nil {
		return false
	}
	return u.scheme == other.scheme &&
		u.host == other.host &&
		u.port == other.port
}

func ( u URI ) Equals ( other * URI ) bool { if other == nil { return false } return u . scheme == other . scheme && u . host == other . host && u . port == other . port }

// Equals returns true if the checked URI is equivalent to this URI.

Equals returns true if the checked URI is equivalent to this URI .


func ValidLabel(label string) bool {
	return len(label) <= maxLabel && labelRegex.Match([]byte(label))
}

func ValidLabel ( label string ) bool { return len ( label ) <= maxLabel && labelRegex . Match ( [ ] byte ( label ) ) }

// ValidLabel returns true if the given label is valid, otherwise false.

ValidLabel returns true if the given label is valid otherwise false .


func ValidKey(key string) bool {
	return len(key) <= maxKey && keyRegex.Match([]byte(key))
}

func ValidKey ( key string ) bool { return len ( key ) <= maxKey && keyRegex . Match ( [ ] byte ( key ) ) }

// ValidKey returns true if the given key is valid, otherwise false.

ValidKey returns true if the given key is valid otherwise false .


func NewClient(addrURIOrCluster interface{}, options ...ClientOption) (*Client, error) {
	var cluster *Cluster
	clientOptions := &ClientOptions{}
	err := clientOptions.addOptions(options...)
	if err != nil {
		return nil, err
	}

	switch u := addrURIOrCluster.(type) {
	case string:
		uri, err := NewURIFromAddress(u)
		if err != nil {
			return nil, err
		}
		return newClientWithURI(uri, clientOptions), nil
	case []string:
		if len(u) == 1 {
			uri, err := NewURIFromAddress(u[0])
			if err != nil {
				return nil, err
			}
			return newClientWithURI(uri, clientOptions), nil
		} else if clientOptions.manualServerAddress {
			return nil, ErrSingleServerAddressRequired
		}
		return newClientFromAddresses(u, clientOptions)
	case *URI:
		uriCopy := *u
		return newClientWithURI(&uriCopy, clientOptions), nil
	case []*URI:
		if len(u) == 1 {
			uriCopy := *u[0]
			return newClientWithURI(&uriCopy, clientOptions), nil
		} else if clientOptions.manualServerAddress {
			return nil, ErrSingleServerAddressRequired
		}
		cluster = NewClusterWithHost(u...)
	case *Cluster:
		cluster = u
	case nil:
		cluster = NewClusterWithHost()
	default:
		return nil, ErrAddrURIClusterExpected
	}

	return newClientWithCluster(cluster, clientOptions), nil
}

func NewClient ( addrURIOrCluster interface { } , options ... ClientOption ) ( * Client , error ) { var cluster * Cluster clientOptions := & ClientOptions { } err := clientOptions . addOptions ( options ... ) if err != nil { return nil , err } switch u := addrURIOrCluster . ( type ) { case string : uri , err := NewURIFromAddress ( u ) if err != nil { return nil , err } return newClientWithURI ( uri , clientOptions ) , nil case [ ] string : if len ( u ) == 1 { uri , err := NewURIFromAddress ( u [ 0 ] ) if err != nil { return nil , err } return newClientWithURI ( uri , clientOptions ) , nil } else if clientOptions . manualServerAddress { return nil , ErrSingleServerAddressRequired } return newClientFromAddresses ( u , clientOptions ) case * URI : uriCopy := * u return newClientWithURI ( & uriCopy , clientOptions ) , nil case [ ] * URI : if len ( u ) == 1 { uriCopy := * u [ 0 ] return newClientWithURI ( & uriCopy , clientOptions ) , nil } else if clientOptions . manualServerAddress { return nil , ErrSingleServerAddressRequired } cluster = NewClusterWithHost ( u ... ) case * Cluster : cluster = u case nil : cluster = NewClusterWithHost ( ) default : return nil , ErrAddrURIClusterExpected } return newClientWithCluster ( cluster , clientOptions ) , nil }

// NewClient creates a client with the given address, URI, or cluster and options.

NewClient creates a client with the given address URI or cluster and options .


func (c *Client) Query(query PQLQuery, options ...interface{}) (*QueryResponse, error) {
	span := c.tracer.StartSpan("Client.Query")
	defer span.Finish()

	if err := query.Error(); err != nil {
		return nil, err
	}
	queryOptions := &QueryOptions{}
	err := queryOptions.addOptions(options...)
	if err != nil {
		return nil, err
	}
	serializedQuery := query.Serialize()
	data, err := makeRequestData(serializedQuery.String(), queryOptions)
	if err != nil {
		return nil, errors.Wrap(err, "making request data")
	}
	useCoordinator := serializedQuery.HasWriteKeys()
	path := fmt.Sprintf("/index/%s/query", query.Index().name)
	_, buf, err := c.httpRequest("POST", path, data, defaultProtobufHeaders(), useCoordinator)
	if err != nil {
		return nil, err
	}
	iqr := &pbuf.QueryResponse{}
	err = proto.Unmarshal(buf, iqr)
	if err != nil {
		return nil, err
	}
	queryResponse, err := newQueryResponseFromInternal(iqr)
	if err != nil {
		return nil, err
	}
	return queryResponse, nil
}

func ( c * Client ) Query ( query PQLQuery , options ... interface { } ) ( * QueryResponse , error ) { span := c . tracer . StartSpan ( " " ) defer span . Finish ( ) if err := query . Error ( ) ; err != nil { return nil , err } queryOptions := & QueryOptions { } err := queryOptions . addOptions ( options ... ) if err != nil { return nil , err } serializedQuery := query . Serialize ( ) data , err := makeRequestData ( serializedQuery . String ( ) , queryOptions ) if err != nil { return nil , errors . Wrap ( err , " " ) } useCoordinator := serializedQuery . HasWriteKeys ( ) path := fmt . Sprintf ( " " , query . Index ( ) . name ) _ , buf , err := c . httpRequest ( " " , path , data , defaultProtobufHeaders ( ) , useCoordinator ) if err != nil { return nil , err } iqr := & pbuf . QueryResponse { } err = proto . Unmarshal ( buf , iqr ) if err != nil { return nil , err } queryResponse , err := newQueryResponseFromInternal ( iqr ) if err != nil { return nil , err } return queryResponse , nil }

// Query runs the given query against the server with the given options.
// Pass nil for default options.

Query runs the given query against the server with the given options . Pass nil for default options .


func (c *Client) CreateIndex(index *Index) error {
	span := c.tracer.StartSpan("Client.CreateIndex")
	defer span.Finish()

	data := []byte(index.options.String())
	path := fmt.Sprintf("/index/%s", index.name)
	response, _, err := c.httpRequest("POST", path, data, nil, false)
	if err != nil {
		if response != nil && response.StatusCode == 409 {
			return ErrIndexExists
		}
		return err
	}
	return nil

}

func ( c * Client ) CreateIndex ( index * Index ) error { span := c . tracer . StartSpan ( " " ) defer span . Finish ( ) data := [ ] byte ( index . options . String ( ) ) path := fmt . Sprintf ( " " , index . name ) response , _ , err := c . httpRequest ( " " , path , data , nil , false ) if err != nil { if response != nil && response . StatusCode == 409 { return ErrIndexExists } return err } return nil }

// CreateIndex creates an index on the server using the given Index struct.

CreateIndex creates an index on the server using the given Index struct .


func (c *Client) CreateField(field *Field) error {
	span := c.tracer.StartSpan("Client.CreateField")
	defer span.Finish()

	data := []byte(field.options.String())
	path := fmt.Sprintf("/index/%s/field/%s", field.index.name, field.name)
	response, _, err := c.httpRequest("POST", path, data, nil, false)
	if err != nil {
		if response != nil && response.StatusCode == 409 {
			return ErrFieldExists
		}
		return err
	}
	return nil
}

func ( c * Client ) CreateField ( field * Field ) error { span := c . tracer . StartSpan ( " " ) defer span . Finish ( ) data := [ ] byte ( field . options . String ( ) ) path := fmt . Sprintf ( " " , field . index . name , field . name ) response , _ , err := c . httpRequest ( " " , path , data , nil , false ) if err != nil { if response != nil && response . StatusCode == 409 { return ErrFieldExists } return err } return nil }

// CreateField creates a field on the server using the given Field struct.

CreateField creates a field on the server using the given Field struct .


func (c *Client) EnsureIndex(index *Index) error {
	err := c.CreateIndex(index)
	if err == ErrIndexExists {
		return nil
	}
	return err
}

func ( c * Client ) EnsureIndex ( index * Index ) error { err := c . CreateIndex ( index ) if err == ErrIndexExists { return nil } return err }

// EnsureIndex creates an index on the server if it does not exist.

EnsureIndex creates an index on the server if it does not exist .


func (c *Client) EnsureField(field *Field) error {
	err := c.CreateField(field)
	if err == ErrFieldExists {
		return nil
	}
	return err
}

func ( c * Client ) EnsureField ( field * Field ) error { err := c . CreateField ( field ) if err == ErrFieldExists { return nil } return err }

// EnsureField creates a field on the server if it doesn't exists.

EnsureField creates a field on the server if it doesn t exists .


func (c *Client) DeleteIndex(index *Index) error {
	span := c.tracer.StartSpan("Client.DeleteIndex")
	defer span.Finish()

	path := fmt.Sprintf("/index/%s", index.name)
	_, _, err := c.httpRequest("DELETE", path, nil, nil, false)
	return err

}

func ( c * Client ) DeleteIndex ( index * Index ) error { span := c . tracer . StartSpan ( " " ) defer span . Finish ( ) path := fmt . Sprintf ( " " , index . name ) _ , _ , err := c . httpRequest ( " " , path , nil , nil , false ) return err }

// DeleteIndex deletes an index on the server.

DeleteIndex deletes an index on the server .