62 lines
1.7 KiB
GDScript
62 lines
1.7 KiB
GDScript
class_name Encoding extends RefCounted
|
|
|
|
enum Type {
|
|
Ascii,
|
|
Utf8,
|
|
Utf16,
|
|
Utf32,
|
|
Wchar
|
|
}
|
|
|
|
static var Ascii = from(Type.Ascii)
|
|
static var Utf8 = from(Type.Utf8)
|
|
static var Utf16 = from(Type.Utf16)
|
|
static var Utf32 = from(Type.Utf32)
|
|
static var Wchar = from(Type.Wchar)
|
|
|
|
var type: Type
|
|
|
|
func _init(_type: Type) -> void:
|
|
type = _type
|
|
|
|
static func from(type: Type) -> Encoding:
|
|
return Encoding.new(type)
|
|
|
|
static func byte_size_of(encoding: Type) -> int:
|
|
match encoding:
|
|
Type.Ascii: return 1
|
|
Type.Utf8: return 1
|
|
Type.Utf16: return 2
|
|
Type.Utf32: return 4
|
|
Type.Wchar:
|
|
match OS.get_name():
|
|
"Windows": return 2
|
|
_: return 4
|
|
return -1
|
|
|
|
func byte_size() -> int:
|
|
return byte_size_of(type)
|
|
|
|
static func encode_str_as(value: String, encoding: Type) -> PackedByteArray:
|
|
match encoding:
|
|
Type.Ascii: return value.to_ascii_buffer()
|
|
Type.Utf8: return value.to_utf8_buffer()
|
|
Type.Utf16: return value.to_utf16_buffer()
|
|
Type.Utf32: return value.to_utf32_buffer()
|
|
Type.Wchar: return value.to_wchar_buffer()
|
|
return PackedByteArray()
|
|
|
|
func encode_str(value: String) -> PackedByteArray:
|
|
return encode_str_as(value, type)
|
|
|
|
static func decode_str_as(value: PackedByteArray, encoding: Type) -> String:
|
|
match encoding:
|
|
Type.Ascii: return value.get_string_from_ascii()
|
|
Type.Utf8: return value.get_string_from_utf8()
|
|
Type.Utf16: return value.get_string_from_utf16()
|
|
Type.Utf32: return value.get_string_from_utf32()
|
|
Type.Wchar: return value.get_string_from_wchar()
|
|
return ""
|
|
|
|
func decode_str(value: PackedByteArray) -> String:
|
|
return decode_str_as(value, type)
|