Skip to content

Towards proper implementation of str and bytes types and conversion between them #349

@pfalcon

Description

@pfalcon

Ok, so let's continue where #8 (comment) stopped. What we have now is:

$ ./micropython
>>> bytes
<function>
>>> str
<function>
>>> 
>>> type(bytes("str"))
<class 'str'>

So, we have 2 issues issues here: a) str and bytes are not types like they should be; b) conversion to bytes doesn't return object of expected type.

And the latter is the main issue. So, let's have requirement that if we Python3 has dreadful dichotomy between str and bytes, and we have no choice but to follow its way, then let's have conversion between str and bytes be efficient as possible, specifically take O(1) of length of underlying string, in particular not duplicate string content (both objects are immutable and content is the same).

That's why in #8 (comment) I considered following problematic:

The storage for the dynamic string would like mp_obj_tulpe_t: a uPy header then the actual data (plus any extra info you wanted, like len and alloc).

With that, optimal type conversion str <-> bytes cannot be implemented.

So, the plan:

typedef struct _mp_obj_str_t {
    mp_obj_base_t base;
    machine_uint_t hash : 16;
    machine_uint_t len : 16;
    byte data[];
} mp_obj_str_t;

Should become:

typedef struct _mp_obj_str_t {
    mp_obj_base_t base;
    machine_uint_t hash : 16;
    machine_uint_t len : 16;
    byte *data;
} mp_obj_str_t;

So, the implementation of both str(obj, enc) and bytes(obj, enc) will be allocating such structure, but reuse data pointer from previous object.

But note that we then waste memory for storing hash and len in such type structures - they depend only on data, and thus the same for particular data, so should rather be part of this data. That's how we come again to what I've been talking about in #8 and #22 for a long time ;-).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy