Commit Graph

1934 Commits

Author SHA1 Message Date
Max Wipfli
3b04420490 AK: Don't create Utf8View from temporary String in URLParser
This fixes a bug where a Utf8View was created with data from a temporary
string, which was immediately deleted. This lead to a use-after-free
issue. This also changes most occurences for StringBuilder::to_string in
URLParser to use ::string_view(), as the value is passed as StringView
const& most of the time anyways.

This fixes oss-fuzz issue 34973.
2021-06-08 19:08:02 +02:00
Max Wipfli
3c7e775a9a AK: Utf8CodePointIterator: Don't output full string to debug output
When a code point is invalid, the full string was outputted to the debug
output. For large strings, this can make the system quite slow.
Furthermore, one of the cases incorrectly assumed the data to be null
terminated. This patch modifies the debug statements not to print the
full string.

This fixes oss-fuzz issue 35050.
2021-06-08 19:08:02 +02:00
Gunnar Beutner
d2662df57c LibC+AK: Remove our custom macros from <assert.h>
Other software might not expect these to be defined and behave
differently if they _are_ defined, e.g. scummvm which checks if
the TODO macro is defined and fails to build if it is.
2021-06-08 17:29:57 +02:00
Max Wipfli
1e8006ebb8 AK: Add children() accessor to Trie 2021-06-08 12:15:04 +02:00
Andreas Kling
7cbe4daa7c LibJS: Move bytecode debug spam behind JS_BYTECODE_DEBUG :^) 2021-06-07 18:11:59 +02:00
Brian Gianforcaro
f5e04759cc AK: Add IntrusiveList::size_slow() to match InlineLinkedList
The functionality is needed to replace InlineLinkedList with
IntrusiveList in the Kernel Process class.
2021-06-07 09:42:55 +02:00
FalseHonesty
403bb07443 LibVideo: Scaffold LibVideo and implement simplistic Matroska parser
This commit initializes the LibVideo library and implements parsing
basic Matroska container files. Currently, it will only parse audio
and video tracks.
2021-06-06 17:47:00 +02:00
Linus Groh
0a7e91329f Revert "Revert "AK: Always inline FlyString::view()""
This reverts commit f09216ac42.
This was supposed to be a local test only, didn't mean to push it. :^)
2021-06-06 08:05:49 +01:00
Linus Groh
f09216ac42 Revert "AK: Always inline FlyString::view()"
This reverts commit 66f15c2e0c.
2021-06-06 01:58:09 +01:00
Idan Horowitz
2011fcff24 AK: Add the parse_ascii_base36_digit method
This is similar to parse_ascii_hex_digit but can parse the whole A-Z
range (also known as base36).
2021-06-06 01:34:22 +01:00
Ali Mohammad Pur
51c2c69357 AK+Everywhere: Disallow constructing Functions from incompatible types
Previously, AK::Function would accept _any_ callable type, and try to
call it when called, first with the given set of arguments, then with
zero arguments, and if all of those failed, it would simply not call the
function and **return a value-constructed Out type**.
This lead to many, many, many hard to debug situations when someone
forgot a `const` in their lambda argument types, and many cases of
people taking zero arguments in their lambdas to ignore them.
This commit reworks the Function interface to not include any such
surprising behaviour, if your function instance is not callable with
the declared argument set of the Function, it can simply not be
assigned to that Function instance, end of story.
2021-06-06 00:27:30 +04:30
Andreas Kling
66f15c2e0c AK: Always inline FlyString::view() 2021-06-05 12:36:14 +02:00
Max Wipfli
2164d8aae8 AK: Stop using U+0000 as end of file code point in URL parser
This changes URL parser to use the 0xFFFFFFFF constant instead of 0 to
indicate end of file. This fixes a bug where inputs containing null
bytes would terminate the parser early, because they were interpreted
as end of file.
2021-06-05 10:53:31 +02:00
Max Wipfli
97425c7dfb AK: Make debugging URLParser easier
This patch adds a state_name method to URLParser to convert a state to a
string. With this, the debugging statements now display the state names.

Furthermore, this fixes a bug where non-ASCII code points were
formatted as characters, which fails an assertion in the formatting
system.
2021-06-05 10:53:31 +02:00
Max Wipfli
99d5555134 AK: Do not trim away non-ASCII bytes when parsing URL
Because non-ASCII code points have negative byte values, trimming away
control characters requires checking for negative bytes values.

This also adds a test case with a URL containing non-ASCII code points.
2021-06-05 10:53:31 +02:00
Max Wipfli
44937e2dfc AK: Update URLParser.{cpp,h} to use east const 2021-06-05 10:53:31 +02:00
Gunnar Beutner
8f81d9ad90 AK: Verify that functions aren't modified while they're being invoked
A Function object should not be set to a different functor while the
original functor is currently executing.
2021-06-04 19:32:25 +02:00
Gunnar Beutner
44418cb351 AK: Allow deferring clear() for the Function class
Ideally a Function should not be clear()ed while it's running.
Unfortunately a number of callers do just that and identifying all of
them would require inspecting all call sites for operator() and clear().

Instead this adds support for deferring clear() until after the
function has finished executing.
2021-06-04 19:32:25 +02:00
Ali Mohammad Pur
824a40e95b AK: Inline *String::is_one_of<Ts...>()
Previously this was generating a crazy number of symbols, and it was
also pretty-damn-slow as it was defined recursively, which made the
compiler incapable of inlining it (due to the many many layers of
recursion before it terminated).
This commit replaces the recursion with a pack expansion and marks it
always-inline.
2021-06-04 12:57:14 +02:00
R Smith
5a6f0ef1bc AK: Don’t drop lines between \r and \n in StringView::lines() (#7662)
StringView::lines() supports line-separators “\n”, “\r”, and “\r\n”.
The method will drop an entire line if it is surrounded by “\r”
and “\n” separators on the left and right sides respectively.
2021-06-04 12:06:08 +04:30
DexesTTP
e01f1c949f AK: Do not VERIFY on invalid code point bytes in UTF8View
The previous behavior was to always VERIFY that the UTF-8 bytes were
valid when iterating over the code points of an UTF8View. This change
makes it so we instead output the 0xFFFD 'REPLACEMENT CHARACTER'
code point when encountering invalid bytes, and keep iterating the
view after skipping one byte.

Leaving the decision to the consumer would break symmetry with the
UTF32View API, which would in turn require heavy refactoring and/or
code duplication in generic code such as the one found in
Gfx::Painter and the Shell.

To make it easier for the consumers to detect the original bytes, we
provide a new method on the iterator that returns a Span over the
data that has been decoded. This method is immediately used in the
TextNode::compute_text_for_rendering method, which previously did
this in a ad-hoc waay.

This also add tests for the new behavior in TestUtf8.cpp, as well
as reinforcements to the existing tests to check if the underlying
bytes match up with their expected values.
2021-06-03 18:28:27 +04:30
Max Wipfli
bc8d16ad28 Everywhere: Replace ctype.h to avoid narrowing conversions
This replaces ctype.h with CharacterType.h everywhere I could find
issues with narrowing conversions. While using it will probably make
sense almost everywhere in the future, the most critical places should
have been addressed.
2021-06-03 13:31:46 +02:00
Max Wipfli
f4a4c36fa0 AK: Add CharacterTypes.h
This patch introduces CharacterTypes.h, which aims to be a replacement
for most usages of ctype.h. In contrast to that implementation, this
header makes use of exclusively constexpr functions and support the full
Unicode code point set without any narrowing-conversion issues.
2021-06-03 13:31:46 +02:00
Brian Gianforcaro
ef4fdcf76f AK: Add reverse iterator support to AK::IntrusiveList
In order for IntrusiveList to be capable of replacing InlineLinkedList,
it needs to support reverse iteration. InlineLinkedList currently
supports manual reverse iteration by calling list->last() followed by
node->prev().
2021-06-03 13:27:40 +02:00
Gunnar Beutner
48da8a568d
AK: Remove unused JsonValue <=> IPv4Address conversion code
This removes code that isn't used anywhere.
2021-06-03 11:56:32 +01:00
Gunnar Beutner
a4f320c76b AK: Allow inlining more string functions 2021-06-03 08:06:51 +02:00
Gunnar Beutner
ed0068d04d AK: Allow inlining ref-count functionality
Previously we'd incur the costs for a function call via the PLT even
for the most trivial ref-count actions like increasing/decreasing the
reference count.

By moving the code to the header file we allow the compiler to inline
this code into the caller's function.
2021-06-03 08:06:51 +02:00
Ali Mohammad Pur
ea7ba34a31 AK+LibWasm+LibJS: Disallow Variant.has() on types that aren't contained
Checking for this (and get()'ing it) is always invalid, so let's just
disallow it.
This also finds two bugs where the code is checking for types that can
never actually be in the variant (which was actually a refactor
artifact).
2021-06-02 18:02:47 +02:00
Ali Mohammad Pur
6cd9906f60 AK: Make checked division also check for divide by zero 2021-06-02 16:09:16 +04:30
Ali Mohammad Pur
944855ca18 AK+Everywhere: Fix compiletime format parsing of replacement fields 2021-06-01 23:12:17 +04:30
Andreas Kling
c0d1a75881 AK: Strip leading/trailing C0-control-or-space in URLs correctly
We have to stop scanning once we hit a non-strippable character.
Add some tests to cover this.
2021-06-01 13:22:04 +02:00
Max Wipfli
2e23954271 AK: Move identity check from URL::operator==() to equals() 2021-06-01 12:23:16 +02:00
Max Wipfli
33396494f6 AK+LibWeb: Remove URL::to_string_encoded()
This replaces URL::to_string_encoded() with to_string() and removes the
former, since they are now equivalent.
2021-06-01 12:23:16 +02:00
Max Wipfli
a9114be1b8 AK: Use correct constness in URL class methods
This changes the URL class to use the correct constness for getters,
setters and other methods. It also changes the entire class to use east
const style.
2021-06-01 12:23:16 +02:00
Max Wipfli
f3fda59abd AK: Enable direct comparsion of Optional<T> and T
This patch introduces a new operator== to compare an Optional to its
contained type directly. If the Optional does not contain a value, the
comparison will always return false.

This also adds a test case for the new behavior as well as comparison
between Optional objects themselves.
2021-06-01 11:38:17 +02:00
Andreas Kling
12a42edd13 Everywhere: codepoint => code point 2021-06-01 10:01:11 +02:00
Andreas Kling
a8ae8b24de AK: Rename Utf32CodepointIterator => Utf32CodePointIterator 2021-06-01 09:46:19 +02:00
Andreas Kling
407d6cd9e4 AK: Rename Utf8CodepointIterator => Utf8CodePointIterator 2021-06-01 09:45:52 +02:00
Max Wipfli
5caaa52bee AK: Add hostname parameter to URL::create_with_file_scheme()
This adds a hostname parameter as the third parameter to
URL::create_with_file_scheme(). If the hostname is "localhost", it will
be ignored (as per the URL specification).

This can for example be used by ls(1) to create more conforming file
URLs.
2021-06-01 09:28:05 +02:00
Max Wipfli
ebf074ca29 AK: Rewrite URL::compute_validity() to conform to new parser
This rewrites the URL validation check to be more specific, so it can
more accurately detect if a user of URL class constructs invalid URLs by
hand.
2021-06-01 09:28:05 +02:00
Max Wipfli
522ef53b98 AK: Remove deprecated m_path member variable from URL
The m_path member variable has been superseded by m_paths. Thus, it has
been removed. The path() getter will continue to exist as a convenience
method for getting the path joined together as a string.
2021-06-01 09:28:05 +02:00
Max Wipfli
b7c6af0a04 AK: Replace URL::to_string() with new serialize() implementation 2021-06-01 09:28:05 +02:00
Max Wipfli
81f03e7a5d AK: Replace old URL parser with new URLParser::parse()
This replaces the old URL::parse() and URL::complete_url() parsing
mechanisms with the new spec-compliant URLParser::parse().
2021-06-01 09:28:05 +02:00
Max Wipfli
1697f3c35b AK: Add spec-compliant URL serialization methods
This adds URL serialization methods which are more in line with the
specification.

The serialize_for_display() method should be used e.g. in the browser
address bar, and as per the spec should not display username and
password. Furthermore, it could decode most percent-encoded code points,
although that is not implemented yet.
2021-06-01 09:28:05 +02:00
Max Wipfli
0d0ed4962f AK: Add a new, spec-compliant URLParser
This adds a new URL parser, which aims to be compliant with the URL
specification (https://url.spec.whatwg.org/). It also contains a
rudimentary data URL parser.
2021-06-01 09:28:05 +02:00
Max Wipfli
8a938a3e25 AK: Add helper functions and private data URL constructor to URL
This adds a few helper functions and a private constructor to
instantiate a data URL to the URL class. These will be needed by the
upcoming URL parser.
2021-06-01 09:28:05 +02:00
Max Wipfli
dd392dfa03 AK: Add member variables to the URL class
This adds the m_username, m_password, m_paths and m_cannot_be_a_base_url
member variables to the URL class. These are necessary for the upcoming
new URL parser.

The deprecated m_path variable shadows the m_paths variable if it is
non-null. This behavior will be removed once the old URL parser has been
removed.
2021-06-01 09:28:05 +02:00
Max Wipfli
0d41a7d39a AK: Remove URLParser
This removes URLParser, because its two exposed functions, urlencode()
and urldecode(), have been superseded by URL::percent_encode() and
URL::percent_decode(). This is in preparation for the introduction of a
new URL parser.
2021-06-01 09:28:05 +02:00
Max Wipfli
a603e69599 AK+Everywhere: Replace usages of URLParser::urlencode() and urldecode()
This replaces all occurrences of those functions with the newly
implemented functions URL::percent_encode() and URL::percent_decode().
The old functions will be removed in a further commit.
2021-06-01 09:28:05 +02:00
Max Wipfli
2a6c9bc5f7 AK: Implement more conforming URL percent encode/decode mechanism
This adds a few new functions to percent encode/decode strings according
to the URL specification. The functions allow specifying a
PercentEncodeSet, which is defined by the specification. It will be used
to replace the current urlencode() and urldecode() functions in a
further commit.

This commit adds a few duplicate helper functions in the URL class, such
as is_digit() and is_ascii_digit(). This will be cleaned up as soon as
the upcoming new URL parser will replace the current one.
2021-06-01 09:28:05 +02:00
Max Wipfli
0e4f7aa8e8 AK: Add trim() method to String, StringView and StringUtils
The methods added make it possible to use the trim mechanism with
specified characters, unlike trim_whitespace(), which uses predefined
characters.
2021-06-01 09:28:05 +02:00
Max Wipfli
14506e8f5e AK: Implement Utf8CodepointIterator::peek(size_t)
This adds a peek method for Utf8CodepointIterator, which enables it to
be used in some parsing cases where peeking is necessary.

peek(0) is equivalent to operator*, expect that peek() does not contain
any assertions and will just return an empty Optional<u32>.

This also implements a test case for iterating UTF-8.
2021-06-01 09:28:05 +02:00
Max Wipfli
31f6ba0952 AK: Internally rename protocol to scheme in URL
This renames all references to protocol to scheme, which is the name
used by the URL standard (https://url.spec.whatwg.org/). Externally, all
methods referencing "protocol" were duplicated with "scheme". The old
methods still exist as compatibility.
2021-06-01 09:28:05 +02:00
Max Wipfli
d6709ac87d AK: Omit unnecessary function parameter names in URL
This patch removes unnecessary function parameter names in declarations
of the URL class. It also changes parameter types from String to
StringView where applicable.
2021-06-01 09:28:05 +02:00
Linus Groh
028a337a6d AK: Add Formatter<unsigned char[Size]> 2021-05-31 17:43:54 +01:00
Andrew Kaster
b3746f9745 AK: Guard inline assembly with ARCH(I386) and provide alternative
For non-x86 targets, it's not very nice to define inline functions in
AK/Memory.h with asm volatile implementations. Guard this inline
assembly with ARCH(I386) and provide portable alternatives. Since we
always compile with optimizations, the hand-vectorized memset and
memcpy seem to be of dubious value, but we'll keep them here until
proven one way or another.

This should fix the Lagom build on native M1 macOS that was reported
on Discord the other day.
2021-05-31 17:29:09 +01:00
Ali Mohammad Pur
2b5732ab77 AK+Kernel: Disallow implicitly lifting pointers to OwnPtr's
This doesn't really _fix_ anything, it just gets rid of the API and
instead makes the users explicitly use `adopt_own_if_non_null()`.
2021-05-31 17:09:12 +04:30
Gunnar Beutner
de0aa44bb6 AK: Remove the m_length member for StringBuilder
Instead we can just use ByteBuffer::size() which already keeps track
of the buffer's size.
2021-05-31 14:49:00 +04:30
Gunnar Beutner
4c32a128ef AK: Fix accidentally-quadratic behavior in StringBuilder
Found by OSS Fuzz:

Related commit: 3908a49661

Co-authored-by: Ben Wiederhake <BenWiederhake.GitHub@gmx.de>
2021-05-31 14:49:00 +04:30
Gunnar Beutner
8f755c9d07 AK: Use ByteBuffer::append for the StringBuilder class
Previously the StringBuilder class would use memcpy() to write
directly into the ByteBuffer's buffer. Instead we should use the
append() method which ensures we don't overrun the buffer.
2021-05-31 14:49:00 +04:30
Gunnar Beutner
425bfabd66 AK: Split the ByteBuffer::trim method into two methods
This allows us to mark the slow part (i.e. where we copy the buffer) as
NEVER_INLINE because this should almost never get called and therefore
should also not get inlined into callers.
2021-05-31 14:49:00 +04:30
Gunnar Beutner
d8b5fa9dfe AK: Remove the public ByteBuffer::trim method
This removes the public trim() method because it is no longer
necessary. Callers can instead use resize().
2021-05-31 14:49:00 +04:30
Gunnar Beutner
5f18cf75c5 AK: Replace ByteBuffer::grow with resize()/ensure_capacity()
Previously ByteBuffer::grow() behaved like Vector<T>::resize().
However the function name was somewhat ambiguous - and so this patch
updates ByteBuffer to behave more like Vector<T> by replacing grow()
with resize() and adding an ensure_capacity() method.

This also lets the user change the buffer's capacity without affecting
the size which was not previously possible.

Additionally this patch makes the capacity() method public (again).
2021-05-31 14:49:00 +04:30
Andrew Kaster
0af192ff8d AK: Handle LEB128 encoded values that are too large for the result type
Previously, we would go crazy and shift things way out of bounds.
Add tests to verify that the decoding algorithm is safe around the
limits of the result type.
2021-05-31 14:25:27 +04:30
Ben Wiederhake
dfd988707c Revert "AK: Fix accidentally-quadratic behavior in StringBuilder"
This reverts commit 2d011961c9.
2021-05-30 21:39:39 +01:00
Tim Schumacher
8c3e4ccd72 AK: Honor variable precision argument when formatting
printf didn't check whether the additional integer variable belongs to
the field width specifier or to the precision specifier, and always
applied it to the field width instead.

Implement the case distinction that we already use in literal width
and precision specifiers for the variable version as well so that
they are correctly attributed.
2021-05-30 18:45:06 +01:00
Edwin Hoksberg
e68780e1ad WebServer: Put dbgln's behind WEBSERVER_DEBUG
These dbgln's caused excessive load in the WebServer process,
accounting for ~67% of the processing time when serving a webpage
with a bunch of resources like serenityos.org/happy/2nd/.
2021-05-30 17:41:56 +01:00
Max Wipfli
a557f83f8c AK: Verify that m_impl is non-null in String::operator[]
This helps to find bugs where null strings are indexed into with
operator[], as this would previously only report a RefPtr null
dereference.
2021-05-30 17:41:49 +01:00
Ben Wiederhake
2d011961c9 AK: Fix accidentally-quadratic behavior in StringBuilder
Found by OSS Fuzz:
#34451 (old bug)

Related commit: 3908a49661
2021-05-30 14:39:30 +01:00
Andrew Kaster
7b4dc590e7 AK+Userland: Use akaster@serenityos.org for my copyright headers 2021-05-30 14:35:34 +01:00
Andreas Kling
c584421592 AK: Make HashTable::operator=(HashTable&&) clear the moved-from table
This is consistent with how other AK containers behave when moved from.
2021-05-30 14:34:32 +02:00
sin-ack
8be98af77c AK: Declare malloc_good_size as extern "C"
This would otherwise cause an error with clang when __serenity__ wasn't
defined.
2021-05-30 11:10:47 +01:00
Andreas Kling
66f3ec687b AK: Move RefCountedBase definitions out-of-line
This dramatically reduces code size since we no longer inline all these
VERIFY() checks everywhere. Appears to be performance neutral.
2021-05-29 20:18:57 +02:00
Andrew Kaster
eae14f4ba6 AK: Extend round_to_power_of_two to types other than unsigned
The previous implementation hardcoded unsigned, when the same logic
easily extends to unsigned long, signed types, and other Integral types.
2021-05-29 17:47:29 +01:00
Brian Gianforcaro
99e23a711d AK+Kernel: Hide AK::adopt_own from usage in the Kernel
We want to discourage folks from using APIs which lull you into a sense
of false safety in terms of OOM. There are cases where you want to force
allocations to succeed or crash, but those should use a more explicit
API than `AK::adopt_own(.)`.
2021-05-29 09:04:05 +02:00
Andrew Kaster
212365130d AK: Add platform macros to detect presence of AddressSanitizer
The ASAN_[UN]POISON_MEMORY_REGION macros can be used to manually notify
the AddressSanitizer runtime about the reachability of instrumented code
accessing a memory region. This is most useful for manually managed
heaps and arenas that do not go directly to malloc or alligned_alloc.
2021-05-28 07:59:41 +02:00
Gunnar Beutner
bacb2dea70 AK: Convince GCC that m_outline_capacity isn't being read
Previously GCC came to the conclusion that we were reading
m_outline_capacity via ByteBuffer(ByteBuffer const&) -> grow()
-> capacity() even though that could never be the case because
m_size is 0 at that point which means we have an inline buffer
and capacity() would return inline_capacity in that case without
reading m_outline_capacity.

This makes GCC inline parts of the grow() function into the
ByteBuffer copy constructor which seems sufficient for GCC to
realize that m_outline_capacity isn't actually being read.
2021-05-27 22:39:25 +02:00
Tim Schumacher
0aaa992c1c LexicalPath: Reset dirname if it's empty
dirname ends up empty if the canonical path only contains one element.

Reset it to the default for relative/absolute paths if that is the case.
2021-05-27 18:21:36 +04:30
Andrew Kaster
505f84daae Kernel+AK: Move UBSanitizer to AK, and to AK namespace
In preparation for copying UBSanitizer to userspace, move the header to
AK :^)
2021-05-27 15:18:03 +02:00
Ali Mohammad Pur
c022b6d74e AK: Add a way to slice from the end of a span 2021-05-27 17:28:41 +04:30
Andrew Kaster
6459c5a713 AK: Explicitly initialize buffer member in ByteBuffer
When compiling the Kernel with Og, the compiler complains that
m_outline_capacity might be uninitialized when calling capacity()

Note that this fix is not really what we want. Ideally only outline
buffer and outline capacity would need initialized, not the entire
inline buffer. However, clang considers the class to not be
default-constructible if we make that change, while gcc accepts it.
2021-05-27 10:21:30 +02:00
Jesse Buhagiar
2b123cc592 AK: Implement AK::Stack 2021-05-26 16:36:53 +04:30
Ali Mohammad Pur
59e01e2813 AK: Define MakeSigned<...>::Type as void in the base struct
This was probably forgotten in the last rewrite, this would make
IsIntegeral<T> not work for floating points.
2021-05-26 15:34:13 +04:30
Matthew Olsson
777c232e16 AK: Add String::repeated(StringView, size_t count) 2021-05-25 00:24:09 +04:30
Andreas Kling
de395a3df2 AK+Everywhere: Consolidate String::index_of() and String::find()
We had two functions for doing mostly the same thing. Combine both
of them into String::find() and use that everywhere.

Also add some tests to cover basic behavior.
2021-05-24 11:59:18 +02:00
Jelle Raaijmakers
2137675047 AK/NumericLimits: Add lowest() for floating-point types 2021-05-22 13:38:34 +01:00
Lenny Maiorani
1c6d2ff21c IntrusiveList: Remove redundant constructor
Problem:
- The constructor is defined to be the default constructor.

Solution:
- Let the compiler generate the destructor by setting it to the
  default.
2021-05-22 10:11:14 +01:00
Jelle Raaijmakers
3dc0657e58 AK/Vector: Constify find_first_index() 2021-05-22 09:34:55 +02:00
Ali Mohammad Pur
6b4d7b6c19 AK: Fix Variant construction from lvalue references
Fixes #7371 and appends its test cases.
2021-05-22 09:34:31 +02:00
Ali Mohammad Pur
3f350c3b65 AK: Remove [[gnu::noinline]] attribute from some variant members
These were left-overs from a debugging session :P
2021-05-22 09:34:31 +02:00
Idan Horowitz
3bc3a7a23a AK: Use calculate_base64_encoded_length in encode_base64
We were accidentally calling calculate_base64_decoded_length instead,
which resulted in extra allocations during the StringBuilder::append
calls that can be avoided.
2021-05-22 08:54:32 +04:30
Gunnar Beutner
c3efae85f2 Games: Add Hearts 2021-05-21 23:38:18 +02:00
Max Wipfli
a72bb34970 AK: Add Utf8View::iterator_at_byte_offset method
This implements a method to get a Utf8CodepointIterator at a specified
byte offset.
2021-05-21 21:57:03 +02:00
Max Wipfli
c1b452f754 AK: Add substring methods to Utf8View
This patch implements a Unicode-safe substring method, which can be used
when offset and length should be specified in actual characters instead
of bytes.

This can be used to mitigate issues where a string is split in the
middle of a UTF-8 multi-byte character, which leads to invalid UTF-8.

Furthermore, it implements to common shorthands for substring methods
which take only an offset and return the substring until the end of the
string.
2021-05-21 21:57:03 +02:00
Max Wipfli
8c19c2f296 AK: Change some argument and return types in Utf8View from int to size_t
This changes the return type of Utf8View::byte_length and the argument
types of substring_view from int to size_t.
2021-05-21 21:57:03 +02:00
Andrew Kaster
a5889b9aad Shell: Hide job times behind SHELL_JOB_DEBUG flag 2021-05-21 12:05:34 +04:30
r-paiva
943f4eb287 LibCore: Let IODevice::can_read_line() buffer until \n or EOF
If a line was larger than 1024 bytes or the file ended without a
newline character, can_read_line would return false.

IODevice::can_read_line() now reads until a newline is found or
EOF is reached.

fixes #5907
2021-05-20 23:53:06 +02:00
r-paiva
edcfbdf4bd AK: Added contains_in_range to Vector
Vector::contains_in_range() allows the search of an element in a given
range on a vector object.
Also added testcases for the new Vector method.
2021-05-20 23:53:06 +02:00
Max Wipfli
3c2565da94 AK: Add UnicodeUtils with Unicode-related helper functions
This introduces the UnicodeUtils file, which contains helper functions
related to Unicode. This is in contrast to StringUtils, whose functions
are not directly related to Unicode and are, in theory,
encoding-agnostic.
2021-05-20 22:10:45 +02:00
Lenny Maiorani
98468ae2d2 Variant: Remove redundant inline keyword
Problem:
- `constexpr inline` is redundant because `constexpr` implies `inline`.

Solution:
- Remove redundancy.
2021-05-20 18:58:18 +02:00
Gunnar Beutner
96b75af5d1 AK: Don't unlink intrusive list elements in the destructor
Removing the element from the intrusive linked list might not be safe
if doing so requires a lock. Instead this is something the caller
should have done so let's verify instead that we're not on any lists.
2021-05-20 09:09:10 +02:00
Lenny Maiorani
d25d4ec0ee Bitmap: De-duplicate bitmasks
Problem:
- Bitmasks are duplicated.
- Bitmasks are C-style arrays.

Solution:
- Move bitmasks to BitmapView.h.
- Change C-style arrays to be AK::Array for added safety.
2021-05-19 23:37:10 +01:00
Maciej Zygmanowski
80077cea86 AK: Add String::find_all() and String::count() 2021-05-19 20:51:51 +01:00
Gunnar Beutner
661d1aa8d1 AK: Add inline storage support for the Function class
This allows us to allocate most Function objects on the stack or as
part of other objects and gets rid of quite a few allocations.
2021-05-19 21:36:57 +02:00
Gunnar Beutner
d954c11f66 Everywhere: Add missing includes for <AK/OwnPtr.h>
Previously <AK/Function.h> also included <AK/OwnPtr.h>. That's about to
change though. This patch fixes a few build problems that will occur
when that change happens.
2021-05-19 21:36:57 +02:00
Timothy Flynn
145e246a5e AK: Allow AK::Variant::visit to return a value
This changes Variant::visit() to forward the value returned by the
selected visitor invocation. By perfectly forwarding the returned value,
this allows for the visitor to return by value or reference.

Note that all provided visitors must return the same type - the compiler
will otherwise fail with the message: "inconsistent deduction for auto
return type".
2021-05-19 20:41:09 +02:00
Lenny Maiorani
0681086cad Time: Remove static from function local constexpr variable
Problem:
- Function local `constexpr` variables do not need to be
  `static`. This consumes memory which is unnecessary and can prevent
  some optimizations.
- C-style arrays are not as safe as AK::Arrays and require the user to
  specify the length of the array manually.

Solution:
- Remove `static` keyword.
- Change from C-style array for AK::Array.
2021-05-19 16:24:02 +02:00
Ali Mohammad Pur
73cb566041 AK: Make vout() log to debug instead of VERIFY()'ing
In case the write was to stderr/stdout, and it just so happened to fail
because of an issue like "the pty is gone", VERIFY() would end up
calling vout() back to write to stderr, which would then fail forever
until the stack is exhausted.
"Fixes" the issue where the Shell would crash in horrible ways when the
terminal is closed.
2021-05-19 09:19:29 +02:00
Gunnar Beutner
598d7f4127 AK: StringBuilder should prefer to use its inline capacity first
Previously StringBuilder would start allocating an external buffer
once the caller has used up more than half of the inline buffer's
capacity. Instead we should prefer to use the inline buffer until
it is full and only then start to allocate an external buffer.
2021-05-18 21:49:10 +02:00
Max Wipfli
f51b0729f5 AK: Implement StringBuilder::append_as_lowercase(char ch)
This patch adds a convenience method to AK::StringBuilder which converts
ASCII uppercase characters to lowercase before appending them.
2021-05-18 21:02:07 +02:00
Ali Mohammad Pur
b6e5c76427 AK: Add deduction guides to Tuple 2021-05-18 18:48:15 +01:00
Ali Mohammad Pur
5bf37d758c AK: Let HashMap export its key and value types 2021-05-18 18:48:15 +01:00
stelar7
24c5b0e81c LibGfx: Add support for DDS images 2021-05-18 08:45:53 +01:00
Gunnar Beutner
c99fd217e2 AK: Make LexicalPath handle relative paths correctly
Previously LexicalPath would consider "." and ".." as equivalent to
"/". This is not true though.
2021-05-18 08:11:21 +02:00
Lenny Maiorani
ebb1d9740e BitmapView: Disable mutations of the underlying Bitmap
Problem:
- `BitmapView` permits changing the underlying `Bitmap`. This violates
  the idea of a "view" since views are simply overlays which can
  themselves change but do not change the underlying data.

Solution:
- Migrate all non-`const` member functions to Bitmap.
2021-05-18 08:10:45 +02:00
Lenny Maiorani
44a9c7c23e AK/PrintfImplementation: Change static constexpr array to function local
Problem:
- Static variables take memory and can be subject to less optimization.
- This static variable is only used in 1 place.

Solution:
- Move the variable into the function and make it non-static.
2021-05-18 08:07:01 +02:00
Gunnar Beutner
3908a49661 AK: Revert removal of StringBuilder::will_append optimization
This was removed as part of the ByteBuffer changes but the allocation
optimization is still necessary at least for non-SerenityOS targets
where malloc_good_size() isn't supported or returns a small value and
causes a whole bunch of unnecessary reallocations.
2021-05-18 08:06:32 +02:00
Linus Groh
61e132ddfa AK: Sort all the debug macros 2021-05-17 22:33:35 +01:00
Ali Mohammad Pur
056be42c0b LibWasm: Start implementing a naive bytecode interpreter
As the parser now flattens out the instructions and inserts synthetic
nesting/structured instructions where needed, we can treat the whole
thing as a simple parsed bytecode stream.
This currently knows how to execute the following instructions:
- unreachable
- nop
- local.get
- local.set
- {i,f}{32,64}.const
- block
- loop
- if/else
- branch / branch_if
- i32_add
- i32_and/or/xor
- i32_ne

This also extends the 'wasm' utility to optionally execute the first
function in the module with optionally user-supplied arguments.
2021-05-17 23:25:30 +02:00
Ali Mohammad Pur
e9b746a723 AK: Include HashTable.h in StringImpl.cpp
This was used without an include, I'm not sure how it didn't break
before :P
2021-05-17 23:25:30 +02:00
Ali Mohammad Pur
1ad6ac1cb4 AK: Include String.h in ScopeLogger 2021-05-17 23:25:30 +02:00
Linus Groh
0aab774343 Everywhere: Fix a bunch of typos 2021-05-17 17:48:55 +01:00
Andreas Kling
bebbeda726 Revert "BitmapView: Disable mutations of the underlying Bitmap"
This reverts commit f25209113f.
2021-05-17 18:29:47 +02:00
Lenny Maiorani
f25209113f BitmapView: Disable mutations of the underlying Bitmap
Problem:
- `BitmapView` permits changing the underlying `Bitmap`. This violates
  the idea of a "view" since views are simply overlays which can
  themselves change but do not change the underlying data.

Solution:
- Migrate all non-`const` member functions to Bitmap.
2021-05-17 18:16:35 +02:00
Andrew Kaster
73adbb319c AK: Don't read past the end in BitmapView::count_in_range()
The current code is factored such that reads to the entirety of the last
byte should be dropped. This was relying on the fact that last would be
one past the end in that case. Instead of actually reading that byte
when it's completely out of bounds of the bitmask, just skip reads that
would be invalid. Add more tests to make sure that the behavior is
correct for byte aligned reads of byte aligned bitmaps.
2021-05-16 21:58:14 +01:00
Andrew Kaster
11214bc94d AK: Don't call memcpy with null argument in ByteBuffer::copy()
This was happening in TestBase64.test_decode, while copying an empty
string.
2021-05-16 21:58:14 +01:00
Liav A
20743e8aed Kernel/Graphics + SystemServer: Support text mode properly
As we removed the support of VBE modesetting that was done by GRUB early
on boot, we need to determine if we can modeset the resolution with our
drivers, and if not, we should enable text mode and ensure that
SystemServer knows about it too.

Also, SystemServer should first check if there's a framebuffer device
node, which is an indication that text mode was not even if it was
requested. Then, if it doesn't find it, it should check what boot_mode
argument the user specified (in case it's self-test). This way if we
try to use bochs-display device (which is not VGA compatible) and
request a text mode, it will not honor the request and will continue
with graphical mode.

Also try to print critical messages with mininum memory allocations
possible.

In LibVT, We make the implementation flexible for kernel-specific
methods that are implemented in ConsoleImpl class.
2021-05-16 19:58:33 +02:00
Gunnar Beutner
53d0150827 AK+Userland: Remove nullability feature for the ByteBuffer type
Nobody seems to use this particular feature, in fact there were some
bugs which were uncovered by removing operator bool.
2021-05-16 17:49:42 +02:00
Gunnar Beutner
fcaf98361f AK: Turn ByteBuffer into a value type
Previously ByteBuffer would internally hold a RefPtr to the byte
buffer and would behave like a reference type, i.e. copying a
ByteBuffer would not create a duplicate byte buffer, but rather
two objects which refer to the same internal buffer.

This also changes ByteBuffer so that it has some internal capacity
much like the Vector<T> type. Unlike Vector<T> however a byte
buffer's data may be uninitialized.

With this commit ByteBuffer makes use of the kmalloc_good_size()
API to pick an optimal allocation size for its internal buffer.
2021-05-16 17:49:42 +02:00
Gunnar Beutner
f0fa51773a AK+Userland: Fix some compiler warnings and make variables const-ref
This fixes a few compiler warnings and makes some variables const-ref
in preparation for the next commit which changes how ByteBuffer works.
2021-05-16 17:49:42 +02:00
Timothy Flynn
ce030ca584 AK+Meta: Add a debug option for Solitaire 2021-05-16 16:37:51 +02:00
Daniel Bertalan
be519022c3 LibVT: Implement new ANSI escape sequence parser
This commit replaces the former, hand-written parser with a new one that
can be generated automatically according to a state change diagram.

The new `EscapeSequenceParser` class provides a more ergonomic interface
to dealing with escape sequences. This interface has been inspired by
Alacritty's [vte library](https://github.com/alacritty/vte/).

I tried to avoid changing the application logic inside the `Terminal`
class. While this code has not been thoroughly tested, I can't find
regressions in the basic command line utilities or `vttest`.

`Terminal` now displays nicer debug messages when it encounters an
unknown escape sequence. Defensive programming and bounds checks have
been added where we access parameters, and as a result, we can now
endure 4-5 seconds of `cat /dev/urandom`. :D

We generate EscapeSequenceStateMachine.h when building the in-kernel
LibVT, and we assume that the file is already in place when the userland
library is being built. This will probably cause problems later on, but
I can't find a way to do it nicely.
2021-05-16 11:50:56 +02:00
Nicholas Baron
aa4d41fe2c
AK+Kernel+LibELF: Remove the need for IteratorDecision::Continue
By constraining two implementations, the compiler will select the best
fitting one. All this will require is duplicating the implementation and
simplifying for the `void` case.

This constraining also informs both the caller and compiler by passing
the callback parameter types as part of the constraint
(e.g.: `IterationFunction<int>`).

Some `for_each` functions in LibELF only take functions which return
`void`. This is a minimal correctness check, as it removes one way for a
function to incompletely do something.

There seems to be a possible idiom where inside a lambda, a `return;` is
the same as `continue;` in a for-loop.
2021-05-16 10:36:52 +01:00
Gunnar Beutner
f89e8fb71a AK+LibC: Implement malloc_good_size() and use it for Vector/HashTable
This implements the macOS API malloc_good_size() which returns the
true allocation size for a given requested allocation size. This
allows us to make use of all the available memory in a malloc chunk.

For example, for a malloc request of 35 bytes our malloc would
internally use a chunk of size 64, however the remaining 29 bytes
would be unused.

Knowing the true allocation size allows us to request more usable
memory that would otherwise be wasted and make that available for
Vector, HashTable and potentially other callers in the future.
2021-05-15 16:30:14 +02:00
Andreas Kling
a4099fc756 AK: Try to avoid String allocation in FlyString(StringView)
If we're constructing a FlyString from a StringView, and we already
have a matching StringImpl in the table, use HashTable::find() to
locate the existing string without creating a temporary String.
2021-05-15 11:01:05 +02:00
Jean-Baptiste Boric
069bf988ed AK: Introduce get_random_uniform()
This is arc4random_uniform(), but inside AK.
2021-05-14 22:24:02 +02:00
Jean-Baptiste Boric
ad7cd05fc1 AK: Fix redefinition of macro inside AK/Platform.h 2021-05-14 22:24:02 +02:00
Andreas Kling
d039542c7c AK: Remove unused STRINGIMPL_DEBUG instrumentation 2021-05-14 17:17:32 +02:00
Andreas Kling
3e603b2f32 AK: Make StringView::hash() constexpr
This required moving string_hash() to its own header so that everyone
can see it.
2021-05-14 15:24:32 +02:00
Gunnar Beutner
a8e6cdc0d8 AK: Avoid allocations in ByteBuffer
Creating a ByteBuffer involves two allocations:

-One for the ByteBufferImpl object
-Another one for the actual byte buffer

This changes the ByteBuffer and ByteBufferImpl classes
so only one allocation is necessary.
2021-05-14 12:51:13 +02:00
Andreas Kling
fccfc33dfb AK: Use move semantics to avoid copying in JSON parser
The JSON parser was deep-copying JsonValues left and right, and it was
all totally avoidable. :^)
2021-05-14 11:54:43 +02:00
Ali Mohammad Pur
df515e1d85 LibCrypto+LibTLS: Avoid unaligned reads and writes
This adds an `AK::ByteReader` to help with that so we don't duplicate
the logic all over the place.
No more `*(const u16*)` and `*(const u32*)` for anyone.
This should help a little with #7060.
2021-05-14 08:39:29 +01:00
Ali Mohammad Pur
bfd4c7a16c AK: Avoid passing nullptr to __buitin_memcpy() in ByteBuffer::grow() 2021-05-14 08:39:29 +01:00
Andrew Kaster
28987d1b56 AK: Add #define for [[gnu::no_sanitize_address]]
This lines up with other attribute global #defines
2021-05-14 08:34:00 +01:00
Gunnar Beutner
a11a1cd4d6 AK: Vector::resize() should initialize new slots for primitive types
We call placement new for the newly added slots. However, we should
also specify an initializer so primitive data types like u64 are
initialized appropriately.
2021-05-14 00:35:57 +02:00
Ali Mohammad Pur
06a1c27e4d AK: Fix Variant's copy constructor trying to delegate to the wrong base
This was forgotten in 4fdbac2.
2021-05-13 19:44:32 +01:00
Brian Gianforcaro
d07309a180 AK: Introduce adopt_ref_if_nonnull(..) to aid in Kernel OOM hardening
Unfortunately adopt_ref requires a reference, which obviously does not
work well with when attempting to harden against allocation failure.
The adopt_ref_if_nonnull() variant will allow you to avoid using bare
pointers, while still allowing you to handle allocation failure.
2021-05-13 08:29:01 +02:00
Brian Gianforcaro
b0fef03e3f AK: Introduce adopt_own_if_nonnull(..) to aid in Kernel OOM hardening
Unfortunately adopt_own requires a reference, which obviously does not
work well with when attempting to harden against allocation failure.
The adopt_own_if_nonnull() variant will allow you to avoid using bare
pointers, while still allowing you to handle allocation failure.
2021-05-13 08:29:01 +02:00
sin-ack
2de11b0dc8 AK: Add LexicalPath::append and LexicalPath::join
This patch adds two new methods to LexicalPath.  LexicalPath::append
appends a new path component to a LexicalPath, and LexicalPath::join
constructs a new LexicalPath from one or more components.

Co-authored-by: Gunnar Beutner <gunnar@beutner.name>
2021-05-12 22:38:20 +02:00
Mart G
b00cdf8ed8 Kernel+LibC: Make get_dir_entries syscall retriable
The get_dir_entries syscall failed if the serialized form of all the
directory entries together was too large to fit in its temporary buffer.

Now the kernel uses a fixed size buffer, that is flushed to an output
buffer when it is full. If this flushing operation fails because there
is not enough space available, the syscall will return -EINVAL. That
error code is then used in userspace as a signal to allocate a larger
buffer and retry the syscall.
2021-05-12 12:50:23 +02:00
Ali Mohammad Pur
02de813950 AK: Add a Tuple implementation
Please don't use this outside of metaprogramming needs, *please*.
2021-05-11 14:09:17 +01:00
Ali Mohammad Pur
4fdbac236d AK/Variant: Deduplicate the contained types
This allows the construction of `Variant<int, int, int>`.
While this might not seem useful, it is very useful for making variants
that contain a series of member function pointers, which I plan to use
in LibGL for glGenLists() and co.
2021-05-11 14:09:17 +01:00
Ali Mohammad Pur
3038b6b7dc AK: Avoid the use of typeinfo in Variant
typeid() and RTTI was a nice clutch to implement this, but let's move
away from the horrible slowness and implement variants using type
indices for faster variants.
2021-05-11 14:09:17 +01:00
Matthew Olsson
8c745ad0d9 LibPDF: Parse page structures
This commit introduces the ability to parse the document catalog dict,
as well as the page tree and individual pages. Pages obviously aren't
fully parsed, as we won't care about most of the fields until we
start actually rendering PDFs.

One of the primary benefits of the PDF format is laziness. PDFs are
not meant to be parsed all at once, and the same is true for pages.
When a Document is constructed, it builds a map of page number to
object index, but it does not fetch and parse any of the pages. A page
is only parsed when a caller requests that particular page (and is
cached going forwards).

Additionally, this commit also adds an object_cast function which
logs bad casts if DEBUG_PDF is set. Additionally, utility functions
were added to ArrayObject and DictObject to get all types of objects
from the collections to avoid having to manually cast.
2021-05-10 10:32:39 +02:00
Matthew Olsson
af9a7b1374 AK: Add missing 'const' in Span 2021-05-10 10:32:39 +02:00
Ali Mohammad Pur
aa4d8d26b9 LibWasm: Start implementing a basic WebAssembly binary format parser
This can currently parse a really simple module.
Note that it cannot parse the DataCount section, and it's still missing
almost all of the instructions.
This commit also adds a 'wasm' test utility that tries to parse a given
webassembly binary file.
It currently does nothing but exit when the parse fails, but it's a
start :^)
2021-05-08 22:14:39 +02:00
Ali Mohammad Pur
56a6d7924e AK: Let Result<T, E> know its Value and Error types
It's much easier to ask for T::ValueType than for
RemoveReference<decltype(declval<T>().release_value())>
2021-05-08 22:14:39 +02:00
Ali Mohammad Pur
62af7c4bdf AK+LibCpp: Remove DEBUG_SPAM in favour of per-application defines
What happens if one file defines DEBUG_SPAM, and another doesn't,
then we link them together and get ODR violations? -- @ADKaster
2021-05-08 22:14:39 +02:00
Ali Mohammad Pur
080f2c0e3e AK: Add an optional 'extra' descriptive field to ScopeLogger
Often it's easier to know what the functions are doing with a unique
name next to the function's name :)
2021-05-08 22:14:39 +02:00
Itamar
8a01167c7d AK: Add missing GenericTraits<NonnullRefPtr>
This enables us to use keys of type NonnullRefPtr in HashMaps and
HashTables.

This commit also includes fixes in various places that used
HashMap<T, NonnullRefPtr<U>>::get() and expected to get an
Optional<NonnullRefPtr<U>> and now get an Optional<U*>.
2021-05-08 18:10:56 +02:00
Itamar
1da0d402b7 AK: Add constructors to Optional that accept non const qualified inputs 2021-05-08 18:10:56 +02:00
Itamar
484823e9d5 AK: Add a non-const overload to HapMap::get()
Additionally, the const version of get() returns Optional<ConstPeekType>
for smart pointers.

For example, if the value in the HashMap is OwnPtr<u32>,
HashMap::get() const returns Optional<const u32*>.
2021-05-08 18:10:56 +02:00
Itamar
b816bd0806 AK: Add ConstPeekType to Traits
Also, the PeekType of smart pointers is now T* instead of const T*.

Note: This commit doesn't compile, it breaks HashMap::get() for some
types. Fixed in the next commit.
2021-05-08 18:10:56 +02:00
Jesse Buhagiar
4807d32139 LibGL: Implement a basic OpenGL 1.x compatible library
This currently (obviously) doesn't support any actual 3D hardware,
hence all calls are done via software rendering.

Note that any modern constructs such as shaders are unsupported,
as this driver only implements Fixed Function Pipeline functionality.

The library is split into a base GLContext interface and a software
based renderer implementation of said interface. The global glXXX
functions serve as an OpenGL compatible c-style interface to the
currently bound context instance.

Co-authored-by: Stephan Unverwerth <s.unverwerth@gmx.de>
2021-05-08 10:13:22 +02:00
Stephan Unverwerth
0a557d65a0 AK: Add epsilon() to NumericLimits for float, double, long double 2021-05-08 10:13:22 +02:00
Andreas Kling
834b6508d7 AK: Remove StringBuilder::appendf()
All users have been converted to using AK::Format via appendff().
2021-05-07 21:12:09 +02:00
Valtteri Koskivuori
1069979ddf AK: Implement Span::starts_with()
Useful for checking for contents at the start of a span.
2021-05-07 11:46:53 +01:00
Ali Mohammad Pur
da68c4580c AK: Make Checked<T> check for division overflow as well
Signed integer overflow can occur with division when the RHS is -1,
as the negative values' range is one larger than the positives.
2021-05-07 09:26:11 +02:00
Brian Gianforcaro
67322b0702 Tests: Move AK tests to Tests/AK 2021-05-06 17:54:28 +02:00
AnotherTest
ba6c9423b8 AK: Implement printf fraction length specification for strings
This adds support for '%.20s' and friends :^)
2021-05-06 15:20:31 +01:00
Ali Mohammad Pur
a51113c58e AK: Add a Variant<Ts...> implementation
Also adds an AK::Empty struct, because 'empty' variants are useful, but
this implementation leaves that to the user (i.e. a variant cannot
actually be empty, but it can contain an instance of Empty - i.e. a
byte).
Note that this is more of a constrained Any type, but they basically do
the same things anyway :^)
2021-05-05 19:02:51 +02:00
Ali Mohammad Pur
ab03c6fadf AK: Export integer_sequence_generate_array() 2021-05-05 19:02:51 +02:00
Ali Mohammad Pur
b361793ad8 AK: Add min() and max() methods to Array<T, N>
...That are only defined when min() and max() are defined on the
elements.
2021-05-05 19:02:51 +02:00
Ali Mohammad Pur
d288f6654e AK: Make LEB128 capable of reading into any type
And not just ssize_t/size_t.
This is useful in cases where the output size is supposed to be larger
than size_t.
2021-05-04 22:33:35 +02:00
Ali Mohammad Pur
48260b5054 AK: Move the LEB128 logic to AK and make it usable with InputStream 2021-05-04 22:33:35 +02:00
Ali Mohammad Pur
415fd4d2ec AK: Make DistinctNumeric constexpr-capable 2021-05-04 21:32:15 +02:00
Gunnar Beutner
56ee4a1af2 AK: Silence -Wmaybe-uninitialized warning
Adding -fno-semantic-interposition to the GCC command
line caused this new warning.

I don't see how output.data() could be uninitialized here. Also,
commenting out the ensure_capacity() call for the Vector
also gets rid of this warning.
2021-05-03 08:42:39 +02:00
Tobias Christiansen
4016e04061 AK: Move bijective-base-conversion into AK/String
This allows everybody to create a String version of their number
in a arbitrary bijective base. Bijective base meaning that the mapping
doesn't have a 0. In the usual mapping to the alphabet the follower
after 'Z' is 'AA'.
The mapping using the (uppercase) alphabet is used as a standard but
can be overridden specifying 'base' and 'map'.

The code was directly yanked from the Spreadsheet.
2021-05-01 01:19:40 +02:00
Gunnar Beutner
ad688ffc73 AK: Make dbgln log the thread ID
This makes debugging multi-threaded programs easier.
2021-04-29 23:12:05 +02:00
Andreas Kling
3d4afe7614 Everywhere: "indexes" => "indices"
I've wasted a silly amount of time in the past fretting over which
of these words to use. Let's just choose one and use it everywhere. :^)
2021-04-29 22:23:52 +02:00
Andreas Kling
7ae7170d61 Everywhere: "file name" => "filename" 2021-04-29 22:16:18 +02:00
Sahan Fernando
c3cf739b94 AK: Make AK::Vector expose allocation failures in API 2021-04-29 09:02:58 +02:00
Linus Groh
649d2faeab Everywhere: Use "the SerenityOS developers." in copyright headers
We had some inconsistencies before:

- Sometimes "The", sometimes "the"
- Sometimes trailing ".", sometimes no trailing "."

I picked the most common one (lowecase "the", trailing ".") and applied
it to all copyright headers.

By using the exact same string everywhere we can ensure nothing gets
missed during a global search (and replace), and that these
inconsistencies are not spread any further (as copyright headers are
commonly copied to new files).
2021-04-29 00:59:26 +02:00
Mart G
c9f3cc6dcc AK: Guarantee a maximum stack depth for dual_pivot_quick_sort
When the two chosen pivots happen to be the smallest and largest
elements of the array, three partitions will be created, two of
size 0 and one of size n-2. If this happens on each recursive call
to dual_pivot_quick_sort, the stack depth will reach approximately n/2.

To avoid the stack from deepening, iteration can be used for the
largest of the three partitions. This ensures the stack depth
will only increase for partitions of size n/2 or smaller, which
results in a maximum stack depth of log(n).
2021-04-28 21:38:48 +02:00
Mart G
67b0d04315 AK: Change pivot selection of dual_pivot_quick_sort
Picking the first and last elements as pivots makes it so that
a sorted array is the worst-case input for the algorithm.

This change instead picks pivots at approximately 1/3 and 2/3 in
the array. This results in desired performance for sorted arrays.

Of course this only changes which inputs result in worst-case
performance, but hopefully those inputs occur less frequently than
already sorted arrays.
2021-04-28 21:38:48 +02:00
Jean-Baptiste Boric
7d84f09e7e Userland: Move non-standard math constants from math.h 2021-04-27 23:06:16 +02:00
Gunnar Beutner
f57c57966b AK: Fix argument type for JsonArray::at and JsonArray::operator[] 2021-04-26 17:13:55 +02:00
Linus Groh
dbe72fd962 Everywhere: Remove empty line after function body opening curly brace 2021-04-25 20:20:00 +02:00
sin-ack
bb096429ad Tests: Remove 4chan catalog JSON from tree
According to kling, it was "an early stress test for the JSON decoder"
and can be removed now.
2021-04-25 10:15:15 +02:00
Brian Gianforcaro
87724b3d09 AK: Add default constructor to SourceLocation 2021-04-25 09:38:27 +02:00
Andrew Kaster
35c0a6c54d AK+Userland: Move AK/TestSuite.h into LibTest and rework Tests' CMake
As many macros as possible are moved to Macros.h, while the
macros to create a test case are moved to TestCase.h. TestCase is now
the only user-facing header for creating a test case. TestSuite and its
helpers have moved into a .cpp file. Instead of requiring a TEST_MAIN
macro to be instantiated into the test file, a TestMain.cpp file is
provided instead that will be linked against each test. This has the
side effect that, if we wanted to have test cases split across multiple
files, it's as simple as adding them all to the same executable.

The test main should be portable to kernel mode as well, so if
there's a set of tests that should be run in self-test mode in kernel
space, we can accomodate that.

A new serenity_test CMake function streamlines adding a new test with
arguments for the test source file, subdirectory under /usr/Tests to
install the test application and an optional list of libraries to link
against the test application. To accomodate future test where the
provided TestMain.cpp is not suitable (e.g. test-js), a CUSTOM_MAIN
parameter can be passed to the function to not link against the
boilerplate main function.
2021-04-25 09:36:49 +02:00
Andrew Kaster
89ee38fe5c Tests: Add environment variable for tests only
This is useful for CI where we don't want to spend a minute and a half
benchmarking Vector::append, and we don't have a good way to pass
test-specific arguments yet. :)
2021-04-25 09:36:49 +02:00
Brian Gianforcaro
7a73f11005 LibCpp: Convert ScopeLogger to use AK:SourceLocation
Utilize AK::SourceLocation to get function information into
the scope logger, instead of relying on pre-processor macros.
2021-04-25 09:32:03 +02:00
Brian Gianforcaro
357a13b404 AK: Add a AK::Formatter implementation for AK::SourceLocation 2021-04-25 09:32:03 +02:00
Brian Gianforcaro
0ad29bc3c9 AK: Add SourceLocation support
C++20 added std::source_location, which lets you capture the
callers __FILE__ / __LINE__ / __FUNCTION__ etc as a default
argument to functions.
See: https://en.cppreference.com/w/cpp/utility/source_location

During a bug investigation @ADKaster suggested we could use this
to make the LOCK_DEBUG feature of the kernel more user friendly
and allow it to automatically instrument all call sites.

We then implemented / tested it over discord. :^)

Co-Authored-by: Andrew Kaster <andrewdkaster@gmail.com>
2021-04-24 20:33:00 +02:00
Andreas Kling
b91c49364d AK: Rename adopt() to adopt_ref()
This makes it more symmetrical with adopt_own() (which is used to
create a NonnullOwnPtr from the result of a naked new.)
2021-04-23 16:46:57 +02:00
Idan Horowitz
f90c224fc5 Revert "AK: Remove virtual destructors from non-virtual classes"
This reverts commit 4378d36f67.
2021-04-23 10:26:14 +02:00
Lenny Maiorani
4378d36f67 AK: Remove virtual destructors from non-virtual classes
Problem:
- Some classes have `virtual` destructors despite not having any
  virtual functions. This causes the classes to have a v-table and
  perform extra jumps at destruction time when there is no need.

Solution:
- Remove `virtual` keyword from destructors where there are no other
  virtual functions.
- Remove the destructor completely when the default destructor can be
  used.
2021-04-23 08:28:25 +02:00
Idan Horowitz
1c512a702a AK+Userland: Use idan.horowitz@serenityos.org for my copyright headers 2021-04-22 22:42:38 +02:00
Ali Mohammad Pur
38418fdfdf AK+Userland: Use mpfard@serenityos.org for my copyright headers 2021-04-22 22:19:09 +02:00