serializer.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. package thrift
  20. type TSerializer struct {
  21. Transport *TMemoryBuffer
  22. Protocol TProtocol
  23. }
  24. type TStruct interface {
  25. Write(p TProtocol) error
  26. Read(p TProtocol) error
  27. }
  28. func NewTSerializer() *TSerializer {
  29. transport := NewTMemoryBufferLen(1024)
  30. protocol := NewTBinaryProtocolFactoryDefault().GetProtocol(transport)
  31. return &TSerializer{
  32. transport,
  33. protocol}
  34. }
  35. func (t *TSerializer) WriteString(msg TStruct) (s string, err error) {
  36. t.Transport.Reset()
  37. if err = msg.Write(t.Protocol); err != nil {
  38. return
  39. }
  40. if err = t.Protocol.Flush(); err != nil {
  41. return
  42. }
  43. if err = t.Transport.Flush(); err != nil {
  44. return
  45. }
  46. return t.Transport.String(), nil
  47. }
  48. func (t *TSerializer) Write(msg TStruct) (b []byte, err error) {
  49. t.Transport.Reset()
  50. if err = msg.Write(t.Protocol); err != nil {
  51. return
  52. }
  53. if err = t.Protocol.Flush(); err != nil {
  54. return
  55. }
  56. if err = t.Transport.Flush(); err != nil {
  57. return
  58. }
  59. b = append(b, t.Transport.Bytes()...)
  60. return
  61. }