herostats 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +9 -0
  3. data/.travis.yml +4 -0
  4. data/CODE_OF_CONDUCT.md +13 -0
  5. data/Gemfile +4 -0
  6. data/LICENSE +7 -0
  7. data/README.md +34 -0
  8. data/Rakefile +10 -0
  9. data/bin/console +14 -0
  10. data/bin/setup +7 -0
  11. data/herostats.gemspec +33 -0
  12. data/lib/heroprotocol/LICENSE +19 -0
  13. data/lib/heroprotocol/README.md +91 -0
  14. data/lib/heroprotocol/__init__.py +0 -0
  15. data/lib/heroprotocol/decoders.py +311 -0
  16. data/lib/heroprotocol/heroprotocol.py +136 -0
  17. data/lib/heroprotocol/mpyq/LICENSE +22 -0
  18. data/lib/heroprotocol/mpyq/MANIFEST.in +3 -0
  19. data/lib/heroprotocol/mpyq/README.md +202 -0
  20. data/lib/heroprotocol/mpyq/__init__.py +0 -0
  21. data/lib/heroprotocol/mpyq/mpyq.py +406 -0
  22. data/lib/heroprotocol/mpyq/setup.py +33 -0
  23. data/lib/heroprotocol/protocol29406.py +491 -0
  24. data/lib/heroprotocol/protocol30414.py +492 -0
  25. data/lib/heroprotocol/protocol30509.py +492 -0
  26. data/lib/heroprotocol/protocol30829.py +492 -0
  27. data/lib/heroprotocol/protocol30948.py +492 -0
  28. data/lib/heroprotocol/protocol31090.py +492 -0
  29. data/lib/heroprotocol/protocol31360.py +494 -0
  30. data/lib/heroprotocol/protocol31566.py +494 -0
  31. data/lib/heroprotocol/protocol31726.py +494 -0
  32. data/lib/heroprotocol/protocol31948.py +494 -0
  33. data/lib/heroprotocol/protocol32120.py +494 -0
  34. data/lib/heroprotocol/protocol32253.py +494 -0
  35. data/lib/heroprotocol/protocol32455.py +496 -0
  36. data/lib/heroprotocol/protocol32524.py +496 -0
  37. data/lib/heroprotocol/protocol33182.py +499 -0
  38. data/lib/heroprotocol/protocol33353.py +499 -0
  39. data/lib/heroprotocol/protocol33684.py +502 -0
  40. data/lib/heroprotocol/protocol34053.py +502 -0
  41. data/lib/heroprotocol/protocol34190.py +502 -0
  42. data/lib/heroprotocol/protocol34659.py +502 -0
  43. data/lib/heroprotocol/protocol34846.py +502 -0
  44. data/lib/heroprotocol/protocol35360.py +502 -0
  45. data/lib/heroprotocol/protocol35529.py +502 -0
  46. data/lib/heroprotocol/protocol35634.py +502 -0
  47. data/lib/heroprotocol/protocol35702.py +502 -0
  48. data/lib/heroprotocol/protocol36144.py +502 -0
  49. data/lib/heroprotocol/protocol36280.py +502 -0
  50. data/lib/heroprotocol/protocol36359.py +502 -0
  51. data/lib/heroprotocol/protocol36536.py +502 -0
  52. data/lib/heroprotocol/protocol36693.py +502 -0
  53. data/lib/heroprotocol/protocol37069.py +507 -0
  54. data/lib/heroprotocol/protocol37117.py +507 -0
  55. data/lib/heroprotocol/protocol37274.py +507 -0
  56. data/lib/heroprotocol/protocol37351.py +507 -0
  57. data/lib/heroprotocol/protocol37569.py +507 -0
  58. data/lib/heroprotocol/protocol37795.py +507 -0
  59. data/lib/heroprotocol/protocol38236.py +508 -0
  60. data/lib/heroprotocol/protocol38500.py +508 -0
  61. data/lib/heroprotocol/protocol38593.py +508 -0
  62. data/lib/heroprotocol/protocol38793.py +508 -0
  63. data/lib/heroprotocol/protocol39015.py +508 -0
  64. data/lib/heroprotocol/protocol39153.py +508 -0
  65. data/lib/heroprotocol/protocol39271.py +508 -0
  66. data/lib/heroprotocol/protocol39445.py +508 -0
  67. data/lib/heroprotocol/protocol39595.py +508 -0
  68. data/lib/heroprotocol/protocol39709.py +508 -0
  69. data/lib/heroprotocol/protocol39951.py +508 -0
  70. data/lib/heroprotocol/protocol40087.py +508 -0
  71. data/lib/heroprotocol/protocol40322.py +508 -0
  72. data/lib/heroprotocol/protocol40336.py +526 -0
  73. data/lib/heroprotocol/protocol40431.py +526 -0
  74. data/lib/heroprotocol/protocol40697.py +526 -0
  75. data/lib/heroprotocol/protocol40798.py +526 -0
  76. data/lib/herostats.rb +10 -0
  77. data/lib/herostats/exp_breakdown.rb +24 -0
  78. data/lib/herostats/game.rb +25 -0
  79. data/lib/herostats/init_data_parser.rb +45 -0
  80. data/lib/herostats/player.rb +25 -0
  81. data/lib/herostats/replay_parser.rb +34 -0
  82. data/lib/herostats/team.rb +10 -0
  83. data/lib/herostats/tracker_events_parser.rb +158 -0
  84. data/lib/herostats/version.rb +3 -0
  85. metadata +171 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 2e9eec958e321b00d2434120062516717d26d62b
4
+ data.tar.gz: 055ca62159d8f848df4e174a970bc45010d3c3ee
5
+ SHA512:
6
+ metadata.gz: d176418cf9aeb55778fbd173c6caa56245baddd42c76077d58dfac0e7bbf4c5fcd9fec36edaa4b2405fc0b4b31d85bba8f83eaf7b808d53075eafa0ec71ce05d
7
+ data.tar.gz: 0d5deb4bd12a5f5973593ffcfbce7f45727ffac74b61cbb4b07407ad65a4acd5d39b6817d6fe55ca01ef98dacf712ff8f5c05ab89d459c119f798253229c9bc9
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.3
4
+ before_install: gem install bundler -v 1.10.6
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in herostats.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2016 Ronald Leask
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,34 @@
1
+ # Herostats
2
+
3
+ Library for collecting stats from Heros of the Storm replays
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'herostats'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install herostats
20
+
21
+ ## Usage
22
+
23
+ Herostats.parse('/path/to/replay')
24
+
25
+ ## Development
26
+
27
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
28
+
29
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
30
+
31
+ ## Contributing
32
+
33
+ Bug reports and pull requests are welcome on GitHub at https://github.com/Helaisgem push squid-utils-0.1.0.gem/herostats. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
34
+
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "herostats"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,33 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'herostats/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'herostats'
8
+ spec.version = Herostats::VERSION
9
+ spec.authors = ['Ronald Leask']
10
+ spec.email = ['ronald.leask@gmail.com']
11
+
12
+ spec.summary = %q{Ruby library for extracting stats from Heroes of the Storm replays}
13
+ spec.description = %q{Ruby library for extracting important statistics from Heroes of the Storm replays}
14
+ spec.homepage = 'https://github.com/Helais/herostats'
15
+ spec.license = 'MIT'
16
+
17
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
18
+ # delete this section to allow pushing this gem to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
21
+ else
22
+ raise 'RubyGems 2.0 or newer is required to protect against public gem pushes.'
23
+ end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = 'exe'
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ['lib']
29
+
30
+ spec.add_development_dependency 'bundler', '~> 1.10'
31
+ spec.add_development_dependency 'rake', '~> 10.0'
32
+ spec.add_development_dependency 'minitest', '~> 5.8'
33
+ end
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2015 Blizzard Entertainment
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
@@ -0,0 +1,91 @@
1
+ # Hero Protocol
2
+
3
+ heroprotocol is a reference Python library and standalone tool to decode Heroes of the Storm replay files into Python data structures.
4
+
5
+ Currently heroprotocol can decode these structures and events:
6
+ * replay header
7
+ * game details
8
+ * replay init data
9
+ * game events
10
+ * message events
11
+ * tracker events
12
+
13
+ heroprotocol can be used as a base-build-specific library to decode binary blobs, or it can be run as a standalone tool to pretty print information from supported replay files.
14
+
15
+ Note that heroprotocol does not expose game balance information or provide any kind of high level analysis of replays; it's meant
16
+ to be just the first tool in the chain for your data mining application.
17
+
18
+ # Supported Versions
19
+
20
+ heroprotocol supports all Hereos of the Storm replay files that were written with retail versions of the game. The current plan is to support all future publicly released versions, including public betas.
21
+
22
+ # How to Use
23
+
24
+ A working installation of Python 2.x is required. From the folder where *heroprotocol* is located, type the following into the command line, assuming that the replay file was also copied into the same folder:
25
+ ```python
26
+ py heroprotocol.py --<option> "<replayFileName>" > output.txt
27
+ ```
28
+
29
+ If you want the output shown directly in the terminal, leave out the `> output.txt`.
30
+
31
+ ## Example Usage
32
+
33
+ ```python
34
+ py heroprotocol.py --details "Blackheart's Bay.StormReplay" > output.txt
35
+ ```
36
+
37
+ ## --<option> arguments
38
+
39
+ `-h, --help` Show the options that are available.
40
+
41
+ `--gameevents` print all game events including coordinates
42
+
43
+ `--messageevents` print message events such as ping events
44
+
45
+ `--trackerevents` print tracker events such as units killed, game stat events, score result event
46
+
47
+ `--attributeevents` print attribute events, a table of attrid, namespace, and attribute values
48
+
49
+ `--header` print protocol header including HotS build and elapsedGameLoops
50
+
51
+ `--details` print protocol details, e.g. teamId, player names and chosen heroes, player region, game result, observer status
52
+
53
+ `--initdata` print protocol initdata, e.g. interface settings for every player
54
+
55
+ `--stats` print game stats
56
+
57
+
58
+ # Tracker Events
59
+
60
+ Some notes on tracker events:
61
+ * Convert unit tag index, recycle pairs into unit tags (as seen in game events) with protocol.unit_tag(index, recycle)
62
+ * Interpret the NNet.Replay.Tracker.SUnitPositionsEvent events like this:
63
+
64
+ ```python
65
+ unitIndex = event['m_firstUnitIndex']
66
+ for i in xrange(0, len(event['m_items']), 3):
67
+ unitIndex += event['m_items'][i + 0]
68
+ x = event['m_items'][i + 1] * 4
69
+ y = event['m_items'][i + 2] * 4
70
+ # unit identified by unitIndex at the current event['_gameloop'] time is at approximate position (x, y)
71
+ ```
72
+ * Only units that have inflicted or taken damage are mentioned in unit position events, and they occur periodically with a limit of 256 units mentioned per event.
73
+ * NNet.Replay.Tracker.SUnitInitEvent events appear for units under construction. When complete you'll see a NNet.Replay.Tracker.SUnitDoneEvent with the same unit tag.
74
+ * NNet.Replay.Tracker.SUnitBornEvent events appear for units that are created fully constructed.
75
+ * You may receive a NNet.Replay.Tracker.SUnitDiedEvent after either a UnitInit or UnitBorn event for the corresponding unit tag.
76
+ * In NNet.Replay.Tracker.SPlayerStatsEvent, m_scoreValueFoodUsed and m_scoreValueFoodMade are in fixed point (divide by 4096 for integer values). All other values are in integers.
77
+ * There's a known issue where revived units are not tracked, and placeholder units track death but not birth.
78
+
79
+ # License
80
+
81
+ Copyright (c) 2015 Blizzard Entertainment
82
+
83
+ Open sourced under the MIT license. See the included LICENSE file for more information.
84
+
85
+ # Acknowledgements
86
+
87
+ The standalone tool uses [mpyq](https://github.com/eagleflo/mpyq) to read mopaq files.
88
+
89
+ Thanks to David Joerg and Graylin Kim of [GGTracker](http://www.ggtracker.com) for design feedback and beta-testing of the s2protocol library that heroprotocol is based upon.
90
+
91
+ Thanks to Ben Barrett of [HOTSLogs](http://www.hotslogs.com) for feedback on and beta-testing of the heroprotocol library.
File without changes
@@ -0,0 +1,311 @@
1
+ # Copyright (c) 2015 Blizzard Entertainment
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in
11
+ # all copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ # THE SOFTWARE.
20
+
21
+ import struct
22
+
23
+
24
+ class TruncatedError(Exception):
25
+ pass
26
+
27
+
28
+ class CorruptedError(Exception):
29
+ pass
30
+
31
+
32
+ class BitPackedBuffer:
33
+ def __init__(self, contents, endian='big'):
34
+ self._data = contents or []
35
+ self._used = 0
36
+ self._next = None
37
+ self._nextbits = 0
38
+ self._bigendian = (endian == 'big')
39
+
40
+ def __str__(self):
41
+ return 'buffer(%02x/%d,[%d]=%s)' % (
42
+ self._nextbits and self._next or 0, self._nextbits,
43
+ self._used, '%02x' % (ord(self._data[self._used]),) if (self._used < len(self._data)) else '--')
44
+
45
+ def done(self):
46
+ return self._nextbits == 0 and self._used >= len(self._data)
47
+
48
+ def used_bits(self):
49
+ return self._used * 8 - self._nextbits
50
+
51
+ def byte_align(self):
52
+ self._nextbits = 0
53
+
54
+ def read_aligned_bytes(self, bytes):
55
+ self.byte_align()
56
+ data = self._data[self._used:self._used + bytes]
57
+ self._used += bytes
58
+ if len(data) != bytes:
59
+ raise TruncatedError(self)
60
+ return data
61
+
62
+ def read_bits(self, bits):
63
+ result = 0
64
+ resultbits = 0
65
+ while resultbits != bits:
66
+ if self._nextbits == 0:
67
+ if self.done():
68
+ raise TruncatedError(self)
69
+ self._next = ord(self._data[self._used])
70
+ self._used += 1
71
+ self._nextbits = 8
72
+ copybits = min(bits - resultbits, self._nextbits)
73
+ copy = (self._next & ((1 << copybits) - 1))
74
+ if self._bigendian:
75
+ result |= copy << (bits - resultbits - copybits)
76
+ else:
77
+ result |= copy << resultbits
78
+ self._next >>= copybits
79
+ self._nextbits -= copybits
80
+ resultbits += copybits
81
+ return result
82
+
83
+ def read_unaligned_bytes(self, bytes):
84
+ return ''.join([chr(self.read_bits(8)) for i in xrange(bytes)])
85
+
86
+
87
+ class BitPackedDecoder:
88
+ def __init__(self, contents, typeinfos):
89
+ self._buffer = BitPackedBuffer(contents)
90
+ self._typeinfos = typeinfos
91
+
92
+ def __str__(self):
93
+ return self._buffer.__str__()
94
+
95
+ def instance(self, typeid):
96
+ if typeid >= len(self._typeinfos):
97
+ raise CorruptedError(self)
98
+ typeinfo = self._typeinfos[typeid]
99
+ return getattr(self, typeinfo[0])(*typeinfo[1])
100
+
101
+ def byte_align(self):
102
+ self._buffer.byte_align()
103
+
104
+ def done(self):
105
+ return self._buffer.done()
106
+
107
+ def used_bits(self):
108
+ return self._buffer.used_bits()
109
+
110
+ def _array(self, bounds, typeid):
111
+ length = self._int(bounds)
112
+ return [self.instance(typeid) for i in xrange(length)]
113
+
114
+ def _bitarray(self, bounds):
115
+ length = self._int(bounds)
116
+ return (length, self._buffer.read_bits(length))
117
+
118
+ def _blob(self, bounds):
119
+ length = self._int(bounds)
120
+ result = self._buffer.read_aligned_bytes(length)
121
+ return result
122
+
123
+ def _bool(self):
124
+ return self._int((0, 1)) != 0
125
+
126
+ def _choice(self, bounds, fields):
127
+ tag = self._int(bounds)
128
+ if tag not in fields:
129
+ raise CorruptedError(self)
130
+ field = fields[tag]
131
+ return {field[0]: self.instance(field[1])}
132
+
133
+ def _fourcc(self):
134
+ return self._buffer.read_unaligned_bytes(4)
135
+
136
+ def _int(self, bounds):
137
+ return bounds[0] + self._buffer.read_bits(bounds[1])
138
+
139
+ def _null(self):
140
+ return None
141
+
142
+ def _optional(self, typeid):
143
+ exists = self._bool()
144
+ return self.instance(typeid) if exists else None
145
+
146
+ def _real32(self):
147
+ return struct.unpack('>f', self._buffer.read_unaligned_bytes(4))
148
+
149
+ def _real64(self):
150
+ return struct.unpack('>d', self._buffer.read_unaligned_bytes(8))
151
+
152
+ def _struct(self, fields):
153
+ result = {}
154
+ for field in fields:
155
+ if field[0] == '__parent':
156
+ parent = self.instance(field[1])
157
+ if isinstance(parent, dict):
158
+ result.update(parent)
159
+ elif len(fields) == 1:
160
+ result = parent
161
+ else:
162
+ result[field[0]] = parent
163
+ else:
164
+ result[field[0]] = self.instance(field[1])
165
+ return result
166
+
167
+
168
+ class VersionedDecoder:
169
+ def __init__(self, contents, typeinfos):
170
+ self._buffer = BitPackedBuffer(contents)
171
+ self._typeinfos = typeinfos
172
+
173
+ def __str__(self):
174
+ return self._buffer.__str__()
175
+
176
+ def instance(self, typeid):
177
+ if typeid >= len(self._typeinfos):
178
+ raise CorruptedError(self)
179
+ typeinfo = self._typeinfos[typeid]
180
+ return getattr(self, typeinfo[0])(*typeinfo[1])
181
+
182
+ def byte_align(self):
183
+ self._buffer.byte_align()
184
+
185
+ def done(self):
186
+ return self._buffer.done()
187
+
188
+ def used_bits(self):
189
+ return self._buffer.used_bits()
190
+
191
+ def _expect_skip(self, expected):
192
+ if self._buffer.read_bits(8) != expected:
193
+ raise CorruptedError(self)
194
+
195
+ def _vint(self):
196
+ b = self._buffer.read_bits(8)
197
+ negative = b & 1
198
+ result = (b >> 1) & 0x3f
199
+ bits = 6
200
+ while (b & 0x80) != 0:
201
+ b = self._buffer.read_bits(8)
202
+ result |= (b & 0x7f) << bits
203
+ bits += 7
204
+ return -result if negative else result
205
+
206
+ def _array(self, bounds, typeid):
207
+ self._expect_skip(0)
208
+ length = self._vint()
209
+ return [self.instance(typeid) for i in xrange(length)]
210
+
211
+ def _bitarray(self, bounds):
212
+ self._expect_skip(1)
213
+ length = self._vint()
214
+ return (length, self._buffer.read_aligned_bytes((length + 7) / 8))
215
+
216
+ def _blob(self, bounds):
217
+ self._expect_skip(2)
218
+ length = self._vint()
219
+ return self._buffer.read_aligned_bytes(length)
220
+
221
+ def _bool(self):
222
+ self._expect_skip(6)
223
+ return self._buffer.read_bits(8) != 0
224
+
225
+ def _choice(self, bounds, fields):
226
+ self._expect_skip(3)
227
+ tag = self._vint()
228
+ if tag not in fields:
229
+ self._skip_instance()
230
+ return {}
231
+ field = fields[tag]
232
+ return {field[0]: self.instance(field[1])}
233
+
234
+ def _fourcc(self):
235
+ self._expect_skip(7)
236
+ return self._buffer.read_aligned_bytes(4)
237
+
238
+ def _int(self, bounds):
239
+ self._expect_skip(9)
240
+ return self._vint()
241
+
242
+ def _null(self):
243
+ return None
244
+
245
+ def _optional(self, typeid):
246
+ self._expect_skip(4)
247
+ exists = self._buffer.read_bits(8) != 0
248
+ return self.instance(typeid) if exists else None
249
+
250
+ def _real32(self):
251
+ self._expect_skip(7)
252
+ return struct.unpack('>f', self._buffer.read_aligned_bytes(4))
253
+
254
+ def _real64(self):
255
+ self._expect_skip(8)
256
+ return struct.unpack('>d', self._buffer.read_aligned_bytes(8))
257
+
258
+ def _struct(self, fields):
259
+ self._expect_skip(5)
260
+ result = {}
261
+ length = self._vint()
262
+ for i in xrange(length):
263
+ tag = self._vint()
264
+ field = next((f for f in fields if f[2] == tag), None)
265
+ if field:
266
+ if field[0] == '__parent':
267
+ parent = self.instance(field[1])
268
+ if isinstance(parent, dict):
269
+ result.update(parent)
270
+ elif len(fields) == 1:
271
+ result = parent
272
+ else:
273
+ result[field[0]] = parent
274
+ else:
275
+ result[field[0]] = self.instance(field[1])
276
+ else:
277
+ self._skip_instance()
278
+ return result
279
+
280
+ def _skip_instance(self):
281
+ skip = self._buffer.read_bits(8)
282
+ if skip == 0: # array
283
+ length = self._vint()
284
+ for i in xrange(length):
285
+ self._skip_instance()
286
+ elif skip == 1: # bitblob
287
+ length = self._vint()
288
+ self._buffer.read_aligned_bytes((length + 7) / 8)
289
+ elif skip == 2: # blob
290
+ length = self._vint()
291
+ self._buffer.read_aligned_bytes(length)
292
+ elif skip == 3: # choice
293
+ tag = self._vint()
294
+ self._skip_instance()
295
+ elif skip == 4: # optional
296
+ exists = self._buffer.read_bits(8) != 0
297
+ if exists:
298
+ self._skip_instance()
299
+ elif skip == 5: # struct
300
+ length = self._vint()
301
+ for i in xrange(length):
302
+ tag = self._vint()
303
+ self._skip_instance()
304
+ elif skip == 6: # u8
305
+ self._buffer.read_aligned_bytes(1)
306
+ elif skip == 7: # u32
307
+ self._buffer.read_aligned_bytes(4)
308
+ elif skip == 8: # u64
309
+ self._buffer.read_aligned_bytes(8)
310
+ elif skip == 9: # vint
311
+ self._vint()