repo stringlengths 5 67 | sha stringlengths 40 40 | path stringlengths 4 234 | url stringlengths 85 339 | language stringclasses 6 values | split stringclasses 3 values | doc stringlengths 3 51.2k | sign stringlengths 5 8.01k | problem stringlengths 13 51.2k | output stringlengths 0 3.87M |
|---|---|---|---|---|---|---|---|---|---|
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | compiler/natives/src/crypto/internal/subtle/aliasing.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/crypto/internal/subtle/aliasing.go#L9-L15 | go | train | // AnyOverlap reports whether x and y share memory at any (not necessarily
// corresponding) index. The memory beyond the slice length is ignored. | func AnyOverlap(x, y []byte) bool | // AnyOverlap reports whether x and y share memory at any (not necessarily
// corresponding) index. The memory beyond the slice length is ignored.
func AnyOverlap(x, y []byte) bool | {
// GopherJS: We can't rely on pointer arithmetic, so use GopherJS slice internals.
return len(x) > 0 && len(y) > 0 &&
js.InternalObject(x).Get("$array") == js.InternalObject(y).Get("$array") &&
js.InternalObject(x).Get("$offset").Int() <= js.InternalObject(y).Get("$offset").Int()+len(y)-1 &&
js.InternalObject(y).Get("$offset").Int() <= js.InternalObject(x).Get("$offset").Int()+len(x)-1
} |
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | compiler/natives/src/syscall/js/js.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/syscall/js/js.go#L171-L178 | go | train | // convertArgs converts arguments into values for GopherJS arguments. | func convertArgs(args ...interface{}) []interface{} | // convertArgs converts arguments into values for GopherJS arguments.
func convertArgs(args ...interface{}) []interface{} | {
newArgs := []interface{}{}
for _, arg := range args {
v := ValueOf(arg)
newArgs = append(newArgs, v.internal())
}
return newArgs
} |
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | compiler/natives/src/net/net.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/net/net.go#L45-L55 | go | train | // Copy of bytes.Equal. | func bytesEqual(x, y []byte) bool | // Copy of bytes.Equal.
func bytesEqual(x, y []byte) bool | {
if len(x) != len(y) {
return false
}
for i, b := range x {
if b != y[i] {
return false
}
}
return true
} |
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | compiler/natives/src/net/net.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/net/net.go#L58-L65 | go | train | // Copy of bytes.IndexByte. | func bytesIndexByte(s []byte, c byte) int | // Copy of bytes.IndexByte.
func bytesIndexByte(s []byte, c byte) int | {
for i, b := range s {
if b == c {
return i
}
}
return -1
} |
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | nosync/pool.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/pool.go#L45-L55 | go | train | // Get selects an arbitrary item from the Pool, removes it from the
// Pool, and returns it to the caller.
// Get may choose to ignore the pool and treat it as empty.
// Callers should not assume any relation between values passed to Put and
// the values returned by Get.
//
// If Get would otherwise return nil and p.New is non-nil, Get returns
// the result of calling p.New. | func (p *Pool) Get() interface{} | // Get selects an arbitrary item from the Pool, removes it from the
// Pool, and returns it to the caller.
// Get may choose to ignore the pool and treat it as empty.
// Callers should not assume any relation between values passed to Put and
// the values returned by Get.
//
// If Get would otherwise return nil and p.New is non-nil, Get returns
// the result of calling p.New.
func (p *Pool) Get() interface{} | {
if len(p.store) == 0 {
if p.New != nil {
return p.New()
}
return nil
}
x := p.store[len(p.store)-1]
p.store = p.store[:len(p.store)-1]
return x
} |
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | nosync/pool.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/nosync/pool.go#L58-L63 | go | train | // Put adds x to the pool. | func (p *Pool) Put(x interface{}) | // Put adds x to the pool.
func (p *Pool) Put(x interface{}) | {
if x == nil {
return
}
p.store = append(p.store, x)
} |
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | tool.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/tool.go#L698-L713 | go | train | // handleError handles err and returns an appropriate exit code.
// If browserErrors is non-nil, errors are written for presentation in browser. | func handleError(err error, options *gbuild.Options, browserErrors *bytes.Buffer) int | // handleError handles err and returns an appropriate exit code.
// If browserErrors is non-nil, errors are written for presentation in browser.
func handleError(err error, options *gbuild.Options, browserErrors *bytes.Buffer) int | {
switch err := err.(type) {
case nil:
return 0
case compiler.ErrorList:
for _, entry := range err {
printError(entry, options, browserErrors)
}
return 1
case *exec.ExitError:
return err.Sys().(syscall.WaitStatus).ExitStatus()
default:
printError(err, options, browserErrors)
return 1
}
} |
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | tool.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/tool.go#L716-L722 | go | train | // printError prints err to Stderr with options. If browserErrors is non-nil, errors are also written for presentation in browser. | func printError(err error, options *gbuild.Options, browserErrors *bytes.Buffer) | // printError prints err to Stderr with options. If browserErrors is non-nil, errors are also written for presentation in browser.
func printError(err error, options *gbuild.Options, browserErrors *bytes.Buffer) | {
e := sprintError(err)
options.PrintError("%s\n", e)
if browserErrors != nil {
fmt.Fprintln(browserErrors, `console.error("`+template.JSEscapeString(e)+`");`)
}
} |
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | tool.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/tool.go#L725-L742 | go | train | // sprintError returns an annotated error string without trailing newline. | func sprintError(err error) string | // sprintError returns an annotated error string without trailing newline.
func sprintError(err error) string | {
makeRel := func(name string) string {
if relname, err := filepath.Rel(currentDirectory, name); err == nil {
return relname
}
return name
}
switch e := err.(type) {
case *scanner.Error:
return fmt.Sprintf("%s:%d:%d: %s", makeRel(e.Pos.Filename), e.Pos.Line, e.Pos.Column, e.Msg)
case types.Error:
pos := e.Fset.Position(e.Pos)
return fmt.Sprintf("%s:%d:%d: %s", makeRel(pos.Filename), pos.Line, pos.Column, e.Msg)
default:
return fmt.Sprintf("%s", e)
}
} |
gopherjs/gopherjs | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | tool.go | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/tool.go#L746-L794 | go | train | // runNode runs script with args using Node.js in directory dir.
// If dir is empty string, current directory is used. | func runNode(script string, args []string, dir string, quiet bool) error | // runNode runs script with args using Node.js in directory dir.
// If dir is empty string, current directory is used.
func runNode(script string, args []string, dir string, quiet bool) error | {
var allArgs []string
if b, _ := strconv.ParseBool(os.Getenv("SOURCE_MAP_SUPPORT")); os.Getenv("SOURCE_MAP_SUPPORT") == "" || b {
allArgs = []string{"--require", "source-map-support/register"}
if err := exec.Command("node", "--require", "source-map-support/register", "--eval", "").Run(); err != nil {
if !quiet {
fmt.Fprintln(os.Stderr, "gopherjs: Source maps disabled. Install source-map-support module for nice stack traces. See https://github.com/gopherjs/gopherjs#gopherjs-run-gopherjs-test.")
}
allArgs = []string{}
}
}
if runtime.GOOS != "windows" {
// We've seen issues with stack space limits causing
// recursion-heavy standard library tests to fail (e.g., see
// https://github.com/gopherjs/gopherjs/pull/669#issuecomment-319319483).
//
// There are two separate limits in non-Windows environments:
//
// - OS process limit
// - Node.js (V8) limit
//
// GopherJS fetches the current OS process limit, and sets the
// Node.js limit to the same value. So both limits are kept in sync
// and can be controlled by setting OS process limit. E.g.:
//
// ulimit -s 10000 && gopherjs test
//
cur, err := sysutil.RlimitStack()
if err != nil {
return fmt.Errorf("failed to get stack size limit: %v", err)
}
allArgs = append(allArgs, fmt.Sprintf("--stack_size=%v", cur/1000)) // Convert from bytes to KB.
}
allArgs = append(allArgs, script)
allArgs = append(allArgs, args...)
node := exec.Command("node", allArgs...)
node.Dir = dir
node.Stdin = os.Stdin
node.Stdout = os.Stdout
node.Stderr = os.Stderr
err := node.Run()
if _, ok := err.(*exec.ExitError); err != nil && !ok {
err = fmt.Errorf("could not run Node.js: %s", err.Error())
}
return err
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | tools.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L11-L26 | go | train | // New creates a new image with the specified width and height, and fills it with the specified color. | func New(width, height int, fillColor color.Color) *image.NRGBA | // New creates a new image with the specified width and height, and fills it with the specified color.
func New(width, height int, fillColor color.Color) *image.NRGBA | {
if width <= 0 || height <= 0 {
return &image.NRGBA{}
}
c := color.NRGBAModel.Convert(fillColor).(color.NRGBA)
if (c == color.NRGBA{0, 0, 0, 0}) {
return image.NewNRGBA(image.Rect(0, 0, width, height))
}
return &image.NRGBA{
Pix: bytes.Repeat([]byte{c.R, c.G, c.B, c.A}, width*height),
Stride: 4 * width,
Rect: image.Rect(0, 0, width, height),
}
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | tools.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L29-L40 | go | train | // Clone returns a copy of the given image. | func Clone(img image.Image) *image.NRGBA | // Clone returns a copy of the given image.
func Clone(img image.Image) *image.NRGBA | {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
size := src.w * 4
parallel(0, src.h, func(ys <-chan int) {
for y := range ys {
i := y * dst.Stride
src.scan(0, y, src.w, y+1, dst.Pix[i:i+size])
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | tools.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L94-L109 | go | train | // Crop cuts out a rectangular region with the specified bounds
// from the image and returns the cropped image. | func Crop(img image.Image, rect image.Rectangle) *image.NRGBA | // Crop cuts out a rectangular region with the specified bounds
// from the image and returns the cropped image.
func Crop(img image.Image, rect image.Rectangle) *image.NRGBA | {
r := rect.Intersect(img.Bounds()).Sub(img.Bounds().Min)
if r.Empty() {
return &image.NRGBA{}
}
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, r.Dx(), r.Dy()))
rowSize := r.Dx() * 4
parallel(r.Min.Y, r.Max.Y, func(ys <-chan int) {
for y := range ys {
i := (y - r.Min.Y) * dst.Stride
src.scan(r.Min.X, y, r.Max.X, y+1, dst.Pix[i:i+rowSize])
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | tools.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L113-L119 | go | train | // CropAnchor cuts out a rectangular region with the specified size
// from the image using the specified anchor point and returns the cropped image. | func CropAnchor(img image.Image, width, height int, anchor Anchor) *image.NRGBA | // CropAnchor cuts out a rectangular region with the specified size
// from the image using the specified anchor point and returns the cropped image.
func CropAnchor(img image.Image, width, height int, anchor Anchor) *image.NRGBA | {
srcBounds := img.Bounds()
pt := anchorPt(srcBounds, width, height, anchor)
r := image.Rect(0, 0, width, height).Add(pt)
b := srcBounds.Intersect(r)
return Crop(img, b)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | tools.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L123-L125 | go | train | // CropCenter cuts out a rectangular region with the specified size
// from the center of the image and returns the cropped image. | func CropCenter(img image.Image, width, height int) *image.NRGBA | // CropCenter cuts out a rectangular region with the specified size
// from the center of the image and returns the cropped image.
func CropCenter(img image.Image, width, height int) *image.NRGBA | {
return CropAnchor(img, width, height, Center)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | tools.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L128-L149 | go | train | // Paste pastes the img image to the background image at the specified position and returns the combined image. | func Paste(background, img image.Image, pos image.Point) *image.NRGBA | // Paste pastes the img image to the background image at the specified position and returns the combined image.
func Paste(background, img image.Image, pos image.Point) *image.NRGBA | {
dst := Clone(background)
pos = pos.Sub(background.Bounds().Min)
pasteRect := image.Rectangle{Min: pos, Max: pos.Add(img.Bounds().Size())}
interRect := pasteRect.Intersect(dst.Bounds())
if interRect.Empty() {
return dst
}
src := newScanner(img)
parallel(interRect.Min.Y, interRect.Max.Y, func(ys <-chan int) {
for y := range ys {
x1 := interRect.Min.X - pasteRect.Min.X
x2 := interRect.Max.X - pasteRect.Min.X
y1 := y - pasteRect.Min.Y
y2 := y1 + 1
i1 := y*dst.Stride + interRect.Min.X*4
i2 := i1 + interRect.Dx()*4
src.scan(x1, y1, x2, y2, dst.Pix[i1:i2])
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | tools.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L152-L166 | go | train | // PasteCenter pastes the img image to the center of the background image and returns the combined image. | func PasteCenter(background, img image.Image) *image.NRGBA | // PasteCenter pastes the img image to the center of the background image and returns the combined image.
func PasteCenter(background, img image.Image) *image.NRGBA | {
bgBounds := background.Bounds()
bgW := bgBounds.Dx()
bgH := bgBounds.Dy()
bgMinX := bgBounds.Min.X
bgMinY := bgBounds.Min.Y
centerX := bgMinX + bgW/2
centerY := bgMinY + bgH/2
x0 := centerX - img.Bounds().Dx()/2
y0 := centerY - img.Bounds().Dy()/2
return Paste(background, img, image.Pt(x0, y0))
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | tools.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L180-L230 | go | train | // Overlay draws the img image over the background image at given position
// and returns the combined image. Opacity parameter is the opacity of the img
// image layer, used to compose the images, it must be from 0.0 to 1.0.
//
// Examples:
//
// // Draw spriteImage over backgroundImage at the given position (x=50, y=50).
// dstImage := imaging.Overlay(backgroundImage, spriteImage, image.Pt(50, 50), 1.0)
//
// // Blend two opaque images of the same size.
// dstImage := imaging.Overlay(imageOne, imageTwo, image.Pt(0, 0), 0.5)
// | func Overlay(background, img image.Image, pos image.Point, opacity float64) *image.NRGBA | // Overlay draws the img image over the background image at given position
// and returns the combined image. Opacity parameter is the opacity of the img
// image layer, used to compose the images, it must be from 0.0 to 1.0.
//
// Examples:
//
// // Draw spriteImage over backgroundImage at the given position (x=50, y=50).
// dstImage := imaging.Overlay(backgroundImage, spriteImage, image.Pt(50, 50), 1.0)
//
// // Blend two opaque images of the same size.
// dstImage := imaging.Overlay(imageOne, imageTwo, image.Pt(0, 0), 0.5)
//
func Overlay(background, img image.Image, pos image.Point, opacity float64) *image.NRGBA | {
opacity = math.Min(math.Max(opacity, 0.0), 1.0) // Ensure 0.0 <= opacity <= 1.0.
dst := Clone(background)
pos = pos.Sub(background.Bounds().Min)
pasteRect := image.Rectangle{Min: pos, Max: pos.Add(img.Bounds().Size())}
interRect := pasteRect.Intersect(dst.Bounds())
if interRect.Empty() {
return dst
}
src := newScanner(img)
parallel(interRect.Min.Y, interRect.Max.Y, func(ys <-chan int) {
scanLine := make([]uint8, interRect.Dx()*4)
for y := range ys {
x1 := interRect.Min.X - pasteRect.Min.X
x2 := interRect.Max.X - pasteRect.Min.X
y1 := y - pasteRect.Min.Y
y2 := y1 + 1
src.scan(x1, y1, x2, y2, scanLine)
i := y*dst.Stride + interRect.Min.X*4
j := 0
for x := interRect.Min.X; x < interRect.Max.X; x++ {
d := dst.Pix[i : i+4 : i+4]
r1 := float64(d[0])
g1 := float64(d[1])
b1 := float64(d[2])
a1 := float64(d[3])
s := scanLine[j : j+4 : j+4]
r2 := float64(s[0])
g2 := float64(s[1])
b2 := float64(s[2])
a2 := float64(s[3])
coef2 := opacity * a2 / 255
coef1 := (1 - coef2) * a1 / 255
coefSum := coef1 + coef2
coef1 /= coefSum
coef2 /= coefSum
d[0] = uint8(r1*coef1 + r2*coef2)
d[1] = uint8(g1*coef1 + g2*coef2)
d[2] = uint8(b1*coef1 + b2*coef2)
d[3] = uint8(math.Min(a1+a2*opacity*(255-a1)/255, 255))
i += 4
j += 4
}
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | tools.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L235-L249 | go | train | // OverlayCenter overlays the img image to the center of the background image and
// returns the combined image. Opacity parameter is the opacity of the img
// image layer, used to compose the images, it must be from 0.0 to 1.0. | func OverlayCenter(background, img image.Image, opacity float64) *image.NRGBA | // OverlayCenter overlays the img image to the center of the background image and
// returns the combined image. Opacity parameter is the opacity of the img
// image layer, used to compose the images, it must be from 0.0 to 1.0.
func OverlayCenter(background, img image.Image, opacity float64) *image.NRGBA | {
bgBounds := background.Bounds()
bgW := bgBounds.Dx()
bgH := bgBounds.Dy()
bgMinX := bgBounds.Min.X
bgMinY := bgBounds.Min.Y
centerX := bgMinX + bgW/2
centerY := bgMinY + bgH/2
x0 := centerX - img.Bounds().Dx()/2
y0 := centerY - img.Bounds().Dy()/2
return Overlay(background, img, image.Point{x0, y0}, opacity)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | transform.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/transform.go#L10-L25 | go | train | // FlipH flips the image horizontally (from left to right) and returns the transformed image. | func FlipH(img image.Image) *image.NRGBA | // FlipH flips the image horizontally (from left to right) and returns the transformed image.
func FlipH(img image.Image) *image.NRGBA | {
src := newScanner(img)
dstW := src.w
dstH := src.h
rowSize := dstW * 4
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
parallel(0, dstH, func(ys <-chan int) {
for dstY := range ys {
i := dstY * dst.Stride
srcY := dstY
src.scan(0, srcY, src.w, srcY+1, dst.Pix[i:i+rowSize])
reverse(dst.Pix[i : i+rowSize])
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | transform.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/transform.go#L135-L178 | go | train | // Rotate rotates an image by the given angle counter-clockwise .
// The angle parameter is the rotation angle in degrees.
// The bgColor parameter specifies the color of the uncovered zone after the rotation. | func Rotate(img image.Image, angle float64, bgColor color.Color) *image.NRGBA | // Rotate rotates an image by the given angle counter-clockwise .
// The angle parameter is the rotation angle in degrees.
// The bgColor parameter specifies the color of the uncovered zone after the rotation.
func Rotate(img image.Image, angle float64, bgColor color.Color) *image.NRGBA | {
angle = angle - math.Floor(angle/360)*360
switch angle {
case 0:
return Clone(img)
case 90:
return Rotate90(img)
case 180:
return Rotate180(img)
case 270:
return Rotate270(img)
}
src := toNRGBA(img)
srcW := src.Bounds().Max.X
srcH := src.Bounds().Max.Y
dstW, dstH := rotatedSize(srcW, srcH, angle)
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
if dstW <= 0 || dstH <= 0 {
return dst
}
srcXOff := float64(srcW)/2 - 0.5
srcYOff := float64(srcH)/2 - 0.5
dstXOff := float64(dstW)/2 - 0.5
dstYOff := float64(dstH)/2 - 0.5
bgColorNRGBA := color.NRGBAModel.Convert(bgColor).(color.NRGBA)
sin, cos := math.Sincos(math.Pi * angle / 180)
parallel(0, dstH, func(ys <-chan int) {
for dstY := range ys {
for dstX := 0; dstX < dstW; dstX++ {
xf, yf := rotatePoint(float64(dstX)-dstXOff, float64(dstY)-dstYOff, sin, cos)
xf, yf = xf+srcXOff, yf+srcYOff
interpolatePoint(dst, dstX, dstY, src, xf, yf, bgColorNRGBA)
}
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | effects.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/effects.go#L19-L32 | go | train | // Blur produces a blurred version of the image using a Gaussian function.
// Sigma parameter must be positive and indicates how much the image will be blurred.
//
// Example:
//
// dstImage := imaging.Blur(srcImage, 3.5)
// | func Blur(img image.Image, sigma float64) *image.NRGBA | // Blur produces a blurred version of the image using a Gaussian function.
// Sigma parameter must be positive and indicates how much the image will be blurred.
//
// Example:
//
// dstImage := imaging.Blur(srcImage, 3.5)
//
func Blur(img image.Image, sigma float64) *image.NRGBA | {
if sigma <= 0 {
return Clone(img)
}
radius := int(math.Ceil(sigma * 3.0))
kernel := make([]float64, radius+1)
for i := 0; i <= radius; i++ {
kernel[i] = gaussianBlurKernel(float64(i), sigma)
}
return blurVertical(blurHorizontal(img, kernel), kernel)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | effects.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/effects.go#L141-L169 | go | train | // Sharpen produces a sharpened version of the image.
// Sigma parameter must be positive and indicates how much the image will be sharpened.
//
// Example:
//
// dstImage := imaging.Sharpen(srcImage, 3.5)
// | func Sharpen(img image.Image, sigma float64) *image.NRGBA | // Sharpen produces a sharpened version of the image.
// Sigma parameter must be positive and indicates how much the image will be sharpened.
//
// Example:
//
// dstImage := imaging.Sharpen(srcImage, 3.5)
//
func Sharpen(img image.Image, sigma float64) *image.NRGBA | {
if sigma <= 0 {
return Clone(img)
}
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
blurred := Blur(img, sigma)
parallel(0, src.h, func(ys <-chan int) {
scanLine := make([]uint8, src.w*4)
for y := range ys {
src.scan(0, y, src.w, y+1, scanLine)
j := y * dst.Stride
for i := 0; i < src.w*4; i++ {
val := int(scanLine[i])<<1 - int(blurred.Pix[j])
if val < 0 {
val = 0
} else if val > 0xff {
val = 0xff
}
dst.Pix[j] = uint8(val)
j++
}
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | utils.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/utils.go#L11-L37 | go | train | // parallel processes the data in separate goroutines. | func parallel(start, stop int, fn func(<-chan int)) | // parallel processes the data in separate goroutines.
func parallel(start, stop int, fn func(<-chan int)) | {
count := stop - start
if count < 1 {
return
}
procs := runtime.GOMAXPROCS(0)
if procs > count {
procs = count
}
c := make(chan int, count)
for i := start; i < stop; i++ {
c <- i
}
close(c)
var wg sync.WaitGroup
for i := 0; i < procs; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fn(c)
}()
}
wg.Wait()
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | utils.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/utils.go#L48-L57 | go | train | // clamp rounds and clamps float64 value to fit into uint8. | func clamp(x float64) uint8 | // clamp rounds and clamps float64 value to fit into uint8.
func clamp(x float64) uint8 | {
v := int64(x + 0.5)
if v > 255 {
return 255
}
if v > 0 {
return uint8(v)
}
return 0
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | utils.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/utils.go#L89-L125 | go | train | // rgbToHSL converts a color from RGB to HSL. | func rgbToHSL(r, g, b uint8) (float64, float64, float64) | // rgbToHSL converts a color from RGB to HSL.
func rgbToHSL(r, g, b uint8) (float64, float64, float64) | {
rr := float64(r) / 255
gg := float64(g) / 255
bb := float64(b) / 255
max := math.Max(rr, math.Max(gg, bb))
min := math.Min(rr, math.Min(gg, bb))
l := (max + min) / 2
if max == min {
return 0, 0, l
}
var h, s float64
d := max - min
if l > 0.5 {
s = d / (2 - max - min)
} else {
s = d / (max + min)
}
switch max {
case rr:
h = (gg - bb) / d
if g < b {
h += 6
}
case gg:
h = (bb-rr)/d + 2
case bb:
h = (rr-gg)/d + 4
}
h /= 6
return h, s, l
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | utils.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/utils.go#L128-L148 | go | train | // hslToRGB converts a color from HSL to RGB. | func hslToRGB(h, s, l float64) (uint8, uint8, uint8) | // hslToRGB converts a color from HSL to RGB.
func hslToRGB(h, s, l float64) (uint8, uint8, uint8) | {
var r, g, b float64
if s == 0 {
v := clamp(l * 255)
return v, v, v
}
var q float64
if l < 0.5 {
q = l * (1 + s)
} else {
q = l + s - l*s
}
p := 2*l - q
r = hueToRGB(p, q, h+1/3.0)
g = hueToRGB(p, q, h)
b = hueToRGB(p, q, h-1/3.0)
return clamp(r * 255), clamp(g * 255), clamp(b * 255)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | convolution.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/convolution.go#L21-L23 | go | train | // Convolve3x3 convolves the image with the specified 3x3 convolution kernel.
// Default parameters are used if a nil *ConvolveOptions is passed. | func Convolve3x3(img image.Image, kernel [9]float64, options *ConvolveOptions) *image.NRGBA | // Convolve3x3 convolves the image with the specified 3x3 convolution kernel.
// Default parameters are used if a nil *ConvolveOptions is passed.
func Convolve3x3(img image.Image, kernel [9]float64, options *ConvolveOptions) *image.NRGBA | {
return convolve(img, kernel[:], options)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | histogram.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/histogram.go#L12-L52 | go | train | // Histogram returns a normalized histogram of an image.
//
// Resulting histogram is represented as an array of 256 floats, where
// histogram[i] is a probability of a pixel being of a particular luminance i. | func Histogram(img image.Image) [256]float64 | // Histogram returns a normalized histogram of an image.
//
// Resulting histogram is represented as an array of 256 floats, where
// histogram[i] is a probability of a pixel being of a particular luminance i.
func Histogram(img image.Image) [256]float64 | {
var mu sync.Mutex
var histogram [256]float64
var total float64
src := newScanner(img)
if src.w == 0 || src.h == 0 {
return histogram
}
parallel(0, src.h, func(ys <-chan int) {
var tmpHistogram [256]float64
var tmpTotal float64
scanLine := make([]uint8, src.w*4)
for y := range ys {
src.scan(0, y, src.w, y+1, scanLine)
i := 0
for x := 0; x < src.w; x++ {
s := scanLine[i : i+3 : i+3]
r := s[0]
g := s[1]
b := s[2]
y := 0.299*float32(r) + 0.587*float32(g) + 0.114*float32(b)
tmpHistogram[int(y+0.5)]++
tmpTotal++
i += 4
}
}
mu.Lock()
for i := 0; i < 256; i++ {
histogram[i] += tmpHistogram[i]
}
total += tmpTotal
mu.Unlock()
})
for i := 0; i < 256; i++ {
histogram[i] = histogram[i] / total
}
return histogram
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | resize.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L65-L105 | go | train | // Resize resizes the image to the specified width and height using the specified resampling
// filter and returns the transformed image. If one of width or height is 0, the image aspect
// ratio is preserved.
//
// Example:
//
// dstImage := imaging.Resize(srcImage, 800, 600, imaging.Lanczos)
// | func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA | // Resize resizes the image to the specified width and height using the specified resampling
// filter and returns the transformed image. If one of width or height is 0, the image aspect
// ratio is preserved.
//
// Example:
//
// dstImage := imaging.Resize(srcImage, 800, 600, imaging.Lanczos)
//
func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA | {
dstW, dstH := width, height
if dstW < 0 || dstH < 0 {
return &image.NRGBA{}
}
if dstW == 0 && dstH == 0 {
return &image.NRGBA{}
}
srcW := img.Bounds().Dx()
srcH := img.Bounds().Dy()
if srcW <= 0 || srcH <= 0 {
return &image.NRGBA{}
}
// If new width or height is 0 then preserve aspect ratio, minimum 1px.
if dstW == 0 {
tmpW := float64(dstH) * float64(srcW) / float64(srcH)
dstW = int(math.Max(1.0, math.Floor(tmpW+0.5)))
}
if dstH == 0 {
tmpH := float64(dstW) * float64(srcH) / float64(srcW)
dstH = int(math.Max(1.0, math.Floor(tmpH+0.5)))
}
if filter.Support <= 0 {
// Nearest-neighbor special case.
return resizeNearest(img, dstW, dstH)
}
if srcW != dstW && srcH != dstH {
return resizeVertical(resizeHorizontal(img, dstW, filter), dstH, filter)
}
if srcW != dstW {
return resizeHorizontal(img, dstW, filter)
}
if srcH != dstH {
return resizeVertical(img, dstH, filter)
}
return Clone(img)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | resize.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L177-L213 | go | train | // resizeNearest is a fast nearest-neighbor resize, no filtering. | func resizeNearest(img image.Image, width, height int) *image.NRGBA | // resizeNearest is a fast nearest-neighbor resize, no filtering.
func resizeNearest(img image.Image, width, height int) *image.NRGBA | {
dst := image.NewNRGBA(image.Rect(0, 0, width, height))
dx := float64(img.Bounds().Dx()) / float64(width)
dy := float64(img.Bounds().Dy()) / float64(height)
if dx > 1 && dy > 1 {
src := newScanner(img)
parallel(0, height, func(ys <-chan int) {
for y := range ys {
srcY := int((float64(y) + 0.5) * dy)
dstOff := y * dst.Stride
for x := 0; x < width; x++ {
srcX := int((float64(x) + 0.5) * dx)
src.scan(srcX, srcY, srcX+1, srcY+1, dst.Pix[dstOff:dstOff+4])
dstOff += 4
}
}
})
} else {
src := toNRGBA(img)
parallel(0, height, func(ys <-chan int) {
for y := range ys {
srcY := int((float64(y) + 0.5) * dy)
srcOff0 := srcY * src.Stride
dstOff := y * dst.Stride
for x := 0; x < width; x++ {
srcX := int((float64(x) + 0.5) * dx)
srcOff := srcOff0 + srcX*4
copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
dstOff += 4
}
}
})
}
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | resize.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L222-L254 | go | train | // Fit scales down the image using the specified resample filter to fit the specified
// maximum width and height and returns the transformed image.
//
// Example:
//
// dstImage := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
// | func Fit(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA | // Fit scales down the image using the specified resample filter to fit the specified
// maximum width and height and returns the transformed image.
//
// Example:
//
// dstImage := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
//
func Fit(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA | {
maxW, maxH := width, height
if maxW <= 0 || maxH <= 0 {
return &image.NRGBA{}
}
srcBounds := img.Bounds()
srcW := srcBounds.Dx()
srcH := srcBounds.Dy()
if srcW <= 0 || srcH <= 0 {
return &image.NRGBA{}
}
if srcW <= maxW && srcH <= maxH {
return Clone(img)
}
srcAspectRatio := float64(srcW) / float64(srcH)
maxAspectRatio := float64(maxW) / float64(maxH)
var newW, newH int
if srcAspectRatio > maxAspectRatio {
newW = maxW
newH = int(float64(newW) / srcAspectRatio)
} else {
newH = maxH
newW = int(float64(newH) * srcAspectRatio)
}
return Resize(img, newW, newH, filter)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | resize.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L263-L286 | go | train | // Fill creates an image with the specified dimensions and fills it with the scaled source image.
// To achieve the correct aspect ratio without stretching, the source image will be cropped.
//
// Example:
//
// dstImage := imaging.Fill(srcImage, 800, 600, imaging.Center, imaging.Lanczos)
// | func Fill(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA | // Fill creates an image with the specified dimensions and fills it with the scaled source image.
// To achieve the correct aspect ratio without stretching, the source image will be cropped.
//
// Example:
//
// dstImage := imaging.Fill(srcImage, 800, 600, imaging.Center, imaging.Lanczos)
//
func Fill(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA | {
dstW, dstH := width, height
if dstW <= 0 || dstH <= 0 {
return &image.NRGBA{}
}
srcBounds := img.Bounds()
srcW := srcBounds.Dx()
srcH := srcBounds.Dy()
if srcW <= 0 || srcH <= 0 {
return &image.NRGBA{}
}
if srcW == dstW && srcH == dstH {
return Clone(img)
}
if srcW >= 100 && srcH >= 100 {
return cropAndResize(img, dstW, dstH, anchor, filter)
}
return resizeAndCrop(img, dstW, dstH, anchor, filter)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | resize.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L292-L311 | go | train | // cropAndResize crops the image to the smallest possible size that has the required aspect ratio using
// the given anchor point, then scales it to the specified dimensions and returns the transformed image.
//
// This is generally faster than resizing first, but may result in inaccuracies when used on small source images. | func cropAndResize(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA | // cropAndResize crops the image to the smallest possible size that has the required aspect ratio using
// the given anchor point, then scales it to the specified dimensions and returns the transformed image.
//
// This is generally faster than resizing first, but may result in inaccuracies when used on small source images.
func cropAndResize(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA | {
dstW, dstH := width, height
srcBounds := img.Bounds()
srcW := srcBounds.Dx()
srcH := srcBounds.Dy()
srcAspectRatio := float64(srcW) / float64(srcH)
dstAspectRatio := float64(dstW) / float64(dstH)
var tmp *image.NRGBA
if srcAspectRatio < dstAspectRatio {
cropH := float64(srcW) * float64(dstH) / float64(dstW)
tmp = CropAnchor(img, srcW, int(math.Max(1, cropH)+0.5), anchor)
} else {
cropW := float64(srcH) * float64(dstW) / float64(dstH)
tmp = CropAnchor(img, int(math.Max(1, cropW)+0.5), srcH, anchor)
}
return Resize(tmp, dstW, dstH, filter)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | resize.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L316-L333 | go | train | // resizeAndCrop resizes the image to the smallest possible size that will cover the specified dimensions,
// crops the resized image to the specified dimensions using the given anchor point and returns
// the transformed image. | func resizeAndCrop(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA | // resizeAndCrop resizes the image to the smallest possible size that will cover the specified dimensions,
// crops the resized image to the specified dimensions using the given anchor point and returns
// the transformed image.
func resizeAndCrop(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA | {
dstW, dstH := width, height
srcBounds := img.Bounds()
srcW := srcBounds.Dx()
srcH := srcBounds.Dy()
srcAspectRatio := float64(srcW) / float64(srcH)
dstAspectRatio := float64(dstW) / float64(dstH)
var tmp *image.NRGBA
if srcAspectRatio < dstAspectRatio {
tmp = Resize(img, dstW, 0, filter)
} else {
tmp = Resize(img, 0, dstH, filter)
}
return CropAnchor(tmp, dstW, dstH, anchor)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | resize.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L342-L344 | go | train | // Thumbnail scales the image up or down using the specified resample filter, crops it
// to the specified width and hight and returns the transformed image.
//
// Example:
//
// dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
// | func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA | // Thumbnail scales the image up or down using the specified resample filter, crops it
// to the specified width and hight and returns the transformed image.
//
// Example:
//
// dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
//
func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA | {
return Fill(img, width, height, Center, filter)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | scanner.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/scanner.go#L30-L285 | go | train | // scan scans the given rectangular region of the image into dst. | func (s *scanner) scan(x1, y1, x2, y2 int, dst []uint8) | // scan scans the given rectangular region of the image into dst.
func (s *scanner) scan(x1, y1, x2, y2 int, dst []uint8) | {
switch img := s.image.(type) {
case *image.NRGBA:
size := (x2 - x1) * 4
j := 0
i := y1*img.Stride + x1*4
if size == 4 {
for y := y1; y < y2; y++ {
d := dst[j : j+4 : j+4]
s := img.Pix[i : i+4 : i+4]
d[0] = s[0]
d[1] = s[1]
d[2] = s[2]
d[3] = s[3]
j += size
i += img.Stride
}
} else {
for y := y1; y < y2; y++ {
copy(dst[j:j+size], img.Pix[i:i+size])
j += size
i += img.Stride
}
}
case *image.NRGBA64:
j := 0
for y := y1; y < y2; y++ {
i := y*img.Stride + x1*8
for x := x1; x < x2; x++ {
s := img.Pix[i : i+8 : i+8]
d := dst[j : j+4 : j+4]
d[0] = s[0]
d[1] = s[2]
d[2] = s[4]
d[3] = s[6]
j += 4
i += 8
}
}
case *image.RGBA:
j := 0
for y := y1; y < y2; y++ {
i := y*img.Stride + x1*4
for x := x1; x < x2; x++ {
d := dst[j : j+4 : j+4]
a := img.Pix[i+3]
switch a {
case 0:
d[0] = 0
d[1] = 0
d[2] = 0
d[3] = a
case 0xff:
s := img.Pix[i : i+4 : i+4]
d[0] = s[0]
d[1] = s[1]
d[2] = s[2]
d[3] = a
default:
s := img.Pix[i : i+4 : i+4]
r16 := uint16(s[0])
g16 := uint16(s[1])
b16 := uint16(s[2])
a16 := uint16(a)
d[0] = uint8(r16 * 0xff / a16)
d[1] = uint8(g16 * 0xff / a16)
d[2] = uint8(b16 * 0xff / a16)
d[3] = a
}
j += 4
i += 4
}
}
case *image.RGBA64:
j := 0
for y := y1; y < y2; y++ {
i := y*img.Stride + x1*8
for x := x1; x < x2; x++ {
s := img.Pix[i : i+8 : i+8]
d := dst[j : j+4 : j+4]
a := s[6]
switch a {
case 0:
d[0] = 0
d[1] = 0
d[2] = 0
case 0xff:
d[0] = s[0]
d[1] = s[2]
d[2] = s[4]
default:
r32 := uint32(s[0])<<8 | uint32(s[1])
g32 := uint32(s[2])<<8 | uint32(s[3])
b32 := uint32(s[4])<<8 | uint32(s[5])
a32 := uint32(s[6])<<8 | uint32(s[7])
d[0] = uint8((r32 * 0xffff / a32) >> 8)
d[1] = uint8((g32 * 0xffff / a32) >> 8)
d[2] = uint8((b32 * 0xffff / a32) >> 8)
}
d[3] = a
j += 4
i += 8
}
}
case *image.Gray:
j := 0
for y := y1; y < y2; y++ {
i := y*img.Stride + x1
for x := x1; x < x2; x++ {
c := img.Pix[i]
d := dst[j : j+4 : j+4]
d[0] = c
d[1] = c
d[2] = c
d[3] = 0xff
j += 4
i++
}
}
case *image.Gray16:
j := 0
for y := y1; y < y2; y++ {
i := y*img.Stride + x1*2
for x := x1; x < x2; x++ {
c := img.Pix[i]
d := dst[j : j+4 : j+4]
d[0] = c
d[1] = c
d[2] = c
d[3] = 0xff
j += 4
i += 2
}
}
case *image.YCbCr:
j := 0
x1 += img.Rect.Min.X
x2 += img.Rect.Min.X
y1 += img.Rect.Min.Y
y2 += img.Rect.Min.Y
hy := img.Rect.Min.Y / 2
hx := img.Rect.Min.X / 2
for y := y1; y < y2; y++ {
iy := (y-img.Rect.Min.Y)*img.YStride + (x1 - img.Rect.Min.X)
var yBase int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio422:
yBase = (y - img.Rect.Min.Y) * img.CStride
case image.YCbCrSubsampleRatio420, image.YCbCrSubsampleRatio440:
yBase = (y/2 - hy) * img.CStride
}
for x := x1; x < x2; x++ {
var ic int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio440:
ic = yBase + (x - img.Rect.Min.X)
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
ic = yBase + (x/2 - hx)
default:
ic = img.COffset(x, y)
}
yy1 := int32(img.Y[iy]) * 0x10101
cb1 := int32(img.Cb[ic]) - 128
cr1 := int32(img.Cr[ic]) - 128
r := yy1 + 91881*cr1
if uint32(r)&0xff000000 == 0 {
r >>= 16
} else {
r = ^(r >> 31)
}
g := yy1 - 22554*cb1 - 46802*cr1
if uint32(g)&0xff000000 == 0 {
g >>= 16
} else {
g = ^(g >> 31)
}
b := yy1 + 116130*cb1
if uint32(b)&0xff000000 == 0 {
b >>= 16
} else {
b = ^(b >> 31)
}
d := dst[j : j+4 : j+4]
d[0] = uint8(r)
d[1] = uint8(g)
d[2] = uint8(b)
d[3] = 0xff
iy++
j += 4
}
}
case *image.Paletted:
j := 0
for y := y1; y < y2; y++ {
i := y*img.Stride + x1
for x := x1; x < x2; x++ {
c := s.palette[img.Pix[i]]
d := dst[j : j+4 : j+4]
d[0] = c.R
d[1] = c.G
d[2] = c.B
d[3] = c.A
j += 4
i++
}
}
default:
j := 0
b := s.image.Bounds()
x1 += b.Min.X
x2 += b.Min.X
y1 += b.Min.Y
y2 += b.Min.Y
for y := y1; y < y2; y++ {
for x := x1; x < x2; x++ {
r16, g16, b16, a16 := s.image.At(x, y).RGBA()
d := dst[j : j+4 : j+4]
switch a16 {
case 0xffff:
d[0] = uint8(r16 >> 8)
d[1] = uint8(g16 >> 8)
d[2] = uint8(b16 >> 8)
d[3] = 0xff
case 0:
d[0] = 0
d[1] = 0
d[2] = 0
d[3] = 0
default:
d[0] = uint8(((r16 * 0xffff) / a16) >> 8)
d[1] = uint8(((g16 * 0xffff) / a16) >> 8)
d[2] = uint8(((b16 * 0xffff) / a16) >> 8)
d[3] = uint8(a16 >> 8)
}
j += 4
}
}
}
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | adjust.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/adjust.go#L10-L32 | go | train | // Grayscale produces a grayscale version of the image. | func Grayscale(img image.Image) *image.NRGBA | // Grayscale produces a grayscale version of the image.
func Grayscale(img image.Image) *image.NRGBA | {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
parallel(0, src.h, func(ys <-chan int) {
for y := range ys {
i := y * dst.Stride
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
for x := 0; x < src.w; x++ {
d := dst.Pix[i : i+3 : i+3]
r := d[0]
g := d[1]
b := d[2]
f := 0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)
y := uint8(f + 0.5)
d[0] = y
d[1] = y
d[2] = y
i += 4
}
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | adjust.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/adjust.go#L35-L52 | go | train | // Invert produces an inverted (negated) version of the image. | func Invert(img image.Image) *image.NRGBA | // Invert produces an inverted (negated) version of the image.
func Invert(img image.Image) *image.NRGBA | {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
parallel(0, src.h, func(ys <-chan int) {
for y := range ys {
i := y * dst.Stride
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
for x := 0; x < src.w; x++ {
d := dst.Pix[i : i+3 : i+3]
d[0] = 255 - d[0]
d[1] = 255 - d[1]
d[2] = 255 - d[2]
i += 4
}
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | adjust.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/adjust.go#L64-L77 | go | train | // AdjustSaturation changes the saturation of the image using the percentage parameter and returns the adjusted image.
// The percentage must be in the range (-100, 100).
// The percentage = 0 gives the original image.
// The percentage = 100 gives the image with the saturation value doubled for each pixel.
// The percentage = -100 gives the image with the saturation value zeroed for each pixel (grayscale).
//
// Examples:
// dstImage = imaging.AdjustSaturation(srcImage, 25) // Increase image saturation by 25%.
// dstImage = imaging.AdjustSaturation(srcImage, -10) // Decrease image saturation by 10%.
// | func AdjustSaturation(img image.Image, percentage float64) *image.NRGBA | // AdjustSaturation changes the saturation of the image using the percentage parameter and returns the adjusted image.
// The percentage must be in the range (-100, 100).
// The percentage = 0 gives the original image.
// The percentage = 100 gives the image with the saturation value doubled for each pixel.
// The percentage = -100 gives the image with the saturation value zeroed for each pixel (grayscale).
//
// Examples:
// dstImage = imaging.AdjustSaturation(srcImage, 25) // Increase image saturation by 25%.
// dstImage = imaging.AdjustSaturation(srcImage, -10) // Decrease image saturation by 10%.
//
func AdjustSaturation(img image.Image, percentage float64) *image.NRGBA | {
percentage = math.Min(math.Max(percentage, -100), 100)
multiplier := 1 + percentage/100
return AdjustFunc(img, func(c color.NRGBA) color.NRGBA {
h, s, l := rgbToHSL(c.R, c.G, c.B)
s *= multiplier
if s > 1 {
s = 1
}
r, g, b := hslToRGB(h, s, l)
return color.NRGBA{r, g, b, c.A}
})
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | adjust.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/adjust.go#L88-L105 | go | train | // AdjustContrast changes the contrast of the image using the percentage parameter and returns the adjusted image.
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
// The percentage = -100 gives solid gray image.
//
// Examples:
//
// dstImage = imaging.AdjustContrast(srcImage, -10) // Decrease image contrast by 10%.
// dstImage = imaging.AdjustContrast(srcImage, 20) // Increase image contrast by 20%.
// | func AdjustContrast(img image.Image, percentage float64) *image.NRGBA | // AdjustContrast changes the contrast of the image using the percentage parameter and returns the adjusted image.
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
// The percentage = -100 gives solid gray image.
//
// Examples:
//
// dstImage = imaging.AdjustContrast(srcImage, -10) // Decrease image contrast by 10%.
// dstImage = imaging.AdjustContrast(srcImage, 20) // Increase image contrast by 20%.
//
func AdjustContrast(img image.Image, percentage float64) *image.NRGBA | {
percentage = math.Min(math.Max(percentage, -100.0), 100.0)
lut := make([]uint8, 256)
v := (100.0 + percentage) / 100.0
for i := 0; i < 256; i++ {
switch {
case 0 <= v && v <= 1:
lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*v) * 255.0)
case 1 < v && v < 2:
lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*(1/(2.0-v))) * 255.0)
default:
lut[i] = uint8(float64(i)/255.0+0.5) * 255
}
}
return adjustLUT(img, lut)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | adjust.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/adjust.go#L116-L126 | go | train | // AdjustBrightness changes the brightness of the image using the percentage parameter and returns the adjusted image.
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
// The percentage = -100 gives solid black image. The percentage = 100 gives solid white image.
//
// Examples:
//
// dstImage = imaging.AdjustBrightness(srcImage, -15) // Decrease image brightness by 15%.
// dstImage = imaging.AdjustBrightness(srcImage, 10) // Increase image brightness by 10%.
// | func AdjustBrightness(img image.Image, percentage float64) *image.NRGBA | // AdjustBrightness changes the brightness of the image using the percentage parameter and returns the adjusted image.
// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
// The percentage = -100 gives solid black image. The percentage = 100 gives solid white image.
//
// Examples:
//
// dstImage = imaging.AdjustBrightness(srcImage, -15) // Decrease image brightness by 15%.
// dstImage = imaging.AdjustBrightness(srcImage, 10) // Increase image brightness by 10%.
//
func AdjustBrightness(img image.Image, percentage float64) *image.NRGBA | {
percentage = math.Min(math.Max(percentage, -100.0), 100.0)
lut := make([]uint8, 256)
shift := 255.0 * percentage / 100.0
for i := 0; i < 256; i++ {
lut[i] = clamp(float64(i) + shift)
}
return adjustLUT(img, lut)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | adjust.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/adjust.go#L136-L145 | go | train | // AdjustGamma performs a gamma correction on the image and returns the adjusted image.
// Gamma parameter must be positive. Gamma = 1.0 gives the original image.
// Gamma less than 1.0 darkens the image and gamma greater than 1.0 lightens it.
//
// Example:
//
// dstImage = imaging.AdjustGamma(srcImage, 0.7)
// | func AdjustGamma(img image.Image, gamma float64) *image.NRGBA | // AdjustGamma performs a gamma correction on the image and returns the adjusted image.
// Gamma parameter must be positive. Gamma = 1.0 gives the original image.
// Gamma less than 1.0 darkens the image and gamma greater than 1.0 lightens it.
//
// Example:
//
// dstImage = imaging.AdjustGamma(srcImage, 0.7)
//
func AdjustGamma(img image.Image, gamma float64) *image.NRGBA | {
e := 1.0 / math.Max(gamma, 0.0001)
lut := make([]uint8, 256)
for i := 0; i < 256; i++ {
lut[i] = clamp(math.Pow(float64(i)/255.0, e) * 255.0)
}
return adjustLUT(img, lut)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | adjust.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/adjust.go#L158-L187 | go | train | // AdjustSigmoid changes the contrast of the image using a sigmoidal function and returns the adjusted image.
// It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail.
// The midpoint parameter is the midpoint of contrast that must be between 0 and 1, typically 0.5.
// The factor parameter indicates how much to increase or decrease the contrast, typically in range (-10, 10).
// If the factor parameter is positive the image contrast is increased otherwise the contrast is decreased.
//
// Examples:
//
// dstImage = imaging.AdjustSigmoid(srcImage, 0.5, 3.0) // Increase the contrast.
// dstImage = imaging.AdjustSigmoid(srcImage, 0.5, -3.0) // Decrease the contrast.
// | func AdjustSigmoid(img image.Image, midpoint, factor float64) *image.NRGBA | // AdjustSigmoid changes the contrast of the image using a sigmoidal function and returns the adjusted image.
// It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail.
// The midpoint parameter is the midpoint of contrast that must be between 0 and 1, typically 0.5.
// The factor parameter indicates how much to increase or decrease the contrast, typically in range (-10, 10).
// If the factor parameter is positive the image contrast is increased otherwise the contrast is decreased.
//
// Examples:
//
// dstImage = imaging.AdjustSigmoid(srcImage, 0.5, 3.0) // Increase the contrast.
// dstImage = imaging.AdjustSigmoid(srcImage, 0.5, -3.0) // Decrease the contrast.
//
func AdjustSigmoid(img image.Image, midpoint, factor float64) *image.NRGBA | {
if factor == 0 {
return Clone(img)
}
lut := make([]uint8, 256)
a := math.Min(math.Max(midpoint, 0.0), 1.0)
b := math.Abs(factor)
sig0 := sigmoid(a, b, 0)
sig1 := sigmoid(a, b, 1)
e := 1.0e-6
if factor > 0 {
for i := 0; i < 256; i++ {
x := float64(i) / 255.0
sigX := sigmoid(a, b, x)
f := (sigX - sig0) / (sig1 - sig0)
lut[i] = clamp(f * 255.0)
}
} else {
for i := 0; i < 256; i++ {
x := float64(i) / 255.0
arg := math.Min(math.Max((sig1-sig0)*x+sig0, e), 1.0-e)
f := a - math.Log(1.0/arg-1.0)/b
lut[i] = clamp(f * 255.0)
}
}
return adjustLUT(img, lut)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | adjust.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/adjust.go#L230-L253 | go | train | // AdjustFunc applies the fn function to each pixel of the img image and returns the adjusted image.
//
// Example:
//
// dstImage = imaging.AdjustFunc(
// srcImage,
// func(c color.NRGBA) color.NRGBA {
// // Shift the red channel by 16.
// r := int(c.R) + 16
// if r > 255 {
// r = 255
// }
// return color.NRGBA{uint8(r), c.G, c.B, c.A}
// }
// )
// | func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGBA | // AdjustFunc applies the fn function to each pixel of the img image and returns the adjusted image.
//
// Example:
//
// dstImage = imaging.AdjustFunc(
// srcImage,
// func(c color.NRGBA) color.NRGBA {
// // Shift the red channel by 16.
// r := int(c.R) + 16
// if r > 255 {
// r = 255
// }
// return color.NRGBA{uint8(r), c.G, c.B, c.A}
// }
// )
//
func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGBA | {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
parallel(0, src.h, func(ys <-chan int) {
for y := range ys {
i := y * dst.Stride
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
for x := 0; x < src.w; x++ {
d := dst.Pix[i : i+4 : i+4]
r := d[0]
g := d[1]
b := d[2]
a := d[3]
c := fn(color.NRGBA{r, g, b, a})
d[0] = c.R
d[1] = c.G
d[2] = c.B
d[3] = c.A
i += 4
}
}
})
return dst
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L54-L83 | go | train | // Decode reads an image from r. | func Decode(r io.Reader, opts ...DecodeOption) (image.Image, error) | // Decode reads an image from r.
func Decode(r io.Reader, opts ...DecodeOption) (image.Image, error) | {
cfg := defaultDecodeConfig
for _, option := range opts {
option(&cfg)
}
if !cfg.autoOrientation {
img, _, err := image.Decode(r)
return img, err
}
var orient orientation
pr, pw := io.Pipe()
r = io.TeeReader(r, pw)
done := make(chan struct{})
go func() {
defer close(done)
orient = readOrientation(pr)
io.Copy(ioutil.Discard, pr)
}()
img, _, err := image.Decode(r)
pw.Close()
<-done
if err != nil {
return nil, err
}
return fixOrientation(img, orient), nil
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L95-L102 | go | train | // Open loads an image from file.
//
// Examples:
//
// // Load an image from file.
// img, err := imaging.Open("test.jpg")
//
// // Load an image and transform it depending on the EXIF orientation tag (if present).
// img, err := imaging.Open("test.jpg", imaging.AutoOrientation(true))
// | func Open(filename string, opts ...DecodeOption) (image.Image, error) | // Open loads an image from file.
//
// Examples:
//
// // Load an image from file.
// img, err := imaging.Open("test.jpg")
//
// // Load an image and transform it depending on the EXIF orientation tag (if present).
// img, err := imaging.Open("test.jpg", imaging.AutoOrientation(true))
//
func Open(filename string, opts ...DecodeOption) (image.Image, error) | {
file, err := fs.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
return Decode(file, opts...)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L143-L148 | go | train | // FormatFromExtension parses image format from filename extension:
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported. | func FormatFromExtension(ext string) (Format, error) | // FormatFromExtension parses image format from filename extension:
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
func FormatFromExtension(ext string) (Format, error) | {
if f, ok := formatExts[strings.ToLower(strings.TrimPrefix(ext, "."))]; ok {
return f, nil
}
return -1, ErrUnsupportedFormat
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L152-L155 | go | train | // FormatFromFilename parses image format from filename:
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported. | func FormatFromFilename(filename string) (Format, error) | // FormatFromFilename parses image format from filename:
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
func FormatFromFilename(filename string) (Format, error) | {
ext := filepath.Ext(filename)
return FormatFromExtension(ext)
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L194-L198 | go | train | // GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce
// a palette of the GIF-encoded image. | func GIFQuantizer(quantizer draw.Quantizer) EncodeOption | // GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce
// a palette of the GIF-encoded image.
func GIFQuantizer(quantizer draw.Quantizer) EncodeOption | {
return func(c *encodeConfig) {
c.gifQuantizer = quantizer
}
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L202-L206 | go | train | // GIFDrawer returns an EncodeOption that sets the drawer that is used to convert
// the source image to the desired palette of the GIF-encoded image. | func GIFDrawer(drawer draw.Drawer) EncodeOption | // GIFDrawer returns an EncodeOption that sets the drawer that is used to convert
// the source image to the desired palette of the GIF-encoded image.
func GIFDrawer(drawer draw.Drawer) EncodeOption | {
return func(c *encodeConfig) {
c.gifDrawer = drawer
}
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L210-L214 | go | train | // PNGCompressionLevel returns an EncodeOption that sets the compression level
// of the PNG-encoded image. Default is png.DefaultCompression. | func PNGCompressionLevel(level png.CompressionLevel) EncodeOption | // PNGCompressionLevel returns an EncodeOption that sets the compression level
// of the PNG-encoded image. Default is png.DefaultCompression.
func PNGCompressionLevel(level png.CompressionLevel) EncodeOption | {
return func(c *encodeConfig) {
c.pngCompressionLevel = level
}
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L217-L254 | go | train | // Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP). | func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) error | // Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) error | {
cfg := defaultEncodeConfig
for _, option := range opts {
option(&cfg)
}
switch format {
case JPEG:
if nrgba, ok := img.(*image.NRGBA); ok && nrgba.Opaque() {
rgba := &image.RGBA{
Pix: nrgba.Pix,
Stride: nrgba.Stride,
Rect: nrgba.Rect,
}
return jpeg.Encode(w, rgba, &jpeg.Options{Quality: cfg.jpegQuality})
}
return jpeg.Encode(w, img, &jpeg.Options{Quality: cfg.jpegQuality})
case PNG:
encoder := png.Encoder{CompressionLevel: cfg.pngCompressionLevel}
return encoder.Encode(w, img)
case GIF:
return gif.Encode(w, img, &gif.Options{
NumColors: cfg.gifNumColors,
Quantizer: cfg.gifQuantizer,
Drawer: cfg.gifDrawer,
})
case TIFF:
return tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
case BMP:
return bmp.Encode(w, img)
}
return ErrUnsupportedFormat
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L268-L283 | go | train | // Save saves the image to file with the specified filename.
// The format is determined from the filename extension:
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
//
// Examples:
//
// // Save the image as PNG.
// err := imaging.Save(img, "out.png")
//
// // Save the image as JPEG with optional quality parameter set to 80.
// err := imaging.Save(img, "out.jpg", imaging.JPEGQuality(80))
// | func Save(img image.Image, filename string, opts ...EncodeOption) (err error) | // Save saves the image to file with the specified filename.
// The format is determined from the filename extension:
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
//
// Examples:
//
// // Save the image as PNG.
// err := imaging.Save(img, "out.png")
//
// // Save the image as JPEG with optional quality parameter set to 80.
// err := imaging.Save(img, "out.jpg", imaging.JPEGQuality(80))
//
func Save(img image.Image, filename string, opts ...EncodeOption) (err error) | {
f, err := FormatFromFilename(filename)
if err != nil {
return err
}
file, err := fs.Create(filename)
if err != nil {
return err
}
err = Encode(file, img, f, opts...)
errc := file.Close()
if err == nil {
err = errc
}
return err
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L305-L422 | go | train | // readOrientation tries to read the orientation EXIF flag from image data in r.
// If the EXIF data block is not found or the orientation flag is not found
// or any other error occures while reading the data, it returns the
// orientationUnspecified (0) value. | func readOrientation(r io.Reader) orientation | // readOrientation tries to read the orientation EXIF flag from image data in r.
// If the EXIF data block is not found or the orientation flag is not found
// or any other error occures while reading the data, it returns the
// orientationUnspecified (0) value.
func readOrientation(r io.Reader) orientation | {
const (
markerSOI = 0xffd8
markerAPP1 = 0xffe1
exifHeader = 0x45786966
byteOrderBE = 0x4d4d
byteOrderLE = 0x4949
orientationTag = 0x0112
)
// Check if JPEG SOI marker is present.
var soi uint16
if err := binary.Read(r, binary.BigEndian, &soi); err != nil {
return orientationUnspecified
}
if soi != markerSOI {
return orientationUnspecified // Missing JPEG SOI marker.
}
// Find JPEG APP1 marker.
for {
var marker, size uint16
if err := binary.Read(r, binary.BigEndian, &marker); err != nil {
return orientationUnspecified
}
if err := binary.Read(r, binary.BigEndian, &size); err != nil {
return orientationUnspecified
}
if marker>>8 != 0xff {
return orientationUnspecified // Invalid JPEG marker.
}
if marker == markerAPP1 {
break
}
if size < 2 {
return orientationUnspecified // Invalid block size.
}
if _, err := io.CopyN(ioutil.Discard, r, int64(size-2)); err != nil {
return orientationUnspecified
}
}
// Check if EXIF header is present.
var header uint32
if err := binary.Read(r, binary.BigEndian, &header); err != nil {
return orientationUnspecified
}
if header != exifHeader {
return orientationUnspecified
}
if _, err := io.CopyN(ioutil.Discard, r, 2); err != nil {
return orientationUnspecified
}
// Read byte order information.
var (
byteOrderTag uint16
byteOrder binary.ByteOrder
)
if err := binary.Read(r, binary.BigEndian, &byteOrderTag); err != nil {
return orientationUnspecified
}
switch byteOrderTag {
case byteOrderBE:
byteOrder = binary.BigEndian
case byteOrderLE:
byteOrder = binary.LittleEndian
default:
return orientationUnspecified // Invalid byte order flag.
}
if _, err := io.CopyN(ioutil.Discard, r, 2); err != nil {
return orientationUnspecified
}
// Skip the EXIF offset.
var offset uint32
if err := binary.Read(r, byteOrder, &offset); err != nil {
return orientationUnspecified
}
if offset < 8 {
return orientationUnspecified // Invalid offset value.
}
if _, err := io.CopyN(ioutil.Discard, r, int64(offset-8)); err != nil {
return orientationUnspecified
}
// Read the number of tags.
var numTags uint16
if err := binary.Read(r, byteOrder, &numTags); err != nil {
return orientationUnspecified
}
// Find the orientation tag.
for i := 0; i < int(numTags); i++ {
var tag uint16
if err := binary.Read(r, byteOrder, &tag); err != nil {
return orientationUnspecified
}
if tag != orientationTag {
if _, err := io.CopyN(ioutil.Discard, r, 10); err != nil {
return orientationUnspecified
}
continue
}
if _, err := io.CopyN(ioutil.Discard, r, 6); err != nil {
return orientationUnspecified
}
var val uint16
if err := binary.Read(r, byteOrder, &val); err != nil {
return orientationUnspecified
}
if val < 1 || val > 8 {
return orientationUnspecified // Invalid tag value.
}
return orientation(val)
}
return orientationUnspecified // Missing orientation tag.
} |
disintegration/imaging | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | io.go | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L425-L444 | go | train | // fixOrientation applies a transform to img corresponding to the given orientation flag. | func fixOrientation(img image.Image, o orientation) image.Image | // fixOrientation applies a transform to img corresponding to the given orientation flag.
func fixOrientation(img image.Image, o orientation) image.Image | {
switch o {
case orientationNormal:
case orientationFlipH:
img = FlipH(img)
case orientationFlipV:
img = FlipV(img)
case orientationRotate90:
img = Rotate90(img)
case orientationRotate180:
img = Rotate180(img)
case orientationRotate270:
img = Rotate270(img)
case orientationTranspose:
img = Transpose(img)
case orientationTransverse:
img = Transverse(img)
}
return img
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | tcp/transport.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/tcp/transport.go#L26-L33 | go | train | // NewTLSTransport returns an initialized TLS-ecrypted Transport. | func NewTLSTransport(certFile, keyPath string, skipVerify bool) *Transport | // NewTLSTransport returns an initialized TLS-ecrypted Transport.
func NewTLSTransport(certFile, keyPath string, skipVerify bool) *Transport | {
return &Transport{
certFile: certFile,
certKey: keyPath,
remoteEncrypted: true,
skipVerify: skipVerify,
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | tcp/transport.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/tcp/transport.go#L36-L51 | go | train | // Open opens the transport, binding to the supplied address. | func (t *Transport) Open(addr string) error | // Open opens the transport, binding to the supplied address.
func (t *Transport) Open(addr string) error | {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
if t.certFile != "" {
config, err := createTLSConfig(t.certFile, t.certKey)
if err != nil {
return err
}
ln = tls.NewListener(ln, config)
}
t.ln = ln
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | tcp/transport.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/tcp/transport.go#L54-L70 | go | train | // Dial opens a network connection. | func (t *Transport) Dial(addr string, timeout time.Duration) (net.Conn, error) | // Dial opens a network connection.
func (t *Transport) Dial(addr string, timeout time.Duration) (net.Conn, error) | {
dialer := &net.Dialer{Timeout: timeout}
var err error
var conn net.Conn
if t.remoteEncrypted {
conf := &tls.Config{
InsecureSkipVerify: t.skipVerify,
}
fmt.Println("doing a TLS dial")
conn, err = tls.DialWithDialer(dialer, "tcp", addr, conf)
} else {
conn, err = dialer.Dial("tcp", addr)
}
return conn, err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | tcp/transport.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/tcp/transport.go#L73-L79 | go | train | // Accept waits for the next connection. | func (t *Transport) Accept() (net.Conn, error) | // Accept waits for the next connection.
func (t *Transport) Accept() (net.Conn, error) | {
c, err := t.ln.Accept()
if err != nil {
fmt.Println("error accepting: ", err.Error())
}
return c, err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | cmd/rqbench/http.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqbench/http.go#L28-L45 | go | train | // Prepare prepares the tester for execution. | func (h *HTTPTester) Prepare(stmt string, bSz int, tx bool) error | // Prepare prepares the tester for execution.
func (h *HTTPTester) Prepare(stmt string, bSz int, tx bool) error | {
s := make([]string, bSz)
for i := 0; i < len(s); i++ {
s[i] = stmt
}
b, err := json.Marshal(s)
if err != nil {
return err
}
h.br = bytes.NewReader(b)
if tx {
h.url = h.url + "?transaction"
}
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | cmd/rqbench/http.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqbench/http.go#L48-L64 | go | train | // Once executes a single test request. | func (h *HTTPTester) Once() (time.Duration, error) | // Once executes a single test request.
func (h *HTTPTester) Once() (time.Duration, error) | {
h.br.Seek(0, io.SeekStart)
start := time.Now()
resp, err := h.client.Post(h.url, "application/json", h.br)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("received %s", resp.Status)
}
dur := time.Since(start)
return dur, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/peers.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/peers.go#L19-L39 | go | train | // NumPeers returns the number of peers indicated by the config files
// within raftDir.
//
// This code makes assumptions about how the Raft module works. | func NumPeers(raftDir string) (int, error) | // NumPeers returns the number of peers indicated by the config files
// within raftDir.
//
// This code makes assumptions about how the Raft module works.
func NumPeers(raftDir string) (int, error) | {
// Read the file
buf, err := ioutil.ReadFile(filepath.Join(raftDir, jsonPeerPath))
if err != nil && !os.IsNotExist(err) {
return 0, err
}
// Check for no peers
if len(buf) == 0 {
return 0, nil
}
// Decode the peers
var peerSet []string
dec := json.NewDecoder(bytes.NewReader(buf))
if err := dec.Decode(&peerSet); err != nil {
return 0, err
}
return len(peerSet), nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/peers.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/peers.go#L43-L49 | go | train | // JoinAllowed returns whether the config files within raftDir indicate
// that the node can join a cluster. | func JoinAllowed(raftDir string) (bool, error) | // JoinAllowed returns whether the config files within raftDir indicate
// that the node can join a cluster.
func JoinAllowed(raftDir string) (bool, error) | {
n, err := NumPeers(raftDir)
if err != nil {
return false, err
}
return n <= 1, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L220-L240 | go | train | // New returns a new Store. | func New(ln Listener, c *StoreConfig) *Store | // New returns a new Store.
func New(ln Listener, c *StoreConfig) *Store | {
logger := c.Logger
if logger == nil {
logger = log.New(os.Stderr, "[store] ", log.LstdFlags)
}
return &Store{
ln: ln,
raftDir: c.Dir,
raftID: c.ID,
dbConf: c.DBConf,
dbPath: filepath.Join(c.Dir, sqliteFile),
randSrc: rand.New(rand.NewSource(time.Now().UnixNano())),
conns: make(map[uint64]*Connection),
done: make(chan struct{}, 1),
meta: make(map[string]map[string]string),
logger: logger,
ApplyTimeout: applyTimeout,
connPollPeriod: connectionPollPeriod,
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L244-L327 | go | train | // Open opens the store. If enableSingle is set, and there are no existing peers,
// then this node becomes the first node, and therefore leader, of the cluster. | func (s *Store) Open(enableSingle bool) error | // Open opens the store. If enableSingle is set, and there are no existing peers,
// then this node becomes the first node, and therefore leader, of the cluster.
func (s *Store) Open(enableSingle bool) error | {
s.closedMu.Lock()
defer s.closedMu.Unlock()
if s.closed {
return ErrStoreInvalidState
}
s.logger.Printf("opening store with node ID %s", s.raftID)
s.logger.Printf("ensuring directory at %s exists", s.raftDir)
if err := os.MkdirAll(s.raftDir, 0755); err != nil {
return err
}
// Create underlying database.
if err := s.createDatabase(); err != nil {
return err
}
// Get utility connection to database.
conn, err := s.db.Connect()
if err != nil {
return err
}
s.dbConn = conn
s.conns[defaultConnID] = NewConnection(s.dbConn, s, defaultConnID, 0, 0)
// Is this a brand new node?
newNode := !pathExists(filepath.Join(s.raftDir, "raft.db"))
// Create Raft-compatible network layer.
s.raftTn = raft.NewNetworkTransport(NewTransport(s.ln),
connectionPoolCount, connectionTimeout, nil)
// Get the Raft configuration for this store.
config := s.raftConfig()
config.LocalID = raft.ServerID(s.raftID)
config.Logger = log.New(os.Stderr, "[raft] ", log.LstdFlags)
// Create the snapshot store. This allows Raft to truncate the log.
snapshots, err := raft.NewFileSnapshotStore(s.raftDir, retainSnapshotCount, os.Stderr)
if err != nil {
return fmt.Errorf("file snapshot store: %s", err)
}
// Create the log store and stable store.
s.boltStore, err = raftboltdb.NewBoltStore(filepath.Join(s.raftDir, "raft.db"))
if err != nil {
return fmt.Errorf("new bolt store: %s", err)
}
s.raftStable = s.boltStore
s.raftLog, err = raft.NewLogCache(raftLogCacheSize, s.boltStore)
if err != nil {
return fmt.Errorf("new cached store: %s", err)
}
// Instantiate the Raft system.
ra, err := raft.NewRaft(config, s, s.raftLog, s.raftStable, snapshots, s.raftTn)
if err != nil {
return fmt.Errorf("new raft: %s", err)
}
if enableSingle && newNode {
s.logger.Printf("bootstrap needed")
configuration := raft.Configuration{
Servers: []raft.Server{
{
ID: config.LocalID,
Address: s.raftTn.LocalAddr(),
},
},
}
ra.BootstrapCluster(configuration)
} else {
s.logger.Printf("no bootstrap needed")
}
s.raft = ra
// Start connection monitoring
s.checkConnections()
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L336-L381 | go | train | // Connect returns a new connection to the database. Changes made to the database
// through this connection are applied via the Raft consensus system. The Store
// must have been opened first. Must be called on the leader or an error will
// we returned.
//
// Any connection returned by this call are READ_COMMITTED isolated from all
// other connections, including the connection built-in to the Store itself. | func (s *Store) Connect(opt *ConnectionOptions) (*Connection, error) | // Connect returns a new connection to the database. Changes made to the database
// through this connection are applied via the Raft consensus system. The Store
// must have been opened first. Must be called on the leader or an error will
// we returned.
//
// Any connection returned by this call are READ_COMMITTED isolated from all
// other connections, including the connection built-in to the Store itself.
func (s *Store) Connect(opt *ConnectionOptions) (*Connection, error) | {
// Randomly-selected connection ID must be part of command so
// that all nodes use the same value as connection ID.
connID := func() uint64 {
s.connsMu.Lock()
defer s.connsMu.Unlock()
for {
// Make sure we get an unused ID.
id := s.randSrc.Uint64()
if _, ok := s.conns[id]; !ok {
s.conns[id] = nil
return id
}
}
}()
var it time.Duration
var tt time.Duration
if opt != nil {
it = opt.IdleTimeout
tt = opt.TxTimeout
}
d := &connectionSub{connID, it, tt}
cmd, err := newCommand(connect, d)
if err != nil {
return nil, err
}
b, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return nil, ErrNotLeader
}
return nil, e.Error()
}
s.connsMu.RLock()
defer s.connsMu.RUnlock()
stats.Add(numConnects, 1)
return s.conns[connID], nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L388-L390 | go | train | // Execute executes queries that return no rows, but do modify the database.
// Changes made to the database through this call are applied via the Raft
// consensus system. The Store must have been opened first. Must be called
// on the leader or an error will we returned. The changes are made using
// the database connection built-in to the Store. | func (s *Store) Execute(ex *ExecuteRequest) (*ExecuteResponse, error) | // Execute executes queries that return no rows, but do modify the database.
// Changes made to the database through this call are applied via the Raft
// consensus system. The Store must have been opened first. Must be called
// on the leader or an error will we returned. The changes are made using
// the database connection built-in to the Store.
func (s *Store) Execute(ex *ExecuteRequest) (*ExecuteResponse, error) | {
return s.execute(nil, ex)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L395-L397 | go | train | // ExecuteOrAbort executes the requests, but aborts any active transaction
// on the underlying database in the case of any error. Any changes are made
// using the database connection built-in to the Store. | func (s *Store) ExecuteOrAbort(ex *ExecuteRequest) (resp *ExecuteResponse, retErr error) | // ExecuteOrAbort executes the requests, but aborts any active transaction
// on the underlying database in the case of any error. Any changes are made
// using the database connection built-in to the Store.
func (s *Store) ExecuteOrAbort(ex *ExecuteRequest) (resp *ExecuteResponse, retErr error) | {
return s.executeOrAbort(nil, ex)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L403-L405 | go | train | // Query executes queries that return rows, and do not modify the database.
// The queries are made using the database connection built-in to the Store.
// Depending on the read consistency requested, it may or may not need to be
// called on the leader. | func (s *Store) Query(qr *QueryRequest) (*QueryResponse, error) | // Query executes queries that return rows, and do not modify the database.
// The queries are made using the database connection built-in to the Store.
// Depending on the read consistency requested, it may or may not need to be
// called on the leader.
func (s *Store) Query(qr *QueryRequest) (*QueryResponse, error) | {
return s.query(nil, qr)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L409-L448 | go | train | // Close closes the store. If wait is true, waits for a graceful shutdown.
// Once closed, a Store may not be re-opened. | func (s *Store) Close(wait bool) error | // Close closes the store. If wait is true, waits for a graceful shutdown.
// Once closed, a Store may not be re-opened.
func (s *Store) Close(wait bool) error | {
s.closedMu.Lock()
defer s.closedMu.Unlock()
if s.closed {
return nil
}
defer func() {
s.closed = true
}()
close(s.done)
s.wg.Wait()
// XXX CLOSE OTHER CONNECTIONS
if err := s.dbConn.Close(); err != nil {
return err
}
s.dbConn = nil
s.db = nil
if s.raft != nil {
f := s.raft.Shutdown()
if wait {
if e := f.(raft.Future); e.Error() != nil {
return e.Error()
}
}
s.raft = nil
}
if s.boltStore != nil {
if err := s.boltStore.Close(); err != nil {
return err
}
s.boltStore = nil
}
s.raftLog = nil
s.raftStable = nil
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L452-L461 | go | train | // WaitForApplied waits for all Raft log entries to to be applied to the
// underlying database. | func (s *Store) WaitForApplied(timeout time.Duration) error | // WaitForApplied waits for all Raft log entries to to be applied to the
// underlying database.
func (s *Store) WaitForApplied(timeout time.Duration) error | {
if timeout == 0 {
return nil
}
s.logger.Printf("waiting for up to %s for application of initial logs", timeout)
if err := s.WaitForAppliedIndex(s.raft.LastIndex(), timeout); err != nil {
return ErrOpenTimeout
}
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L469-L483 | go | train | // State returns the current node's Raft state | func (s *Store) State() ClusterState | // State returns the current node's Raft state
func (s *Store) State() ClusterState | {
state := s.raft.State()
switch state {
case raft.Leader:
return Leader
case raft.Candidate:
return Candidate
case raft.Follower:
return Follower
case raft.Shutdown:
return Shutdown
default:
return Unknown
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L501-L506 | go | train | // Connection returns the connection for the given ID. | func (s *Store) Connection(id uint64) (*Connection, bool) | // Connection returns the connection for the given ID.
func (s *Store) Connection(id uint64) (*Connection, bool) | {
s.connsMu.RLock()
defer s.connsMu.RUnlock()
c, ok := s.conns[id]
return c, ok
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L516-L530 | go | train | // LeaderID returns the node ID of the Raft leader. Returns a
// blank string if there is no leader, or an error. | func (s *Store) LeaderID() (string, error) | // LeaderID returns the node ID of the Raft leader. Returns a
// blank string if there is no leader, or an error.
func (s *Store) LeaderID() (string, error) | {
addr := s.LeaderAddr()
configFuture := s.raft.GetConfiguration()
if err := configFuture.Error(); err != nil {
s.logger.Printf("failed to get raft configuration: %v", err)
return "", err
}
for _, srv := range configFuture.Configuration().Servers {
if srv.Address == raft.ServerAddress(addr) {
return string(srv.ID), nil
}
}
return "", nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L533-L550 | go | train | // Nodes returns the slice of nodes in the cluster, sorted by ID ascending. | func (s *Store) Nodes() ([]*Server, error) | // Nodes returns the slice of nodes in the cluster, sorted by ID ascending.
func (s *Store) Nodes() ([]*Server, error) | {
f := s.raft.GetConfiguration()
if f.Error() != nil {
return nil, f.Error()
}
rs := f.Configuration().Servers
servers := make([]*Server, len(rs))
for i := range rs {
servers[i] = &Server{
ID: string(rs[i].ID),
Addr: string(rs[i].Address),
}
}
sort.Sort(Servers(servers))
return servers, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L553-L570 | go | train | // WaitForLeader blocks until a leader is detected, or the timeout expires. | func (s *Store) WaitForLeader(timeout time.Duration) (string, error) | // WaitForLeader blocks until a leader is detected, or the timeout expires.
func (s *Store) WaitForLeader(timeout time.Duration) (string, error) | {
tck := time.NewTicker(leaderWaitDelay)
defer tck.Stop()
tmr := time.NewTimer(timeout)
defer tmr.Stop()
for {
select {
case <-tck.C:
l := s.LeaderAddr()
if l != "" {
return l, nil
}
case <-tmr.C:
return "", fmt.Errorf("timeout expired")
}
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L574-L590 | go | train | // WaitForAppliedIndex blocks until a given log index has been applied,
// or the timeout expires. | func (s *Store) WaitForAppliedIndex(idx uint64, timeout time.Duration) error | // WaitForAppliedIndex blocks until a given log index has been applied,
// or the timeout expires.
func (s *Store) WaitForAppliedIndex(idx uint64, timeout time.Duration) error | {
tck := time.NewTicker(appliedWaitDelay)
defer tck.Stop()
tmr := time.NewTimer(timeout)
defer tmr.Stop()
for {
select {
case <-tck.C:
if s.raft.AppliedIndex() >= idx {
return nil
}
case <-tmr.C:
return fmt.Errorf("timeout expired")
}
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L593-L669 | go | train | // Stats returns stats for the store. | func (s *Store) Stats() (map[string]interface{}, error) | // Stats returns stats for the store.
func (s *Store) Stats() (map[string]interface{}, error) | {
fkEnabled, err := s.dbConn.FKConstraints()
if err != nil {
return nil, err
}
dbStatus := map[string]interface{}{
"dsn": s.dbConf.DSN,
"fk_constraints": enabledFromBool(fkEnabled),
"version": sdb.DBVersion,
}
if !s.dbConf.Memory {
dbStatus["path"] = s.dbPath
stat, err := os.Stat(s.dbPath)
if err != nil {
return nil, err
}
dbStatus["size"] = stat.Size()
} else {
dbStatus["path"] = ":memory:"
}
nodes, err := s.Nodes()
if err != nil {
return nil, err
}
leaderID, err := s.LeaderID()
if err != nil {
return nil, err
}
status := map[string]interface{}{
"node_id": s.raftID,
"raft": s.raft.Stats(),
"addr": s.Addr(),
"leader": map[string]string{
"node_id": leaderID,
"addr": s.LeaderAddr(),
},
"apply_timeout": s.ApplyTimeout.String(),
"heartbeat_timeout": s.HeartbeatTimeout.String(),
"snapshot_threshold": s.SnapshotThreshold,
"conn_poll_period": s.connPollPeriod.String(),
"metadata": s.meta,
"nodes": nodes,
"dir": s.raftDir,
"sqlite3": dbStatus,
"db_conf": s.dbConf,
}
// Add connections status
if err := func() error {
s.connsMu.RLock()
defer s.connsMu.RUnlock()
if len(s.conns) > 1 {
conns := make([]interface{}, len(s.conns)-1)
ci := 0
for id, c := range s.conns {
if id == defaultConnID {
continue
}
stats, err := c.Stats()
if err != nil {
return err
}
conns[ci] = stats
ci++
}
status["connections"] = conns
}
return nil
}(); err != nil {
return nil, err
}
return status, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L676-L699 | go | train | // Backup writes a snapshot of the underlying database to dst
//
// If leader is true, this operation is performed with a read consistency
// level equivalent to "weak". Otherwise no guarantees are made about the
// read consistency level. | func (s *Store) Backup(leader bool, fmt BackupFormat, dst io.Writer) error | // Backup writes a snapshot of the underlying database to dst
//
// If leader is true, this operation is performed with a read consistency
// level equivalent to "weak". Otherwise no guarantees are made about the
// read consistency level.
func (s *Store) Backup(leader bool, fmt BackupFormat, dst io.Writer) error | {
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
if leader && s.raft.State() != raft.Leader {
return ErrNotLeader
}
var err error
if fmt == BackupBinary {
err = s.database(leader, dst)
if err != nil {
return err
}
} else if fmt == BackupSQL {
if err := s.dbConn.Dump(dst); err != nil {
return err
}
} else {
return ErrInvalidBackupFormat
}
stats.Add(numBackups, 1)
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L703-L747 | go | train | // Join joins a node, identified by id and located at addr, to this store.
// The node must be ready to respond to Raft communications at that address. | func (s *Store) Join(id, addr string, metadata map[string]string) error | // Join joins a node, identified by id and located at addr, to this store.
// The node must be ready to respond to Raft communications at that address.
func (s *Store) Join(id, addr string, metadata map[string]string) error | {
s.logger.Printf("received request to join node at %s", addr)
if s.raft.State() != raft.Leader {
return ErrNotLeader
}
configFuture := s.raft.GetConfiguration()
if err := configFuture.Error(); err != nil {
s.logger.Printf("failed to get raft configuration: %v", err)
return err
}
for _, srv := range configFuture.Configuration().Servers {
// If a node already exists with either the joining node's ID or address,
// that node may need to be removed from the config first.
if srv.ID == raft.ServerID(id) || srv.Address == raft.ServerAddress(addr) {
// However if *both* the ID and the address are the same, the no
// join is actually needed.
if srv.Address == raft.ServerAddress(addr) && srv.ID == raft.ServerID(id) {
s.logger.Printf("node %s at %s already member of cluster, ignoring join request",
id, addr)
return nil
}
if err := s.remove(id); err != nil {
s.logger.Printf("failed to remove node: %v", err)
return err
}
}
}
f := s.raft.AddVoter(raft.ServerID(id), raft.ServerAddress(addr), 0, 0)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return e.Error()
}
if err := s.setMetadata(id, metadata); err != nil {
return err
}
s.logger.Printf("node at %s joined successfully", addr)
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L750-L759 | go | train | // Remove removes a node from the store, specified by ID. | func (s *Store) Remove(id string) error | // Remove removes a node from the store, specified by ID.
func (s *Store) Remove(id string) error | {
s.logger.Printf("received request to remove node %s", id)
if err := s.remove(id); err != nil {
s.logger.Printf("failed to remove node %s: %s", id, err.Error())
return err
}
s.logger.Printf("node %s removed successfully", id)
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L762-L774 | go | train | // Metadata returns the value for a given key, for a given node ID. | func (s *Store) Metadata(id, key string) string | // Metadata returns the value for a given key, for a given node ID.
func (s *Store) Metadata(id, key string) string | {
s.metaMu.RLock()
defer s.metaMu.RUnlock()
if _, ok := s.meta[id]; !ok {
return ""
}
v, ok := s.meta[id][key]
if ok {
return v
}
return ""
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L778-L780 | go | train | // SetMetadata adds the metadata md to any existing metadata for
// this node. | func (s *Store) SetMetadata(md map[string]string) error | // SetMetadata adds the metadata md to any existing metadata for
// this node.
func (s *Store) SetMetadata(md map[string]string) error | {
return s.setMetadata(s.raftID, md)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L784-L821 | go | train | // setMetadata adds the metadata md to any existing metadata for
// the given node ID. | func (s *Store) setMetadata(id string, md map[string]string) error | // setMetadata adds the metadata md to any existing metadata for
// the given node ID.
func (s *Store) setMetadata(id string, md map[string]string) error | {
// Check local data first.
if func() bool {
s.metaMu.RLock()
defer s.metaMu.RUnlock()
if _, ok := s.meta[id]; ok {
for k, v := range md {
if s.meta[id][k] != v {
return false
}
}
return true
}
return false
}() {
// Local data is same as data being pushed in,
// nothing to do.
return nil
}
c, err := newMetadataSetCommand(id, md)
if err != nil {
return err
}
b, err := json.Marshal(c)
if err != nil {
return err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return e.Error()
}
return f.Response().(*fsmGenericResponse).error
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L825-L847 | go | train | // disconnect removes a connection to the database, a connection
// which was previously established via Raft consensus. | func (s *Store) disconnect(c *Connection) error | // disconnect removes a connection to the database, a connection
// which was previously established via Raft consensus.
func (s *Store) disconnect(c *Connection) error | {
d := &connectionSub{
ConnID: c.ID,
}
cmd, err := newCommand(disconnect, d)
if err != nil {
return err
}
b, err := json.Marshal(cmd)
if err != nil {
return err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return e.Error()
}
stats.Add(numDisconnects, 1)
return f.Response().(*fsmGenericResponse).error
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L851-L896 | go | train | // Execute executes queries that return no rows, but do modify the database. If connection
// is nil then the utility connection is used. | func (s *Store) execute(c *Connection, ex *ExecuteRequest) (*ExecuteResponse, error) | // Execute executes queries that return no rows, but do modify the database. If connection
// is nil then the utility connection is used.
func (s *Store) execute(c *Connection, ex *ExecuteRequest) (*ExecuteResponse, error) | {
if c == nil {
s.connsMu.RLock()
c = s.conns[defaultConnID]
s.connsMu.RUnlock()
}
c.SetLastUsedNow()
start := time.Now()
d := &databaseSub{
ConnID: c.ID,
Atomic: ex.Atomic,
Queries: ex.Queries,
Timings: ex.Timings,
}
cmd, err := newCommand(execute, d)
if err != nil {
return nil, err
}
b, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return nil, ErrNotLeader
}
return nil, e.Error()
}
switch r := f.Response().(type) {
case *fsmExecuteResponse:
return &ExecuteResponse{
Results: r.results,
Time: time.Since(start).Seconds(),
Raft: RaftResponse{f.Index(), s.raftID},
}, r.error
case *fsmGenericResponse:
return nil, r.error
default:
panic("unsupported type")
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L927-L986 | go | train | // Query executes queries that return rows, and do not modify the database. If
// connection is nil, then the utility connection is used. | func (s *Store) query(c *Connection, qr *QueryRequest) (*QueryResponse, error) | // Query executes queries that return rows, and do not modify the database. If
// connection is nil, then the utility connection is used.
func (s *Store) query(c *Connection, qr *QueryRequest) (*QueryResponse, error) | {
if c == nil {
s.connsMu.RLock()
c = s.conns[defaultConnID]
s.connsMu.RUnlock()
}
c.SetLastUsedNow()
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
start := time.Now()
if qr.Lvl == Strong {
d := &databaseSub{
ConnID: c.ID,
Atomic: qr.Atomic,
Queries: qr.Queries,
Timings: qr.Timings,
}
cmd, err := newCommand(query, d)
if err != nil {
return nil, err
}
b, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return nil, ErrNotLeader
}
return nil, e.Error()
}
switch r := f.Response().(type) {
case *fsmQueryResponse:
return &QueryResponse{
Rows: r.rows,
Time: time.Since(start).Seconds(),
Raft: &RaftResponse{f.Index(), s.raftID},
}, r.error
case *fsmGenericResponse:
return nil, r.error
default:
panic("unsupported type")
}
}
if qr.Lvl == Weak && s.raft.State() != raft.Leader {
return nil, ErrNotLeader
}
r, err := c.db.Query(qr.Queries, qr.Atomic, qr.Timings)
return &QueryResponse{
Rows: r,
Time: time.Since(start).Seconds(),
}, err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L989-L1011 | go | train | // createDatabase creates the the in-memory or file-based database. | func (s *Store) createDatabase() error | // createDatabase creates the the in-memory or file-based database.
func (s *Store) createDatabase() error | {
var db *sdb.DB
var err error
if !s.dbConf.Memory {
// as it will be rebuilt from (possibly) a snapshot and committed log entries.
if err := os.Remove(s.dbPath); err != nil && !os.IsNotExist(err) {
return err
}
db, err = sdb.New(s.dbPath, s.dbConf.DSN, false)
if err != nil {
return err
}
s.logger.Println("SQLite database opened at", s.dbPath)
} else {
db, err = sdb.New(s.dbPath, s.dbConf.DSN, true)
if err != nil {
return err
}
s.logger.Println("SQLite in-memory database opened")
}
s.db = db
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1014-L1044 | go | train | // remove removes the node, with the given ID, from the cluster. | func (s *Store) remove(id string) error | // remove removes the node, with the given ID, from the cluster.
func (s *Store) remove(id string) error | {
if s.raft.State() != raft.Leader {
return ErrNotLeader
}
f := s.raft.RemoveServer(raft.ServerID(id), 0, 0)
if f.Error() != nil {
if f.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return f.Error()
}
c, err := newCommand(metadataDelete, id)
if err != nil {
return err
}
b, err := json.Marshal(c)
if err != nil {
return err
}
f = s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
e.Error()
}
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1047-L1059 | go | train | // raftConfig returns a new Raft config for the store. | func (s *Store) raftConfig() *raft.Config | // raftConfig returns a new Raft config for the store.
func (s *Store) raftConfig() *raft.Config | {
config := raft.DefaultConfig()
if s.SnapshotThreshold != 0 {
config.SnapshotThreshold = s.SnapshotThreshold
}
if s.SnapshotInterval != 0 {
config.SnapshotInterval = s.SnapshotInterval
}
if s.HeartbeatTimeout != 0 {
config.HeartbeatTimeout = s.HeartbeatTimeout
}
return config
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1063-L1110 | go | train | // checkConnections periodically checks which connections should
// close due to timeouts. | func (s *Store) checkConnections() | // checkConnections periodically checks which connections should
// close due to timeouts.
func (s *Store) checkConnections() | {
s.wg.Add(1)
ticker := time.NewTicker(s.connPollPeriod)
go func() {
defer s.wg.Done()
defer ticker.Stop()
for {
select {
case <-s.done:
return
case <-ticker.C:
// This is not a 100% correct check, but is right almost all
// the time, and saves the node from most unneeded network
// access. Read https://github.com/rqlite/rqlite/issues/5
if !s.IsLeader() {
continue
}
var conns []*Connection
s.connsMu.RLock()
for _, c := range s.conns {
// Sometimes IDs are in the slice without a connection, if a
// connection is in process of being formed via consensus.
if c == nil || c.ID == defaultConnID {
continue
}
if c.IdleTimedOut() || c.TxTimedOut() {
conns = append(conns, c)
}
}
s.connsMu.RUnlock()
for _, c := range conns {
if err := c.Close(); err != nil {
if err == ErrNotLeader {
// Not an issue, the actual leader will close it.
continue
}
s.logger.Printf("%s failed to close: %s", c, err.Error())
}
s.logger.Printf("%s closed due to timeout", c)
// Only increment stat here to make testing easier.
stats.Add(numConnTimeouts, 1)
}
}
}
}()
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1127-L1219 | go | train | // Apply applies a Raft log entry to the database. | func (s *Store) Apply(l *raft.Log) interface{} | // Apply applies a Raft log entry to the database.
func (s *Store) Apply(l *raft.Log) interface{} | {
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
var c command
if err := json.Unmarshal(l.Data, &c); err != nil {
panic(fmt.Sprintf("failed to unmarshal cluster command: %s", err.Error()))
}
switch c.Typ {
case execute, query:
var d databaseSub
if err := json.Unmarshal(c.Sub, &d); err != nil {
return &fsmGenericResponse{error: err}
}
s.connsMu.RLock()
conn, ok := s.conns[d.ConnID]
s.connsMu.RUnlock()
if !ok {
return &fsmGenericResponse{error: ErrConnectionDoesNotExist}
}
if c.Typ == execute {
txChange := NewTxStateChange(conn)
r, err := conn.db.Execute(d.Queries, d.Atomic, d.Timings)
txChange.CheckAndSet()
return &fsmExecuteResponse{results: r, error: err}
}
r, err := conn.db.Query(d.Queries, d.Atomic, d.Timings)
return &fsmQueryResponse{rows: r, error: err}
case metadataSet:
var d metadataSetSub
if err := json.Unmarshal(c.Sub, &d); err != nil {
return &fsmGenericResponse{error: err}
}
func() {
s.metaMu.Lock()
defer s.metaMu.Unlock()
if _, ok := s.meta[d.RaftID]; !ok {
s.meta[d.RaftID] = make(map[string]string)
}
for k, v := range d.Data {
s.meta[d.RaftID][k] = v
}
}()
return &fsmGenericResponse{}
case metadataDelete:
var d string
if err := json.Unmarshal(c.Sub, &d); err != nil {
return &fsmGenericResponse{error: err}
}
func() {
s.metaMu.Lock()
defer s.metaMu.Unlock()
delete(s.meta, d)
}()
return &fsmGenericResponse{}
case connect:
var d connectionSub
if err := json.Unmarshal(c.Sub, &d); err != nil {
return &fsmGenericResponse{error: err}
}
conn, err := s.db.Connect()
if err != nil {
return &fsmGenericResponse{error: err}
}
s.connsMu.Lock()
s.conns[d.ConnID] = NewConnection(conn, s, d.ConnID, d.IdleTimeout, d.TxTimeout)
s.connsMu.Unlock()
return d.ConnID
case disconnect:
var d connectionSub
if err := json.Unmarshal(c.Sub, &d); err != nil {
return &fsmGenericResponse{error: err}
}
if d.ConnID == defaultConnID {
return &fsmGenericResponse{error: ErrDefaultConnection}
}
return func() interface{} {
s.connsMu.Lock()
defer s.connsMu.Unlock()
delete(s.conns, d.ConnID)
return &fsmGenericResponse{}
}()
default:
return &fsmGenericResponse{error: fmt.Errorf("unknown command: %v", c.Typ)}
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1222-L1259 | go | train | // Database copies contents of the underlying SQLite file to dst | func (s *Store) database(leader bool, dst io.Writer) error | // Database copies contents of the underlying SQLite file to dst
func (s *Store) database(leader bool, dst io.Writer) error | {
if leader && s.raft.State() != raft.Leader {
return ErrNotLeader
}
f, err := ioutil.TempFile("", "rqlilte-snap-")
if err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
os.Remove(f.Name())
db, err := sdb.New(f.Name(), "", false)
if err != nil {
return err
}
conn, err := db.Connect()
if err != nil {
return err
}
if err := s.dbConn.Backup(conn); err != nil {
return err
}
if err := conn.Close(); err != nil {
return err
}
of, err := os.Open(f.Name())
if err != nil {
return err
}
defer of.Close()
_, err = io.Copy(dst, of)
return err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1264-L1315 | go | train | // Snapshot returns a snapshot of the store. The caller must ensure that
// no Raft transaction is taking place during this call. Hashicorp Raft
// guarantees that this function will not be called concurrently with Apply. | func (s *Store) Snapshot() (raft.FSMSnapshot, error) | // Snapshot returns a snapshot of the store. The caller must ensure that
// no Raft transaction is taking place during this call. Hashicorp Raft
// guarantees that this function will not be called concurrently with Apply.
func (s *Store) Snapshot() (raft.FSMSnapshot, error) | {
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
// Snapshots are not permitted while any connection has a transaction
// in progress, because it's not possible (not without a lot of extra
// code anyway) to capture the state of a connection during a transaction
// on that connection. Since only during Apply() can a connection change
// its transaction state, and Apply() is never called concurrently with
// this call, it's safe to check transaction state here across all connections.
if err := func() error {
s.connsMu.Lock()
defer s.connsMu.Unlock()
for _, c := range s.conns {
if c.TransactionActive() {
stats.Add(numSnaphotsBlocked, 1)
return ErrTransactionActive
}
}
return nil
}(); err != nil {
return nil, err
}
// Copy the database.
fsm := &fsmSnapshot{}
var buf bytes.Buffer
var err error
err = s.database(false, &buf)
if err != nil {
s.logger.Printf("failed to read database for snapshot: %s", err.Error())
return nil, err
}
fsm.database = buf.Bytes()
// Copy the node metadata.
fsm.meta, err = json.Marshal(s.meta)
if err != nil {
s.logger.Printf("failed to encode meta for snapshot: %s", err.Error())
return nil, err
}
// Copy the active connections.
fsm.connections, err = json.Marshal(s.conns)
if err != nil {
s.logger.Printf("failed to encode connections for snapshot: %s", err.Error())
return nil, err
}
stats.Add(numSnaphots, 1)
return fsm, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1318-L1407 | go | train | // Restore restores the node to a previous state. | func (s *Store) Restore(rc io.ReadCloser) error | // Restore restores the node to a previous state.
func (s *Store) Restore(rc io.ReadCloser) error | {
s.restoreMu.Lock()
defer s.restoreMu.Unlock()
// Get size of database.
var sz uint64
if err := binary.Read(rc, binary.LittleEndian, &sz); err != nil {
return err
}
// Now read in the database file data and restore.
database := make([]byte, sz)
if _, err := io.ReadFull(rc, database); err != nil {
return err
}
// Create temp file and write incoming database to there.
temp, err := tempfile()
if err != nil {
return err
}
defer os.Remove(temp.Name())
defer temp.Close()
if _, err := temp.Write(database); err != nil {
return err
}
// Create new database from file, connect, and load
// existing database from that.
db, err := sdb.New(temp.Name(), "", false)
if err != nil {
return err
}
conn, err := db.Connect()
if err != nil {
return err
}
defer conn.Close()
if err := s.dbConn.Load(conn); err != nil {
return err
}
// Get size of meta, read those bytes, and set to meta.
if err := binary.Read(rc, binary.LittleEndian, &sz); err != nil {
return err
}
meta := make([]byte, sz)
if _, err := io.ReadFull(rc, meta); err != nil {
return err
}
err = func() error {
s.metaMu.Lock()
defer s.metaMu.Unlock()
return json.Unmarshal(meta, &s.meta)
}()
if err != nil {
return err
}
// Get size of connections, read those bytes, and set to connections.
if err := binary.Read(rc, binary.LittleEndian, &sz); err != nil {
return err
}
conns := make([]byte, sz)
if _, err := io.ReadFull(rc, conns); err != nil {
return err
}
err = func() error {
s.connsMu.Lock()
defer s.connsMu.Unlock()
if err := json.Unmarshal(conns, &s.conns); err != nil {
return err
}
for _, c := range s.conns {
dbConn, err := s.db.Connect()
if err != nil {
return err
}
c.Restore(dbConn, s)
}
return nil
}()
if err != nil {
return err
}
stats.Add(numRestores, 1)
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1410-L1412 | go | train | // RegisterObserver registers an observer of Raft events | func (s *Store) RegisterObserver(o *raft.Observer) | // RegisterObserver registers an observer of Raft events
func (s *Store) RegisterObserver(o *raft.Observer) | {
s.raft.RegisterObserver(o)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1415-L1417 | go | train | // DeregisterObserver deregisters an observer of Raft events | func (s *Store) DeregisterObserver(o *raft.Observer) | // DeregisterObserver deregisters an observer of Raft events
func (s *Store) DeregisterObserver(o *raft.Observer) | {
s.raft.DeregisterObserver(o)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1426-L1459 | go | train | // Persist writes the snapshot to the given sink. | func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error | // Persist writes the snapshot to the given sink.
func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error | {
// sizeWriter writes the size of given byte slize to the
// raft sink, followed by the byte slice itself.
sizeWriter := func(s raft.SnapshotSink, b []byte) error {
buf := new(bytes.Buffer)
sz := uint64(len(b))
err := binary.Write(buf, binary.LittleEndian, sz)
if err != nil {
return err
}
if _, err := s.Write(buf.Bytes()); err != nil {
return err
}
if _, err := s.Write(b); err != nil {
return err
}
return nil
}
if err := func() error {
for _, b := range [][]byte{f.database, f.meta, f.connections} {
if err := sizeWriter(sink, b); err != nil {
return err
}
}
// Close the sink.
return sink.Close()
}(); err != nil {
sink.Cancel()
return err
}
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1473-L1478 | go | train | // pathExists returns true if the given path exists. | func pathExists(p string) bool | // pathExists returns true if the given path exists.
func pathExists(p string) bool | {
if _, err := os.Lstat(p); err != nil && os.IsNotExist(err) {
return false
}
return true
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.