Last active
August 31, 2017 03:59
-
-
Save nakatanakatana/87b9d63debbf2d6704fc743ac5044329 to your computer and use it in GitHub Desktop.
plantuml_serverに渡す文字列を生成する。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"bytes" | |
"strings" | |
"compress/zlib" | |
"math" | |
) | |
const encodeStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_" | |
func encode64(str string) (string, error) { | |
var b bytes.Buffer | |
w, err := zlib.NewWriterLevel(&b, zlib.BestCompression) | |
if err != nil { | |
return "", err | |
} | |
defer w.Close() | |
w.Write([]byte(str)) | |
w.Flush() | |
bytesData := b.Bytes() | |
bytesData = bytesData[2:len(bytesData)-4] | |
bytesData[0] += 1 | |
var l int | |
outputLength := int((math.Ceil(float64(len(bytesData)) / 3)) * 4) | |
code := make([]string, outputLength) | |
codeIndex := 0 | |
for i := 0; i < len(bytesData); i += 3 { | |
var result [4]string | |
l = len(bytesData[i:]) | |
switch { | |
case l >= 3: | |
fmt.Printf("%02x %02x %02x || ", int(bytesData[i]), int(bytesData[i+1]), int(bytesData[i+2])) | |
result, err = append3bytes(int(bytesData[i]), int(bytesData[i+1]), int(bytesData[i+2])) | |
case l == 2: | |
fmt.Printf("%02x %02x %02x || ", int(bytesData[i]), int(bytesData[i+1]), 0) | |
result, err = append3bytes(int(bytesData[i]), int(bytesData[i+1]), 0) | |
case l == 1: | |
fmt.Printf("%02x %02x %02x || ", int(bytesData[i]), 0, 0) | |
result, err = append3bytes(int(bytesData[i]), 0, 0) | |
} | |
if err != nil { | |
return "", err | |
} | |
for _, r := range result { | |
code[codeIndex] = r | |
codeIndex += 1 | |
} | |
} | |
return strings.Join(code, ""), nil | |
} | |
func append3bytes(b1, b2, b3 int) ([4]string, error) { | |
c1 := int((b1 >> 2) & 0x3F) | |
c2 := int((((b1 & 0x3) << 4) | (b2 >> 4)) & 0x3F) | |
c3 := int((((b2 & 0xF) << 2) | (b3 >> 6)) & 0x3F) | |
c4 := int(b3 & 0x3F) | |
fmt.Printf("%02d %02d %02d %02d || %06b %06b %06b %06b\n", c1, c2, c3, c4, c1, c2, c3, c4) | |
return [4]string{string(encodeStr[c1]), string(encodeStr[c2]), string(encodeStr[c3]), string(encodeStr[c4])}, nil | |
} | |
func main() { | |
var stdin string | |
fmt.Scan(&stdin) | |
// fmt.Println(stdin) | |
result, err := encode64(stdin) | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println(result[:]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment