This repository has been archived on 2015-04-29. You can view files and clone it, but cannot push or open issues or pull requests.
jsh/common.go

73 lines
1.3 KiB
Go

/* Common structures and methods used across all coreutils */
package jsh
import (
"encoding/json"
"fmt"
)
type JshFrame struct {
StdOut interface{}
StdErr interface{}
}
// Converts a JshFrame into a JSON string
func (j JshFrame) ToJson() *string {
jsonOut, err := json.Marshal(j)
if err != nil {
panic(err)
}
jsonString := string(jsonOut)
return &jsonString
}
// goroutine for outputing frames. Pass it a channel of pointers to JshFrames,
// and it will send "true" to the done channel once you close the queue channel.
func OutputFrames(queue chan *JshFrame, done chan bool) {
fmt.Printf("[")
isFirst := true
for {
frame, more := <-queue
if more {
if !isFirst {
fmt.Printf(",")
} else {
isFirst = false
}
fmt.Printf(*frame.ToJson())
} else {
fmt.Printf("]\n")
done <- true
return
}
}
}
// Size prefixes as integers, using binary representation
type Unit int
const (
B Unit = 2 ^ 0
KB Unit = 2 ^ 10
MB Unit = 2 ^ 20
GB Unit = 2 ^ 30
TB Unit = 2 ^ 40
)
func (u Unit) ToString() string {
if u == B {
return "B"
} else if u == KB {
return "kB"
} else if u == MB {
return "mB"
} else if u == GB {
return "gB"
} else if u == TB {
return "tB"
} else {
return fmt.Sprintf("Unknown type, values is %d", u)
}
}