Пример #1
0
  /**
   * Read into the given PyObject that implements the Jython buffer API (with write access) or is a
   * PyArray.
   *
   * @param buf a PyObject compatible with the buffer API
   * @return the amount of data read as an int
   */
  public int readinto(PyObject buf) {

    // This is an inefficient version of readinto: but readinto is
    // not recommended for use in Python 2.x anyway

    if (buf instanceof PyArray) {
      // PyArray has the buffer interface but it only works for bytes at present
      PyArray array = (PyArray) buf;
      String read = read(array.__len__());
      for (int i = 0; i < read.length(); i++) {
        array.set(i, new PyString(read.charAt(i)));
      }
      return read.length();

    } else if (buf instanceof BufferProtocol) {
      try (PyBuffer view = ((BufferProtocol) buf).getBuffer(PyBUF.FULL_RO)) {
        if (view.isReadonly()) {
          // More helpful than falling through to CPython message
          throw Py.TypeError("cannot read into read-only " + buf.getType().fastGetName());
        } else {
          // Inefficiently, we have to go via a String
          String read = read(view.getLen());
          int n = read.length();
          for (int i = 0; i < n; i++) {
            view.storeAt((byte) read.charAt(i), i);
          }
          return read.length();
        }
      }
    }

    // No valid alternative worked
    throw Py.TypeError("argument 1 must be read-write buffer, not " + buf.getType().fastGetName());
  }
Пример #2
0
 public static PyTuple unpack(String format, PyArray buffer) {
   String string = buffer.tostring();
   FormatDef[] f = whichtable(format);
   int size = calcsize(format, f);
   int len = string.length();
   if (size != len) throw StructError("unpack str size does not match format");
   return unpack(f, size, format, new ByteStream(string));
 }
Пример #3
0
  static void pack_into(String format, FormatDef[] f, int size, int argstart, PyObject[] args) {
    if (args.length - argstart < 2) Py.TypeError("illegal argument type for built-in operation");
    if (!(args[argstart] instanceof PyArray)) {
      throw Py.TypeError("pack_into takes an array arg"); // as well as a buffer, what else?
    }
    PyArray buffer = (PyArray) args[argstart];
    int offset = args[argstart + 1].asInt();

    ByteStream res = pack(format, f, size, argstart + 2, args);
    if (res.pos > buffer.__len__()) {
      throw StructError(
          "pack_into requires a buffer of at least " + res.pos + " bytes, got " + buffer.__len__());
    }
    for (int i = 0; i < res.pos; i++, offset++) {
      char val = res.data[i];
      buffer.set(offset, val);
    }
  }