1"""
2Example data formatters for strings represented as (pointer,length) pairs
3encoded in UTF8/16/32 for use with the LLDB debugger
4
5To use in your projects, tweak the children names as appropriate for your data structures
6and use as summaries for your data types
7
8Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
9See https://llvm.org/LICENSE.txt for license information.
10SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
11"""
12
13import lldb
14
15
16def utf8_summary(value, unused):
17    pointer = value.GetChildMemberWithName("first").GetValueAsUnsigned(0)
18    length = value.GetChildMemberWithName("second").GetValueAsUnsigned(0)
19    if pointer == 0:
20        return False
21    if length == 0:
22        return '""'
23    error = lldb.SBError()
24    string_data = value.process.ReadMemory(pointer, length, error)
25    return '"%s"' % (string_data)  # utf8 is safe to emit as-is on OSX
26
27
28def utf16_summary(value, unused):
29    pointer = value.GetChildMemberWithName("first").GetValueAsUnsigned(0)
30    length = value.GetChildMemberWithName("second").GetValueAsUnsigned(0)
31    # assume length is in bytes - if in UTF16 chars, just multiply by 2
32    if pointer == 0:
33        return False
34    if length == 0:
35        return '""'
36    error = lldb.SBError()
37    string_data = value.process.ReadMemory(pointer, length, error)
38    # utf8 is safe to emit as-is on OSX
39    return '"%s"' % (string_data.decode('utf-16').encode('utf-8'))
40
41
42def utf32_summary(value, unused):
43    pointer = value.GetChildMemberWithName("first").GetValueAsUnsigned(0)
44    length = value.GetChildMemberWithName("second").GetValueAsUnsigned(0)
45    # assume length is in bytes - if in UTF32 chars, just multiply by 4
46    if pointer == 0:
47        return False
48    if length == 0:
49        return '""'
50    error = lldb.SBError()
51    string_data = value.process.ReadMemory(pointer, length, error)
52    # utf8 is safe to emit as-is on OSX
53    return '"%s"' % (string_data.decode('utf-32').encode('utf-8'))
54