Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions src/core/IronPython.Modules/_struct.cs
Original file line number Diff line number Diff line change
Expand Up @@ -899,15 +899,21 @@ private readonly struct Format(FormatType type, int count) {
private static CacheDict<string, Struct> _cache = new CacheDict<string, Struct>(MAX_CACHE_SIZE);

private static string FormatObjectToString(object fmt) {
if (fmt is IList<byte> b) {
return PythonOps.MakeString(b);
}
if (Converter.TryConvertToString(fmt, out string res)) {
// replicate CPython behaviour: throws UnicodeEncodeError if non-ASCII
StringOps.DoEncodeAscii(res);
return res;
if (fmt is Bytes b) return PythonOps.MakeString(b);

string str = fmt switch {
string s => s,
Extensible<string> es => es.Value,
_ => throw PythonOps.TypeError("Struct() argument 1 must be a str or bytes object, not {0}", PythonOps.GetPythonTypeName(fmt)),
};
foreach (char c in str) {
if (c > 0x7f) {
// replicate CPython behaviour: throws UnicodeEncodeError if non-ASCII
StringOps.DoEncodeAscii(str);
break;
}
}
throw PythonOps.TypeError("Struct() argument 1 must be a str or bytes object, not {0}", PythonOps.GetPythonTypeName(fmt));
return str;
}

private static Struct GetStructFromCache(CodeContext/*!*/ context, object fmt) {
Expand Down
2 changes: 1 addition & 1 deletion src/core/IronPython/Runtime/PythonTuple.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ internal static PythonTuple Make(object o) {

internal static PythonTuple MakeTuple(params object?[] items) {
if (items.Length == 0) return EMPTY;
return new PythonTuple(DefaultContext.Default, items);
return new PythonTuple(items);
}

private static object?[] MakeItems(CodeContext context, object? o) {
Expand Down
15 changes: 15 additions & 0 deletions tests/suite/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,21 @@ def test_format_string_ascii_and_whitespace(self):
with self.assertRaises(struct.error):
struct.calcsize(bytes([0xff]))

def test_format_types(self):
class B(bytes): pass
class S(str): pass
for fmt in (b'>H', B(b'>H'), S('>H')):
self.assertEqual(struct.Struct(fmt).format, '>H')
self.assertEqual(struct.calcsize(fmt), 2)
with self.assertRaises(UnicodeEncodeError):
struct.calcsize(S(chr(0x0662)))
class C:
def __str__(self): return '>H'
# avoid a cached format: memoryview(b'>H') == b'>H' hits CPython's cache (fixed by https://github.com/python/cpython/issues/85943)
for fmt in (bytearray(b'@7x'), memoryview(b'@7x'), C(), 1):
self.assertRaises(TypeError, struct.Struct, fmt)
self.assertRaises(TypeError, struct.calcsize, fmt)

def test_pack_into(self):
# test string format string
result = array.array('b', [0, 0])
Expand Down
Loading