bencode_ext 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ bin/*
3
+ -
4
+ features/**/*.feature
5
+ LICENSE.txt
data/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2010 naquad
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,19 @@
1
+ = bencode_ext
2
+
3
+ BEncodeExt is implementation of Bencode reader/writer (BitTorent encoding) in C. See BEncode module for details.
4
+ This module was tested with ruby 1.9.2. It definitely doesn't work with ruby 1.8.x.
5
+
6
+ == Contributing to bencode_ext
7
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
8
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
9
+ * Fork the project
10
+ * Start a feature/bugfix branch
11
+ * Commit and push until you are happy with your contribution
12
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
13
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
14
+
15
+ == Copyright
16
+
17
+ Copyright (c) 2010 naquad. See LICENSE.txt for
18
+ further details.
19
+
data/Rakefile ADDED
@@ -0,0 +1,43 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ require 'jeweler'
5
+ Jeweler::Tasks.new do |gem|
6
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
7
+ gem.name = "bencode_ext"
8
+ gem.homepage = "http://github.com/naquad/bencode_ext"
9
+ gem.license = "MIT"
10
+ gem.summary = %Q{BitTorrent encoding parser/writer}
11
+ gem.description = %Q{BEncodeExt is implementation of Bencode reader/writer (BitTorent encoding) in C.}
12
+ gem.email = "naquad@gmail.com"
13
+ gem.authors = ["naquad"]
14
+ gem.required_ruby_version = '~>1.9.2'
15
+ gem.add_dependency 'rake-compiler', '~>0.7.5'
16
+ gem.add_development_dependency "jeweler", "~> 1.5.2"
17
+ gem.extensions << "ext/bencode_ext/extconf.rb"
18
+ end
19
+ Jeweler::RubygemsDotOrgTasks.new
20
+ Jeweler::GemcutterTasks.new
21
+
22
+ require 'rake/testtask'
23
+ Rake::TestTask.new(:test) do |test|
24
+ test.libs << 'lib' << 'test'
25
+ test.pattern = 'test/**/test_*.rb'
26
+ test.verbose = true
27
+ end
28
+
29
+ task :default => :test
30
+
31
+ require 'rake/rdoctask'
32
+ Rake::RDocTask.new do |rdoc|
33
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
34
+
35
+ rdoc.rdoc_dir = 'rdoc'
36
+ rdoc.title = "bencode_ext #{version}"
37
+ rdoc.rdoc_files.include('README*')
38
+ rdoc.rdoc_files.include('ext/**/*.c')
39
+ end
40
+
41
+
42
+ require 'rake/extensiontask'
43
+ Rake::ExtensionTask.new('bencode_ext')
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,285 @@
1
+ /*
2
+ * Document-module: BEncode
3
+ *
4
+ * BEncode module provides functionality for encoding/decoding Ruby objects
5
+ * in BitTorrent loosly structured data format - <i>bencode</i>. To decode data you sould use one of the following:
6
+ * 'string'.bdecode
7
+ * BEncode.decode('string')
8
+ * Where string contains bencoded data (i.e. some torrent file)
9
+ * To encode your objects into bencode format:
10
+ * object.bencode
11
+ * # or
12
+ * BEncode.encode(object)
13
+ * bencode format has only following datatypes:
14
+ * Integer
15
+ * String
16
+ * List
17
+ * Dictionary (Hash)
18
+ * No other types allowed. Only symbols are converted to string for convenience
19
+ * (<b>but they're decoded as strings</b>).
20
+ *
21
+ * <b>BEncode is included into Object on load.</b>
22
+ */
23
+
24
+ #include "bencode.h"
25
+
26
+ #define NEXT_CHAR ++*str; --*len;
27
+ #define END_CHECK_SKIP(t) {if(!*len)\
28
+ rb_raise(DecodeError, "Unpexpected " #t " end!");\
29
+ if(**str != 'e')\
30
+ rb_raise(DecodeError, "Mailformed " #t " at %d byte: %c", rlen - *len, **str);\
31
+ NEXT_CHAR;}
32
+
33
+ static long parse_num(char** str, long* len){
34
+ long t = 1, ret = 0;
35
+
36
+ if(**str == '-'){
37
+ t = -1;
38
+ NEXT_CHAR;
39
+ }
40
+
41
+ while(*len && **str >= '0' && **str <= '9'){
42
+ ret = ret * 10 + (**str - '0');
43
+ NEXT_CHAR;
44
+ }
45
+
46
+ return ret * t;
47
+ }
48
+
49
+ static VALUE _decode(char** str, long* len, long rlen){
50
+ if(!*len)
51
+ return Qnil;
52
+
53
+ switch(**str){
54
+ case 'l':{
55
+ VALUE ret = rb_ary_new();
56
+ NEXT_CHAR;
57
+
58
+ while(**str != 'e' && *len)
59
+ rb_ary_push(ret, _decode(str, len, rlen));
60
+
61
+ END_CHECK_SKIP(list);
62
+ return ret;
63
+ }
64
+ case 'd':{
65
+ VALUE ret = rb_hash_new();
66
+ NEXT_CHAR;
67
+
68
+ while(**str != 'e' && *len){
69
+ long t = rlen - *len;
70
+ VALUE k = _decode(str, len, rlen);
71
+
72
+ if(NIL_P(k))
73
+ rb_raise(DecodeError, "Unpexpected dictionary end!");
74
+ else if(TYPE(k) != T_STRING)
75
+ rb_raise(DecodeError, "Dictionary key is not a string at %d!", t);
76
+
77
+ rb_hash_aset(ret, k, _decode(str, len, rlen));
78
+ }
79
+
80
+ END_CHECK_SKIP(dictionary);
81
+ return ret;
82
+ }
83
+ case 'i':{
84
+ long t;
85
+ NEXT_CHAR;
86
+ t = parse_num(str, len);
87
+ END_CHECK_SKIP(integer);
88
+ return LONG2FIX(t);
89
+ }
90
+ case '0'...'9':{
91
+ VALUE ret;
92
+ long slen = parse_num(str, len);
93
+
94
+ if(slen < 0 || (*len && **str != ':'))
95
+ rb_raise(DecodeError, "Invalid string length specification at %d: %c", rlen - *len, **str);
96
+
97
+ if(!*len || *len < slen + 1)
98
+ rb_raise(DecodeError, "Unexpected string end!");
99
+
100
+ ret = rb_str_new(++*str, slen);
101
+ *str += slen;
102
+ *len -= slen + 1;
103
+ return ret;
104
+ }
105
+ default:
106
+ rb_raise(DecodeError, "Unknown element type at %d byte: %c", rlen - *len, **str);
107
+ return Qnil;
108
+ }
109
+ }
110
+
111
+ /*
112
+ * Document-method: BEncode.decode
113
+ * call-seq:
114
+ * BEncode.decode(string)
115
+ *
116
+ * Returns data structure from parsed _string_.
117
+ * String must be valid bencoded data, or
118
+ * BEncode::DecodeError will be raised with description
119
+ * of error.
120
+ *
121
+ * Examples:
122
+ *
123
+ * 'i1e' => 1
124
+ * 'i-1e' => -1
125
+ * '6:string' => 'string'
126
+ */
127
+
128
+ static VALUE decode(VALUE self, VALUE str){
129
+ long rlen, len;
130
+ char* ptr;
131
+ VALUE ret;
132
+
133
+ if(!rb_obj_is_kind_of(str, rb_cString))
134
+ rb_raise(rb_eTypeError, "String expected");
135
+
136
+ rlen = len = RSTRING_LEN(str);
137
+ ptr = RSTRING_PTR(str);
138
+ ret = _decode(&ptr, &len, len);
139
+
140
+ if(len)
141
+ rb_raise(DecodeError, "String has garbage on the end (starts at %d).", rlen - len);
142
+
143
+ return ret;
144
+ }
145
+
146
+ static VALUE _decode_file(VALUE fp){
147
+ return decode(BEncode, rb_funcall(fp, readId, 0));
148
+ }
149
+
150
+ /*
151
+ * Document-method: BEncode.decode_file
152
+ * call-seq:
153
+ * BEncode.decode_file(file)
154
+ *
155
+ * Load content of _file_ and decodes it.
156
+ * _file_ may be either IO instance or
157
+ * String path to file.
158
+ *
159
+ * Examples:
160
+ *
161
+ * BEncode.decode_file('/path/to/file.torrent')
162
+ *
163
+ * open('/path/to/file.torrent', 'rb') do |f|
164
+ * BEncode.decode_file(f)
165
+ * end
166
+ */
167
+
168
+ static VALUE decode_file(VALUE self, VALUE path){
169
+ if(rb_obj_is_kind_of(path, rb_cIO)){
170
+ return _decode_file(path);
171
+ }else{
172
+ VALUE fp = rb_file_open_str(path, "rb");
173
+ return rb_ensure(_decode_file, fp, rb_io_close, fp);
174
+ }
175
+ }
176
+
177
+ /*
178
+ * Document-method: BEncode#bencode
179
+ * call-seq:
180
+ * object.bencode
181
+ *
182
+ * Returns a string representing _object_ in
183
+ * bencoded format. _object_ must be one of:
184
+ * Integer
185
+ * String
186
+ * Symbol (will be converter to String)
187
+ * Array
188
+ * Hash
189
+ * If _object_ does not belong to these types
190
+ * or their derivates BEncode::EncodeError exception will
191
+ * be raised.
192
+ *
193
+ * Because BEncode is included into Object
194
+ * This method is avilable for all objects.
195
+ *
196
+ * Examples:
197
+ *
198
+ * 1.bencode => 'i1e'
199
+ * -1.bencode => 'i-1e'
200
+ * 'string'.bencode => '6:string'
201
+ */
202
+
203
+ static VALUE encode(VALUE self){
204
+ if(TYPE(self) == T_SYMBOL){
205
+ return encode(rb_id2str(SYM2ID(self)));
206
+ }if(rb_obj_is_kind_of(self, rb_cString)){
207
+ long len = RSTRING_LEN(self);
208
+ return rb_sprintf("%d:%.*s", len, len, RSTRING_PTR(self));
209
+ }else if(rb_obj_is_kind_of(self, rb_cInteger)){
210
+ return rb_sprintf("i%de", NUM2LONG(self));
211
+ }else if(rb_obj_is_kind_of(self, rb_cHash)){
212
+ VALUE ret = rb_str_new2("d");
213
+ rb_hash_foreach(self, hash_traverse, ret);
214
+ rb_str_cat2(ret, "e");
215
+ return ret;
216
+ }else if(rb_obj_is_kind_of(self, rb_cArray)){
217
+ long i, c;
218
+ VALUE *ptr, ret = rb_str_new2("l");
219
+
220
+ for(i = 0, c = RARRAY_LEN(self), ptr = RARRAY_PTR(self); i < c; ++i)
221
+ rb_str_concat(ret, encode(ptr[i]));
222
+
223
+ rb_str_cat2(ret, "e");
224
+ return ret;
225
+ }else
226
+ rb_raise(EncodeError, "Don't know how to encode %s!", rb_class2name(CLASS_OF(self)));
227
+ }
228
+
229
+ static int hash_traverse(VALUE key, VALUE val, VALUE str){
230
+ if(!rb_obj_is_kind_of(key, rb_cString) && TYPE(key) != T_SYMBOL)
231
+ rb_raise(EncodeError, "Keys must be strings, not %s!", rb_class2name(CLASS_OF(key)));
232
+
233
+ rb_str_concat(str, encode(key));
234
+ rb_str_concat(str, encode(val));
235
+ return ST_CONTINUE;
236
+ }
237
+
238
+ /*
239
+ * Document-method: String#bdecode
240
+ * call-seq:
241
+ * string.bdecode
242
+ *
243
+ * Shortcut to BEncode.encode(_string_)
244
+ */
245
+
246
+ static VALUE str_bdecode(VALUE self){
247
+ return decode(BEncode, self);
248
+ }
249
+
250
+ /*
251
+ * Document-method: encode
252
+ * call-seq:
253
+ * BEncode.encode(object)
254
+ *
255
+ * Shortcut to _object_.bencode
256
+ */
257
+
258
+ static VALUE mod_encode(VALUE self, VALUE x){
259
+ return encode(x);
260
+ }
261
+
262
+ void Init_bencode_ext(){
263
+ readId = rb_intern("read");
264
+ BEncode = rb_define_module("BEncode");
265
+ /*
266
+ * Document-class: BEncode::DecodeError
267
+ * Exception for indicating decoding errors.
268
+ */
269
+ DecodeError = rb_define_class_under(BEncode, "DecodeError", rb_eRuntimeError);
270
+
271
+ /*
272
+ * Document-class: BEncode::EncodeError
273
+ * Exception for indicating encoding errors.
274
+ */
275
+ EncodeError = rb_define_class_under(BEncode, "EncodeError", rb_eRuntimeError);
276
+
277
+ rb_define_singleton_method(BEncode, "decode", decode, 1);
278
+ rb_define_singleton_method(BEncode, "encode", mod_encode, 1);
279
+ rb_define_singleton_method(BEncode, "decode_file", decode_file, 1);
280
+
281
+ rb_define_method(BEncode, "bencode", encode, 0);
282
+ rb_define_method(rb_cString, "bdecode", str_bdecode, 0);
283
+
284
+ rb_include_module(rb_cObject, BEncode);
285
+ }
@@ -0,0 +1,22 @@
1
+ #ifndef __BENCODE_H__
2
+ #define __BENCODE_H__
3
+
4
+ #include "ruby.h"
5
+
6
+ static VALUE BEncode;
7
+ static VALUE DecodeError;
8
+ static VALUE EncodeError;
9
+ static VALUE readId;
10
+
11
+ static long parse_num(char**, long*);
12
+ static VALUE _decode(char**, long*, long);
13
+ static VALUE decode(VALUE, VALUE);
14
+ static VALUE encode(VALUE);
15
+ static int hash_traverse(VALUE, VALUE, VALUE);
16
+ static VALUE str_bdecode(VALUE);
17
+ static VALUE mod_encode(VALUE, VALUE);
18
+ static VALUE _decode_file(VALUE);
19
+ static VALUE decode_file(VALUE, VALUE);
20
+ void Init_bencode_ext();
21
+
22
+ #endif
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/ruby -w
2
+
3
+ require 'mkmf'
4
+ create_makefile('bencode_ext')
data/test/helper.rb ADDED
@@ -0,0 +1,9 @@
1
+ require 'rubygems'
2
+ require 'test/unit'
3
+
4
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
5
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'ext'))
6
+ require 'bencode_ext'
7
+
8
+ class Test::Unit::TestCase
9
+ end
@@ -0,0 +1,28 @@
1
+ require 'helper'
2
+
3
+ class TestBencodeExt < Test::Unit::TestCase
4
+ def test_encoding
5
+ assert_equal('i1e', 1.bencode)
6
+ assert_equal('i-1e', -1.bencode)
7
+ assert_equal('6:symbol', :symbol.bencode)
8
+ assert_equal('6:string', 'string'.bencode)
9
+ assert_equal('li1ei2ee', [1, 2].bencode)
10
+ assert_equal('d3:keyi10ee', {:key => 10}.bencode)
11
+ assert_equal('ld1:ki1eed1:ki2eed1:kd1:v3:123eee', [{:k => 1}, {:k => 2}, {:k => {:v => '123'}}].bencode)
12
+
13
+ assert_raises(BEncode::EncodeError) { STDERR.bencode }
14
+ end
15
+
16
+ def test_decoding
17
+ assert_equal(1, 'i1e'.bdecode)
18
+ assert_equal(-1, 'i-1e'.bdecode)
19
+ assert_equal('string', '6:string'.bdecode)
20
+ assert_equal([1, 2], 'li1ei2ee'.bdecode)
21
+ assert_equal({'key' => 10}, 'd3:keyi10ee'.bdecode)
22
+ assert_equal([{'k' => 1}, {'k' => 2}, {'k' => {'v' => '123'}}], 'ld1:ki1eed1:ki2eed1:kd1:v3:123eee'.bdecode)
23
+
24
+ assert_raises(BEncode::DecodeError) {'33:unpexpected_end'.bdecode }
25
+ assert_raises(BEncode::DecodeError) { 'i1x'.bdecode }
26
+ assert_nil(''.bdecode)
27
+ end
28
+ end
metadata ADDED
@@ -0,0 +1,107 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bencode_ext
3
+ version: !ruby/object:Gem::Version
4
+ prerelease: false
5
+ segments:
6
+ - 0
7
+ - 1
8
+ - 0
9
+ version: 0.1.0
10
+ platform: ruby
11
+ authors:
12
+ - naquad
13
+ autorequire:
14
+ bindir: bin
15
+ cert_chain: []
16
+
17
+ date: 2010-12-24 00:00:00 +02:00
18
+ default_executable:
19
+ dependencies:
20
+ - !ruby/object:Gem::Dependency
21
+ name: rake-compiler
22
+ prerelease: false
23
+ requirement: &id001 !ruby/object:Gem::Requirement
24
+ none: false
25
+ requirements:
26
+ - - ~>
27
+ - !ruby/object:Gem::Version
28
+ segments:
29
+ - 0
30
+ - 7
31
+ - 5
32
+ version: 0.7.5
33
+ type: :runtime
34
+ version_requirements: *id001
35
+ - !ruby/object:Gem::Dependency
36
+ name: jeweler
37
+ prerelease: false
38
+ requirement: &id002 !ruby/object:Gem::Requirement
39
+ none: false
40
+ requirements:
41
+ - - ~>
42
+ - !ruby/object:Gem::Version
43
+ segments:
44
+ - 1
45
+ - 5
46
+ - 2
47
+ version: 1.5.2
48
+ type: :development
49
+ version_requirements: *id002
50
+ description: BEncodeExt is implementation of Bencode reader/writer (BitTorent encoding) in C.
51
+ email: naquad@gmail.com
52
+ executables: []
53
+
54
+ extensions:
55
+ - ext/bencode_ext/extconf.rb
56
+ - ext/bencode_ext/extconf.rb
57
+ extra_rdoc_files:
58
+ - LICENSE.txt
59
+ - README.rdoc
60
+ files:
61
+ - .document
62
+ - LICENSE.txt
63
+ - README.rdoc
64
+ - Rakefile
65
+ - VERSION
66
+ - ext/bencode_ext/bencode.c
67
+ - ext/bencode_ext/bencode.h
68
+ - ext/bencode_ext/extconf.rb
69
+ - test/helper.rb
70
+ - test/test_bencode_ext.rb
71
+ has_rdoc: true
72
+ homepage: http://github.com/naquad/bencode_ext
73
+ licenses:
74
+ - MIT
75
+ post_install_message:
76
+ rdoc_options: []
77
+
78
+ require_paths:
79
+ - lib
80
+ required_ruby_version: !ruby/object:Gem::Requirement
81
+ none: false
82
+ requirements:
83
+ - - ~>
84
+ - !ruby/object:Gem::Version
85
+ segments:
86
+ - 1
87
+ - 9
88
+ - 2
89
+ version: 1.9.2
90
+ required_rubygems_version: !ruby/object:Gem::Requirement
91
+ none: false
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ segments:
96
+ - 0
97
+ version: "0"
98
+ requirements: []
99
+
100
+ rubyforge_project:
101
+ rubygems_version: 1.3.7
102
+ signing_key:
103
+ specification_version: 3
104
+ summary: BitTorrent encoding parser/writer
105
+ test_files:
106
+ - test/helper.rb
107
+ - test/test_bencode_ext.rb