This repository has been archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a payload conversion method to ease UTF8 conversion.
- Loading branch information
Showing
2 changed files
with
37 additions
and
6 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package webwire | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"unicode/utf16" | ||
"unicode/utf8" | ||
) | ||
|
||
// Payload represents an encoded message payload | ||
type Payload struct { | ||
Encoding PayloadEncoding | ||
Data []byte | ||
} | ||
|
||
// Utf8 returns a UTF8 representation of the payload data | ||
func (pld *Payload) Utf8() (string, error) { | ||
if pld.Encoding == EncodingUtf16 { | ||
if len(pld.Data)%2 != 0 { | ||
return "", fmt.Errorf("Cannot convert invalid UTF16 payload data to UTF8") | ||
} | ||
u16str := make([]uint16, 1) | ||
// TODO: check whether the builtin append would be more efficient than bytes.Buffer | ||
utf8str := &bytes.Buffer{} | ||
utf8buf := make([]byte, 4) | ||
for i := 0; i < len(pld.Data); i += 2 { | ||
u16str[0] = uint16(pld.Data[i]) + (uint16(pld.Data[i+1]) << 8) | ||
rn := utf16.Decode(u16str) | ||
rnSize := utf8.EncodeRune(utf8buf, rn[0]) | ||
utf8str.Write(utf8buf[:rnSize]) | ||
} | ||
return utf8str.String(), nil | ||
} | ||
|
||
// Binary and UTF8 encoded payloads should pass through untouched | ||
return string(pld.Data), nil | ||
} |