-
Notifications
You must be signed in to change notification settings - Fork 54
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge remote-tracking branch 'origin/tl-decoder'
- Loading branch information
Showing
6 changed files
with
893 additions
and
19 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package liteclient | ||
|
||
import ( | ||
"bytes" | ||
"encoding/binary" | ||
"errors" | ||
"fmt" | ||
"github.com/tonkeeper/tongo/tl" | ||
"reflect" | ||
) | ||
|
||
func pointer[T any](t T) *T { | ||
return &t | ||
} | ||
|
||
type RequestName = string | ||
|
||
const ( | ||
UnknownRequest RequestName = "Unknown" | ||
) | ||
|
||
func decodeRequest(tag uint32, name RequestName, msgType any) reqDecoderFunc { | ||
return func(b []byte) (*RequestName, any, error) { | ||
if len(b) < 4 { | ||
return nil, nil, errors.New("message too short") | ||
} | ||
readTag := binary.LittleEndian.Uint32(b[:4]) | ||
if readTag != tag { | ||
return nil, nil, fmt.Errorf("invalid tag") | ||
} | ||
body := reflect.New(reflect.TypeOf(msgType)) | ||
reader := bytes.NewReader(b[4:]) | ||
err := tl.Unmarshal(reader, body.Interface()) | ||
if err == nil { | ||
return pointer(name), body.Elem().Interface(), nil | ||
} | ||
return nil, nil, err | ||
} | ||
} | ||
|
||
type reqDecoderFunc func(b []byte) (*RequestName, any, error) | ||
|
||
func LiteapiRequestDecoder(b []byte) (uint32, *RequestName, any, error) { | ||
if len(b) < 4 { | ||
return 0, nil, nil, errors.New("message too short") | ||
} | ||
tag := binary.LittleEndian.Uint32(b[:4]) | ||
f := taggedRequestDecodeFunctions[tag] | ||
if f != nil { | ||
o, d, err := f(b) | ||
if err == nil { | ||
return tag, o, d, nil | ||
} | ||
} | ||
return tag, pointer(UnknownRequest), nil, nil | ||
} |
Oops, something went wrong.