Commit Graph

2180 Commits

Author SHA1 Message Date
Musab Kılıç
f6a43c7cf5 AK: Add min and max functions to Statistics 2021-11-06 22:09:25 -07:00
Ben Wiederhake
03526a7f2b AK: Make BumpAllocator work in multi-threaded environments
Fixes #10578.
2021-10-31 18:43:03 +01:00
Daniel Bertalan
fed9cb5d2d AK+Tests: Fix formatting of infinity and NaN values
When I added this code in 1472f6d, I forgot to add tests for it. That's
why I didn't realize that the values were appended to the wrong
FormatBuilder object, so an empty string was returned instead of the
expected "nan"/"inf". This made debugging some FPU issues with the
ScummVM port significantly more difficult.
2021-10-31 12:15:34 +01:00
Andreas Kling
47c140610d AK: Prefix debug log messages with current-time-since-boot
This is very helpful when trying to better understand how long certain
things take. :^)
2021-10-26 01:00:54 +02:00
Leandro Pereira
368e74fdf8 AK: Allow seed value to be specified in string_hash()
For some algorithms, such as bloom filters, it's possible to reuse a
hash function (rather than having different hashing functions) if the
seed is different each time the hash function is used.

Modify AK::string_hash() to take a seed parameter, which defaults to 0
(the value the hash value was originally initialized to).
2021-10-25 23:37:18 +02:00
Andreas Kling
b4c0e27d26 AK: Always inline Optional::release_value()
This allows the compiler to optimize away the VERIFY(m_has_value) in
many cases.
2021-10-25 14:31:46 +02:00
Andreas Kling
b2f15537bb AK: Add fast path for constructing StringImpl from "" literal 2021-10-25 13:29:44 +02:00
Ben Wiederhake
cb868cfa41 AK+Everywhere: Make Base64 decoding fallible 2021-10-23 19:16:40 +01:00
Ben Wiederhake
3bf1f7ae87 AK: Don't crash on invalid Base64 input
In the long-term, we should probably have a way to signal decoding
failure. For now, it should suffice to at least not crash. This is
particularly relevant because apparently this can be triggered while
parsing a PEM certificate, which happens during every TLS connection.

Found by OSS Fuzz
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=38979
2021-10-23 19:16:40 +01:00
Ben Wiederhake
50698a0db4 AK: Prevent accidental misuse of BumpAllocator
In particular, we implicitly required that the caller initializes the
returned instances themselves (solved by making
UniformBumpAllocator::allocate call the constructor), and BumpAllocator
itself cannot handle classes that are not trivially deconstructible
(solved by deleting the method).

Co-authored-by: Ali Mohammad Pur <ali.mpfard@gmail.com>
2021-10-23 19:02:54 +01:00
Ben Wiederhake
5d865d574a AK: Fix BumpAllocator iteration if last object doesn't align
This fixes two bugs:

1. `end_offset` was missing the alignment that might have been
   introduced while computing `base_ptr`.
2. Ignoring point 1, `end_offset` computed the offset of the first byte
   that is outside the current chunk. However, this might be in the
   middle of a (hypothetical) object! The loop treats `end_offset` as if
   it points to the first byte beyond the last (valid) object. So if the
   last few bytes of the chunk are unused, the loop iterates once too
   often.

Found by OSS Fuzz, long-standing issue (since 2021-07-31)
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=38733
(This probably also resolves some other issues that go through
RegexMatcher.)

See also: 0f1425c895
2021-10-23 19:02:54 +01:00
Ben Wiederhake
885b69c877 AK: Check consistency during BumpAllocator allocation 2021-10-23 19:02:54 +01:00
Daniel Bertalan
39a74676bd AK: Avoid temporary String allocation in Formatter<FormatString>
Creating a String object from the formatted data is unnecessary, as it
immediately gets turned into a StringView anyways.

With this change, we will no longer allocate on the heap when printing
`VirtualAddress`, `VirtualRange` and `InodeIdentifier` objects, which is
a step towards stronger OOM hardening.
2021-10-21 22:19:50 +02:00
Daniel Bertalan
018c4e0e7e AK+Kernel: Format DistinctNumeric using the underlying type's formatter
Forcing the formatting to go through `Formatter<FormatString>` is
completely unnecessary, increases code size, performs a String
allocation and prevents us from using the formatting options available
on that type.

This commit also removes explicit formatters from
`BlockBasedFileSystem::BlockIndex` and `Kernel::InodeIndex`, as those
are already covered by the blanket implementation for all
`DistinctNumeric` types.
2021-10-21 22:19:50 +02:00
Linus Groh
805f8496be AK: Add IsPOD<T> template to StdLibExtras 2021-10-21 09:02:23 +01:00
Daniel Bertalan
9869b598d5 AK: Make Span trivially copy-constructible
There is no need to have a user-defined copy constructor that simply
calls the base class's copy constructor. By having the compiler generate
it for us, Span is made trivially copyable, so it can be passed in
registers.
2021-10-17 17:09:58 +01:00
Daniel Bertalan
fccb06b2cd AK: Use UnicodeUtils::code_point_to_utf8 in StringBuilder 2021-10-15 21:50:19 -07:00
Daniel Bertalan
c8367df746 LibC: Implement wcrtomb
This function converts a single wide character into its multibyte
representation (UTF-8 in our case). It is called from libc++'s
`std::basic_ostream<wchar_t>::flush`, which gets called at program exit
from a global destructor in order to flush `std::wcout`.
2021-10-15 21:50:19 -07:00
James Mintram
f4fb637914 Kernel: Split ScopedCritical so header is platform independent
A new header file has been created in the Arch/ folder while the
implementation has been moved into a CPP living in the X86 folder.
2021-10-15 21:48:45 +01:00
James Mintram
545ce5b595 Kernel: Add per platform Processor.h headers
The platform independent Processor.h file includes the shared processor
code and includes the specific platform header file.

All references to the Arch/x86/Processor.h file have been replaced with
a reference to Arch/Processor.h.
2021-10-14 01:23:08 +01:00
James Mintram
af2761600d AK: Add support for ARCH(AARCH64) to Platform.h 2021-10-11 23:41:56 +01:00
Ben Wiederhake
50ad294527 AK: Implement a way to resolve relative paths lexically 2021-10-10 15:18:55 -07:00
Andreas Kling
77f72c7cfe AK: Always inline the RefCountedBase functions 2021-10-08 22:11:39 +02:00
Peter Elliott
39baadcddf AK: Calculate CircularQueue::end() correctly (for real this time)
Both my approach and the previous approach were wrong for different
cases. I've changed the Iterators index from storage-relative to
queue-relative, and it's much simpler and more obviously correct.

fixes #10383
2021-10-08 11:40:06 +02:00
Luke Wilde
49259777ef Kernel: Note if the page fault address is a destroyed smart pointer
While I was working on LibWeb, I got a page fault at 0xe0e0e0e4.
This indicates a destroyed RefPtr if compiled with SANITIZE_PTRS
defined. However, the page fault handler didn't print out this
indication.

This makes the page fault handler print out a note if the faulting
address looks like a recently destroyed RefPtr, OwnPtr, NonnullRefPtr,
NonnullOwnPtr, ThreadSafeRefPtr or ThreadSafeNonnullRefPtr. It will
only do this if SANITIZE_PTRS is defined, as smart pointers don't get
scrubbed without it being defined.
2021-10-07 21:30:13 +02:00
Andreas Kling
5b1f697460 AK+Kernel: Make automatically locking RefPtr & co a kernel-only thing
Some time ago, automatic locking was added to the AK smart pointers to
paper over various race conditions in the kernel. Until we've actually
solved the issues in the kernel, we're stuck with the locking.

However, we don't need to punish single-threaded userspace programs with
the high cost of locking. This patch moves the thread-safe variants of
RefPtr, NonnullRefPtr, WeakPtr and RefCounted into Kernel/Library/.
2021-10-07 19:27:30 +02:00
Ben Wiederhake
f8d7b4daea AK: Add missing headers
Example failure:

IDAllocator.h only pulls in AK/Hashtable.h, so any compilation unit that
includes AK/IDAllocator.h without including AK/Traits.h before it used
to be doomed to fail with the cryptic error message "In instantiation of
'AK::HashTable<T, TraitsForT, IsOrdered>::Iterator AK::HashTable<T,
TraitsForT, IsOrdered>::find(const T&) [with T = int; TraitsForT =
AK::Traits: incomplete type 'AK::Traits<int>' used in nested name
specifier".
2021-10-06 23:52:40 +01:00
Peter Elliott
c515121844 AK: Calculate CircularQueue::end() correctly
Previously end() was only correct when m_head == 0.
2021-10-06 12:31:13 +02:00
Peter Elliott
accf4b338d AK: Expand to_int<i64> to to_int<long> and to_int<long long>
This change also applys to to_uint

On i686 u64 == long long but on x86_64 u64 == long. Therefor on either
arch, one of the instantiations is missed. This change makes sure that
all integer types have an instantiation.
2021-10-05 13:27:25 +03:30
Tim Schumacher
67a579aab0 AK: Add a basic formatter for wchar_t 2021-10-03 11:13:50 +00:00
Andreas Kling
87290e300e AK: Simplify Utf16View::operator==(Utf16View) 2021-10-02 18:32:56 +02:00
Andreas Kling
024367d82e LibJS+AK: Use Vector<u16, 1> for UTF-16 string storage
It's very common to encounter single-character strings in JavaScript on
the web. We can make such strings significantly lighter by having a
1-character inline capacity on the Vectors.
2021-10-02 17:39:38 +02:00
Andreas Kling
77f0e57b27 RequestServer: Don't hide the SIGINFO state dump behind a debug macro
Until we're confident that RequestServer doesn't need this runtime debug
dump helper, it's much nicer if everyone has it built in, so they can
simply send a SIGINFO if they see it acting up.
2021-10-01 20:17:15 +02:00
Nico Weber
5e21759f3d AK: Fix typos 2021-10-01 01:33:43 +01:00
Ali Mohammad Pur
398435277b RequestServer: Use an OwnPtr for cached connections
Otherwise we'd end up trying to delete the wrong connection if a
connection made before us is deleted.
Fixes _some_ RequestServer spins (though not all...).
This commit also adds a small debug mechanism to RequestServer (which
can be enabled by turning REQUEST_SERVER_DEBUG on), that can dump all
the current active connections in the cache, what they're doing, and how
long they've been doing that by sending it a SIGINFO.
2021-09-29 11:47:18 +02:00
Rodrigo Tobar
69b64a6b04 AK: Accept StringView in LexicalPath::join
The first argument for LexicalPath::join was a String const&, which
resulted in an unnecessary memory copy when invoked with a StringView.
Changing the type of the parameter to StringView avoids the extra cost.

This was noticed while working on #10230.
2021-09-28 18:06:06 +03:00
Idan Horowitz
b56b0ba689 AK: Eliminate avoidable strlen call in String::matches
We already know the length of these substrings, so there's no need to
check their lengths using strlen in the StringView(char*) constructor.

This patch also removes an accidental 1-byte OOB read that was left over
from when this method received null-terminated char pointers instead of
string views, as well removes the unnecessary lambda call (two of the
checks were impossible, and this was only called in one place, so we can
just inline it)
2021-09-28 00:31:45 +02:00
Ben Wiederhake
743470c8f2 AK: Introduce ability to default-initialize a Variant
I noticed that Variant<Empty, …> is a somewhat common pattern while
working on #10080, and this will simplify a few use-cases. :^)
2021-09-21 04:22:52 +04:30
Andrew Kaster
61ad239ee0 AK: Remove unnecessary include of <new> for non-__serenity__ builds
We already include `<new>` in AK/kmalloc.h when KERNEL is not defined,
which applies to all non-`__serenity__` builds.
2021-09-20 00:39:46 +00:00
Andrew Kaster
da87497e61 AK+LibC: Remove SERENITY_LIBC_BUILD guard around <initializer_list>
This was required before commit 5f724b6ca1
when we were building LibC before libstdc++ headers were available in
the sysroot. However as noted in that commit, we never actually needed
to be building LibC before libstdc++, so we can go ahead and remove this
ancient hack.
2021-09-20 00:39:46 +00:00
Andrew Kaster
210b0b883b AK: Remove unused ifdef for BUILDING_SERENITY_TOOLCHAIN
The only use of this define was removed in commit
5f724b6ca1, over a year ago.

The define was there to prevent the LibC build we built before libstdc++
from complaining about missing libgcc symbols. However, as noted in that
commit, we never actually needed to build LibC at all.
2021-09-20 00:39:46 +00:00
Andreas Kling
391352c112 AK: Inline all the trivial Utf8View functions
This improves parsing time on a large chunk of JS by ~3%.
2021-09-18 19:54:24 +02:00
Andreas Kling
1be4cbd639 AK: Make Utf8View constructors inline and remove C string constructor
Using StringView instead of C strings is basically always preferable.
The only reason to use a C string is because you are calling a C API.
2021-09-18 19:54:24 +02:00
Mustafa Quraish
27f28998b1 AK/Vector: Add Vector::reverse() method
This reverses the contents of the vector in-place.
2021-09-17 16:56:59 +00:00
Brian Gianforcaro
14eb736e22 AK: Reduce the scope of fraction_string to where it's needed
pvs-studio flagged this a potential optimization, as we only
need to really construct the fraction_string if is_double is
true.
2021-09-16 17:17:13 +02:00
Brian Gianforcaro
c192c303d2 AK: Use default constructor/destructor instead of declaring an empty one
Default implementations allow for more optimizations.
See: https://pvs-studio.com/en/docs/warnings/v832/
2021-09-16 17:17:13 +02:00
Linus Groh
cbdd069279 AK: Rename the local variable in the TRY() macro to avoid name clashes
"result" is a tad bit too generic to provide a clash-free experience -
we found instances in LibJS where this breaks already. Essentially this
doesn't work:

    auto foo = TRY(bar(result));

Because it expands to the following within the TRY() scope:

    {
        auto result = bar(result);
        ...
    }

And that of course fails:

    error: use of ‘result’ before deduction of ‘auto’

The simple solution here is to use a name that is much less likely to
clash with anything used in the expression ("_temporary_result"). :^)
2021-09-15 23:46:53 +01:00
Ali Mohammad Pur
ccb53c64e9 AK: Add an abstraction over multiple disjoint buffers
DisjointChunks<T> provides a nice interface over multiple sequential
Vector<T>'s, allowing the user to iterate over/index into/slice from
said buffers as if they were a single contiguous buffer.
To work with views on such objects, DisjointSpans<T> is provided, which
has the same behaviour but does not own the underlying objects.
2021-09-14 21:33:15 +04:30
Idan Horowitz
30849b10d5 AK: Move the path argument of URL::append_path instead of copying it 2021-09-14 00:14:45 +02:00
Idan Horowitz
d6cfa34667 AK: Make URL::m_port an Optional<u16>, Expose raw port getter
Our current way of signalling a missing port with m_port == 0 was
lacking, as 0 is a valid port number in URLs.
2021-09-14 00:14:45 +02:00
Idan Horowitz
1c9c43785d AK: Add URL::cannot_have_a_username_or_password_or_port
As defined by the URL specification:
https://url.spec.whatwg.org/#cannot-have-a-username-password-port
2021-09-14 00:14:45 +02:00
Idan Horowitz
929af64a67 AK: Change URL::cannot_be_a_base_url, URL::is_valid return type to bool
There's no need to return a const reference (8 bytes) when the value is
always used as a temporary bool (1 byte).
2021-09-14 00:14:45 +02:00
Idan Horowitz
55b67ba7a7 AK: Accept optional url and state override parameters in URLParser
These are required in the specification and used by the web's URL
built-in, this commit also removes the Badge<AK::URL> from URLParser
to allow other classes that need to call the parser directly like the
web's URL built-in to do so.
2021-09-14 00:14:45 +02:00
Idan Horowitz
6fa4fc8353 AK: Add URL::serialize_origin based on HTML's origin definition 2021-09-14 00:14:45 +02:00
James Puleo
ae6862cb2d AK: Remove unimplemented method fill_buffer from UUID 2021-09-13 20:19:34 +02:00
Ali Mohammad Pur
25f43ea0a1 AK: Make Span::operator==() comply with the ISO C++ idea of operator==
This should:
- Accept const& on both sides
- Not involve implicit conversions on either side

otherwise the argument order would be deemed significant, and trip this
warning.
2021-09-13 14:38:53 +04:30
Ali Mohammad Pur
a42c7757d3 AK: Switch Span.h to east-const style 2021-09-13 14:38:53 +04:30
Ali Mohammad Pur
a72eea6408 AK: Give BumpAllocator a single-block cache
This avoid excessive mmap/munmap traffic in normal operation.
2021-09-13 14:38:53 +04:30
Ali Mohammad Pur
913382734c AK: Allow RBTree::find_largest_not_above_iterator() to fail
Previously this function would've crashed if the key failed to match any
entry.
2021-09-13 14:38:53 +04:30
Ali Mohammad Pur
27e3589f61 AK+Kernel: Avoid unescaped control chars in append_escaped_for_json()
Otherwise it could produce invalid JSON.
2021-09-13 14:38:53 +04:30
Ali Mohammad Pur
a21a3c2620 AK: Make traits for NonnullOwnPtr use ptr_hash instead of int_hash
Otherwise they'd be truncating the pointer in 64-bit builds.
2021-09-13 14:38:53 +04:30
Brian Gianforcaro
ff1e5aa935 AK: Add secure_zero() implementation so it can be used on all platforms
Serenity has explicit_bzero() in LibC with the same implementation,
however we need to be able to use this from Lagom on all platforms
that we support building serenity on. I've implemented it in AK for
this reason.
2021-09-13 00:02:42 +02:00
Brian Gianforcaro
871ef7a735 AK+LibCore: Standardize on AK_OS_MACOS instead of __APPLE__
We use our custom platform definitions in most places, remove
the few remaining places we weren't using `AK_OS_MACOS`.
2021-09-12 18:31:10 +02:00
Brian Gianforcaro
54fe0c8855 AK: Add the ability to hash the contents of a AK::HashMap 2021-09-12 16:39:23 +02:00
Peter Elliott
d28459fb11 AK: Escape '"' in escape_html_entities 2021-09-12 12:17:16 +02:00
Idan Horowitz
6704961c82 AK: Replace the mutable String::replace API with an immutable version
This removes the awkward String::replace API which was the only String
API which mutated the String and replaces it with a new immutable
version that returns a new String with the replacements applied. This
also fixes a couple of UAFs that were caused by the use of this API.

As an optimization an equivalent StringView::replace API was also added
to remove an unnecessary String allocations in the format of:
`String { view }.replace(...);`
2021-09-11 20:36:43 +03:00
Idan Horowitz
6d2b003b6e AK: Make String::count not use strstr and take a StringView
This was needlessly copying StringView arguments, and was also using
strstr internally, which meant it was doing a bunch of unnecessary
strlen calls on it. This also moves the implementation to StringUtils
to allow API consistency between String and StringView.
2021-09-11 20:36:43 +03:00
Ben Wiederhake
9413dddb8b AK: Forbid creating StringView from temporary FlyString 2021-09-11 13:22:51 +03:00
Ben Wiederhake
f6d0955a46 AK: Forbid creating StringView from temporary ByteBuffer 2021-09-11 13:22:51 +03:00
Idan Horowitz
6348b63476 Kernel: Add kernelearlyputstr and use it in dbgln in very-early boot
This variant of dbgputstr does not lock the global log lock, as it is
called before the current or any other processor was initialized,
meaning that:
A) The $gs base was not setup yet, so we cannot enter into critical
   sections, and as a result we cannot use SpinLocks
B) No other processors may try to print at the same time anyway
2021-09-10 22:58:08 +03:00
Idan Horowitz
18d2a74e62 AK: Only try and get the Processor::current_id when it was initialized
This caused a null pointer dereference on early boot, since the gs_base
was not set yet.
2021-09-10 22:58:08 +03:00
Ali Mohammad Pur
14c8373eb0 AK+Kernel: Reduce the number of template parameters of IntrusiveRBTree
This makes the user-facing type only take the node member pointer, and
lets the compiler figure out the other needed types from that.
2021-09-10 18:05:46 +03:00
Ali Mohammad Pur
5a0cdb15b0 AK+Everywhere: Reduce the number of template parameters of IntrusiveList
This makes the user-facing type only take the node member pointer, and
lets the compiler figure out the other needed types from that.
2021-09-10 18:05:46 +03:00
Hendiadyoin1
93cf01ad7d AK: Mark HashTable::size_in_bytes() as constexpr 2021-09-10 14:33:53 +00:00
Hediadyoin1
1aa527f5b6 AK: Add OOM safe interface to HashTable/Map
This adds a new HashSetResult only returned by try_set, to signal
allocation failure during setting.
2021-09-10 14:33:53 +00:00
Idan Horowitz
679bde06ed AK: Remove a redundant double find-call in HashMap::ensure
If the value was found there's no reason to search for it again.
2021-09-10 15:26:41 +03:00
Idan Horowitz
0279fb4dd3 AK: Add key getter to IntrusiveRedBlackTreeNode 2021-09-08 19:17:07 +03:00
Idan Horowitz
cb9720baab AK: Set IntrusiveRBTree Node key on insertion instead of construction
This makes the API look much nicer.
2021-09-08 19:17:07 +03:00
Idan Horowitz
1db9250766 AK: Make IntrusiveRedBlackTree capable of holding non-raw pointers
This is completely based on e4412f1f59
and will allow us to convert some AK::HashMap users in the kernel.
2021-09-08 19:17:07 +03:00
sin-ack
f633fb706e AK: Add note about an internal compile error with Optional in GCC 10.3+
This bit me because I accidentally made the destructor for a class which
was wrapped in an Optional private. This causes none of the Optional
destructors to be able to be deduced, which when combined with concepts
causes an internal compile error in GCC 10.3.0+. This commit adds a note
here to make sure that future encounters of this bug does not surprise
people.
2021-09-08 00:37:19 +02:00
Andreas Kling
6ad427993a Everywhere: Behaviour => Behavior 2021-09-07 13:53:14 +02:00
Ali Mohammad Pur
d4e425e52e AK: Use the full name of 'integer_sequence_generate_array' in Variant.h
c27abaabc4 moved this out of the global
namespace, but did not qualify its users.
While this seems to be fine (sometimes, somehow), let's qualify it to
avoid random breakage.
2021-09-06 21:26:47 +02:00
Andreas Kling
b096e85777 AK: Make Json{Array,Object}Serializer ignore append() return values
This is in preparation for making KBufferBuilder::append() and friends
return a KResult. Long-term we should come up with a solution that works
for both kernel and userspace clients of the JSON API.
2021-09-06 18:56:51 +02:00
Ali Mohammad Pur
97e97bccab Everywhere: Make ByteBuffer::{create_*,copy}() OOM-safe 2021-09-06 01:53:26 +02:00
Ali Mohammad Pur
3a9f00c59b Everywhere: Use OOM-safe ByteBuffer APIs where possible
If we can easily communicate failure, let's avoid asserting and report
failure instead.
2021-09-06 01:53:26 +02:00
Ali Mohammad Pur
6606993432 AK: Add OOM-safe ByteBuffer::try_{resize,append,ensure_capacity}() APIs 2021-09-06 01:53:26 +02:00
Brian Gianforcaro
112de58fe0 AK: Add AssertSize utility template to provide rich type size assertions
This type is useful, as the sizes will be visible in the compiler error
messages, as they will be part of the template parameters. This is not
possible with a normal static_assert of the sizeof a type.
2021-09-05 20:08:57 +02:00
Andreas Kling
b4d8e166d8 AK: Add a TRY(expression) macro to simplify the unwrap-or-return pattern
The way we use classes like Kernel::KResultOr<T> and AK::Result<T, E>
makes checking for errors (and short-circuiting returns) quite verbose.

This patch adds a new TRY(expression) macro that either evaluates to
the released result of the expression if successful, or returns the
error if not.

Before:

    auto foo_or_error = get_foo();
    if (foo_or_error.is_error())
        return foo_or_error.release_error();
    auto foo = foo_or_error.release_value();

After:

    auto foo = TRY(get_foo());

The macro uses a GNU C++ extension which is supported by GCC, Clang,
Intel C++, and possibly others. It's not *ideal*, but since it makes our
codebase considerably nicer, let's try(!) it out. :^)

Co-authored-by: Ali Mohammad Pur <mpfard@serenityos.org>
2021-09-05 14:08:12 +02:00
sin-ack
566c5d1e99 AK+Kernel: Move KResult.h to Kernel/API for userspace access
This commit moves the KResult and KResultOr objects to Kernel/API to
signify that they may now be freely used by userspace code at points
where a syscall-related error result is to be expected. It also exposes
KResult and KResultOr to the global namespace to make it nicer to use
for userspace code.
2021-09-05 12:54:48 +02:00
Idan Horowitz
e8f6840471 AK+LibRegex: Disable construction of views from temporary Strings 2021-09-04 21:01:15 +02:00
Andreas Kling
1a71e20f93 AK: Add HashMap::ensure(key, callback)
This function ensures that a key is present in the HashMap.
If it's not present, it is inserted, and the corresponding value
is initialized with whatever the callback returns.

It allows us to express this:

    auto it = map.find(key);
    if (it == map.end()) {
        map.set(it, make_a_value());
        it = map.find(key);
    }
    auto& value = it->value;

Like this:

    auto& value = map.ensure(key, [] { return make_a_value(); });

Note that the callback is only invoked if we have to insert a missing
key into the HashMap. This is important in case constructing the default
value is expensive or otherwise undesirable.
2021-09-04 20:30:56 +02:00
Stephan Unverwerth
a595345e7c AK: Make declaration of std::move and std::forward optional
This introduces a new define AK_DONT_REPLACE_STD that disables our own
implementation of std::move and std::forward. Some ports include both
STL and AK headers which causes conflicts when trying to resolve those
functions. The port can define AK_DONT_REPLACE_STD before including
Serenity headers in that case.
2021-09-04 16:32:54 +02:00
Andreas Kling
7dda773426 AK: Add rvalue-ref qualifiers for Optional's value() and value_or()
This avoids a value copy when calling value() or value_or() on a
temporary Optional. This is very common when using the HashMap::get()
API like this:

    auto value = hash_map.get(key).value_or(fallback_value);
2021-09-04 03:02:08 +02:00
Andreas Kling
0b36499f46 AK: Convert Optional.h to east-const style 2021-09-04 03:02:08 +02:00
Daniel Bertalan
d7b6cc6421 Everywhere: Prevent risky implicit casts of (Nonnull)RefPtr
Our existing implementation did not check the element type of the other
pointer in the constructors and move assignment operators. This meant
that some operations that would require explicit casting on raw pointers
were done implicitly, such as:
- downcasting a base class to a derived class (e.g. `Kernel::Inode` =>
  `Kernel::ProcFSDirectoryInode` in Kernel/ProcFS.cpp),
- casting to an unrelated type (e.g. `Promise<bool>` => `Promise<Empty>`
  in LibIMAP/Client.cpp)

This, of course, allows gross violations of the type system, and makes
the need to type-check less obvious before downcasting. Luckily, while
adding the `static_ptr_cast`s, only two truly incorrect usages were
found; in the other instances, our casts just needed to be made
explicit.
2021-09-03 23:20:23 +02:00
Andreas Kling
eaf88cc78a AK: Rename create<T> => make_ref_counted<T>
And also try_create<T> => try_make_ref_counted<T>.

A global "create" was a bit much. The new name matches make<T> better,
which we've used for making single-owner objects since forever.
2021-09-03 02:36:09 +02:00
Andreas Kling
f4c4b42db9 AK: Move forward() into the std namespace
Same as we already did with move(). This allows compiler diagnostics
and static analyzers like SonarCloud to detect more issues.
2021-09-01 23:02:18 +02:00
Brian Gianforcaro
fee2a03ba9 AK: Pass AK::Format TypeErasedFormatParams by reference in AK::String
This silences a overeager warning in sonar cloud, warning that
slicing could occur with `VariadicFormatParams` which derives from
`TypeErasedFormatParams`.

Reference:
https://sonarcloud.io/project/issues?id=SerenityOS_serenity&issues=AXuVPBW3k92xXUF3qXTE&open=AXuVPBW3k92xXUF3qXTE

This is a continuation of f0b3aa0331.
2021-09-01 18:06:14 +02:00
Brian Gianforcaro
10f5a046c4 AK: Remove dead store from Time:operator+
This is written, but never read again, and is thus useless.
2021-09-01 01:22:14 +02:00
Tobias Christiansen
dcf06a4f40 AK: Add Statistics helper
This patch adds a helper to AK which allows for basic statistical
analysis of values.
The median algorithm is very naive and slow, but it works.
2021-08-31 16:38:22 +02:00