Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 108 lines (99 sloc) 2.273 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
// Embedded bencode support, header definitions.
// 2012-09-29 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

#include "EmBencode.h"

enum { EMB_ANY, EMB_LEN, EMB_INT, EMB_STR };

uint8_t EmBdecode::reset () {
  count = next;
  level = next = 0;
  state = EMB_ANY;
  return count;
}

uint8_t EmBdecode::process (char ch) {
  switch (state) {
    case EMB_ANY:
      if (ch < '0' || ch > '9') {
        if (ch == 'i') {
          AddToBuf(T_NUMBER);
          state = EMB_INT;
        } else if (ch == 'd' || ch == 'l') {
          AddToBuf(ch == 'd' ? T_DICT : T_LIST);
          ++level;
        } else if (ch == 'e') {
          AddToBuf(T_POP);
          --level;
          break; // end of dict or list
        }
        return 0;
      }
      state = EMB_LEN;
      count = 0;
      // fall through
    case EMB_LEN:
      if (ch == ':') {
        AddToBuf(T_STRING + count);
        if (count == 0) {
          AddToBuf(0);
          break; // empty string
        }
        state = EMB_STR;
      } else
        count = 10 * count + (ch - '0');
      return 0;
    case EMB_STR:
      AddToBuf(ch);
      if (--count == 0) {
        AddToBuf(0);
        break; // end of string
      }
      return 0;
    case EMB_INT:
      if (ch == 'e') {
        AddToBuf(0);
        break; // end of int
      }
      AddToBuf(ch);
      return 0;
  }
  // end of an item reached
  if (level > 0) {
    state = EMB_ANY;
    return 0;
  }
  AddToBuf(T_END);
  return reset(); // not in dict or list, data is complete
}

void EmBdecode::AddToBuf (char ch) {
  if (next >= bufLen)
    bufPtr[0] = T_END; // mark entire buffer as empty
  else
    bufPtr[next++] = ch;
}

uint8_t EmBdecode::nextToken () {
  uint8_t ch = bufPtr[next++];
  last = next;
  switch (ch) {
    default: // string
      next += ch + 1;
      return T_STRING;
    case T_NUMBER:
      while (bufPtr[next++] != 0)
        ;
      break;
    case T_END:
      --next; // don't advance past end token
      // fall through
    case T_DICT:
    case T_LIST:
    case T_POP:
      break;
  }
  return ch;
}

const char* EmBdecode::asString (uint8_t* plen) {
  if (plen != 0)
    *plen = next - last - 1;
  return bufPtr + last;
}

long EmBdecode::asNumber () {
  return atol(bufPtr + last);
}
Something went wrong with that request. Please try again.