Subversion Repositories SmartDukaan

Rev

Rev 30 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
30 ashish 1
# encoding: ascii-8bit
2
# 
3
# Licensed to the Apache Software Foundation (ASF) under one
4
# or more contributor license agreements. See the NOTICE file
5
# distributed with this work for additional information
6
# regarding copyright ownership. The ASF licenses this file
7
# to you under the Apache License, Version 2.0 (the
8
# "License"); you may not use this file except in compliance
9
# with the License. You may obtain a copy of the License at
10
# 
11
#   http://www.apache.org/licenses/LICENSE-2.0
12
# 
13
# Unless required by applicable law or agreed to in writing,
14
# software distributed under the License is distributed on an
15
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
# KIND, either express or implied. See the License for the
17
# specific language governing permissions and limitations
18
# under the License.
19
#
20
 
21
module Thrift
22
  class FramedTransport < BaseTransport
23
    def initialize(transport, read=true, write=true)
24
      @transport = transport
25
      @rbuf      = ''
26
      @wbuf      = ''
27
      @read      = read
28
      @write     = write
29
      @index      = 0
30
    end
31
 
32
    def open?
33
      @transport.open?
34
    end
35
 
36
    def open
37
      @transport.open
38
    end
39
 
40
    def close
41
      @transport.close
42
    end
43
 
44
    def read(sz)
45
      return @transport.read(sz) unless @read
46
 
47
      return '' if sz <= 0
48
 
49
      read_frame if @index >= @rbuf.length
50
 
51
      @index += sz
52
      @rbuf.slice(@index - sz, sz) || ''
53
    end
54
 
55
    def write(buf,sz=nil)
56
      return @transport.write(buf) unless @write
57
 
58
      @wbuf << (sz ? buf[0...sz] : buf)
59
    end
60
 
61
    #
62
    # Writes the output buffer to the stream in the format of a 4-byte length
63
    # followed by the actual data.
64
    #
65
    def flush
66
      return @transport.flush unless @write
67
 
68
      out = [@wbuf.length].pack('N')
69
      out << @wbuf
70
      @transport.write(out)
71
      @transport.flush
72
      @wbuf = ''
73
    end
74
 
75
    private
76
 
77
    def read_frame
78
      sz = @transport.read_all(4).unpack('N').first
79
 
80
      @index = 0
81
      @rbuf = @transport.read_all(sz)
82
    end
83
  end
84
 
85
  class FramedTransportFactory < BaseTransportFactory
86
    def get_transport(transport)
87
      return FramedTransport.new(transport)
88
    end
89
  end
90
end