@@ -71,7 +71,16 @@ defmodule Protobuf.Wire do
7171 @ spec encode ( proto_type ( ) , proto_value ( ) ) :: iodata ( )
7272 def encode ( type , value )
7373
74- def encode ( type , binary ) when is_binary ( binary ) and type in [ :string , :bytes ] ,
74+ def encode ( :string , binary ) when is_binary ( binary ) do
75+ unless String . valid? ( binary ) do
76+ raise Protobuf.EncodeError ,
77+ message: "invalid UTF-8 data for type string: #{ inspect ( binary ) } "
78+ end
79+
80+ encode_from_wire_type ( wire_delimited ( ) , binary )
81+ end
82+
83+ def encode ( :bytes , binary ) when is_binary ( binary ) ,
7584 do: encode_from_wire_type ( wire_delimited ( ) , binary )
7685
7786 def encode ( :int32 , n ) when n in @ sint32_range , do: encode_from_wire_type ( wire_varint ( ) , n )
@@ -133,7 +142,16 @@ defmodule Protobuf.Wire do
133142 @ spec decode ( proto_type ( ) , binary ( ) | integer ( ) ) :: proto_value ( )
134143 def decode ( type , value )
135144
136- def decode ( type , val ) when type in [ :string , :bytes ] , do: val
145+ def decode ( :string , binary ) when is_binary ( binary ) do
146+ unless String . valid? ( binary ) do
147+ raise Protobuf.DecodeError ,
148+ message: "invalid UTF-8 data for type string: #{ inspect ( binary ) } "
149+ end
150+
151+ binary
152+ end
153+
154+ def decode ( :bytes , binary ) when is_binary ( binary ) , do: binary
137155
138156 def decode ( :int32 , val ) do
139157 << n :: signed - integer - 32 >> = << val :: 32 >>
0 commit comments